avoid Negative Array Size Exception with try, catch and throw - arrays

The following Java code:
public class SomeClass {
int[] table;
int size;
public SomeClass(int size) {
this.size = size;
table = new int[size];
}
public static void main(String[] args) {
int[] sizes = {5, 3, -2, 2, 6, -4};
SomeClass testInst;
for (int i = 0; i < 6; i++) {
testInst = new SomeClass(sizes[i]);
System.out.println("New example size " + testInst.size);
}
}
}
The first two instances of SomeClass, which have size 5 and 3, will be created without a problem. However, when the constructor SomeClass is called with an argument of -2, a run time error is generated: NegativeArraySizeException.
how can i modify the above code so that it behaves more robustly by using try, catch and throw. The main method should catch this exception and print a warning message then continue execution of the loop.
im a java newbie so would appreciate any help.
thanks

make the class constructor throw the error and catch it in the main class , like this :
public class SomeClass {
int[] table;
int size;
public SomeClass(int size) throws NegativeArraySizeException{
this.size = size;
table = new int[size];
}
public static void main(String[] args) {
int[] sizes = {5, 3, -2, 2, 6, -4};
SomeClass testInst;
for (int i = 0; i < 6; i++) {
try {
testInst = new SomeClass(sizes[i]);
System.out.println("New example size " + testInst.size);
}
catch (NegativeArraySizeException err) {
System.out.println(err.toString());
}
}
}
}
the output would be

Related

Calling array method in main class

How can i call runningSum method in main with new array of intigers so it return result?
class Main {
public static void main(String[] args) {
}
public int[] runningSum(int[] nums) {
int[] result = new int[nums.length];
result[0] = nums[0];
for (int i = 1; i < nums.length; i++) {
result[i] = result[i - 1] + nums[i];
}
return result;
}
}
I have no idea how to call it.
Add static modifier to your runningSum method. example
public static void main(String[] args) {
int[] myNum = {10, 20, 30, 40};
int[] result = runningSum(myNum);
for (int item : result){
System.out.println(item);
}
}
public static int[] runningSum(int[] nums) {
int[] result = new int[nums.length];
result[0] = nums[0];
for (int i = 1; i < nums.length; i++) {
result[i] = result[i - 1] + nums[i];
}
return result;
}

Im trying to get the index of element if the user input number is present in the array. But when give the input i get he same number as output

import java.util.Arrays;
import java.util.Scanner;
public class RemoveElement {
public static void main(String[] args) {
int [] myarray2 = {1,2,3,4,15,6,7,8,9,34,50};
Scanner input2 = new Scanner(System.in);
System.out.println("Enter you no form 1 to 9");
int num2 = input2.nextInt();
for (int i = 0; i < myarray2.length; i++) {
if( num2 == i) {
myarray2 [i] = (myarray2[i - 1]);
System.out.println(myarray2[i]);

Finding Second duplicate element in an array in java

Hi Everyone, i am new to the programming world, can you please help me in finding second duplicate element in an array. i have tried but its not working.
public class FindSecondDuplicate {
public static void main(String[] args) {
int[] intArray = { 6,4,2,3,4,6,8};
int count=0;
Set<Integer> set=new LinkedHashSet<>();
for(int no:intArray)
{
if(set.add(no)==false)
{
count=count+1;
if(count==2)
{
System.out.println(no);
break;
}
}
else
{
set.add(no);
}
}
}
}
I think what you are trying to do can be accomplished using
public static void main(String[] args) {
int[] intArray = {6, 4, 2, 3, 4, 6, 8};
int count = 0;
Map<Integer, Integer> repeatCounter = new HashMap<>();
for (int i : intArray) {
if (repeatCounter.containsKey(i)) {
int repeatedNTimes = repeatCounter.get(i);
repeatCounter.put(i, repeatedNTimes + 1);
}else{
repeatCounter.put(i, 1);
}
}
for (int i : intArray) {
if (repeatCounter.get(i) == 2) {
count++;
if (count == 2) {
System.out.println(i);
break;
}
}
}
}
Find 2nd/3rd or any duplicate with Set Interface
public static void main(String[] args){
int[] array = {3, 12, 9, 3, 8, 3, 12, 4, 7, 8};
int find_duplicate = 3;
// Add all duplicates to set
Set<Integer> storeDuplicates = new LinkedHashSet<>();
for (int i = 0; i < array.length-1; i++){
for (int j = i+1; j < array.length; j++){
if (array[i] == array[j]){
storeDuplicates.add(array[i]);
}
}
}
// Traverse set for find the 2nd/3rd/any other duplicate
int count = 0;
for (int i : storeDuplicates){
count++;
if (count == find_duplicate) System.out.println(find_duplicate+" duplicate is : "+i);
}
}

Counting Number of Unique Numbers in int Array

Trying to get number of unique(non duplicated) numbers of an array via a static method.
For example the array is {1,1,2,4,5,5,7,78,89}
the output would be 7.
public class UniqueNumbes {
public static void main(String[] args) {
int[] test = {1, 2, 4, 5, 10, 30, 20, 1};
int num = numUnique(test);
System.out.println(num);
}
public static int numUnique(int[] list){
int count= 0;
int fin =list.length;
Arrays.sort(list);
for (int i = 0; i<=list.length; i++){
if(list[i]==list[i-1])
count++;
}
return fin-count;
}
}
Put everything in a set and return the size of the set.
import java.util.HashSet;
import java.util.Set;
public class UniqueNumbes {
public static void main(String[] args) {
int[] test = { 1, 2, 4, 5, 10, 30, 20, 1 };
int num = numUnique(test);
System.out.println(num);
}
public static int numUnique(int[] list) {
// java.util.Set
// "A collection that contains no duplicate elements."
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < list.length; i++) {
set.add(list[i]);
}
return set.size();
}
}

Null Pointer Exception in array passed class

So I have a project that requires a generic class that extends Number and also finds the largest and smallest value in the array, the average of all the values, and the size of the array. This seems easy enough to implement, but I have a problem before even putting the generic part of this in place, I get a runtime error of Null Pointer Exception at x.length, regardless of which method I call, always in the same place.
import java.util.Comparator;
public class test
{
public int x[];
public test(int x[])
{
}
public void setx(int newx[])
{
x = newx;
}
public int[] getx()
{
return x;
}
public int findSmallest()
{
int i = 0;
int temp = x[i];
while (i < x.length)
{
i++;
if(x[i] < temp)
{
temp = x[i];
}
else
{
}
}
return temp;
}
public int findLargest()
{
int i = 0;
int temp = x[i];
while (i < x.length)
{
i++;
if(x[i] > temp)
{
temp = x[i];
}
else
{
}
}
return temp;
}
public double findMean()
{
int i = 0;
double sum = 0.0;
double avg = 0.0;
while (i < x.length)
{
sum += x[i];
i++;
}
avg = sum / x.length;
return avg;
}
public int findTotal()
{
int i = x.length;
return i;
}
public static void main (String args[])
{
int[] ia = {1, 2, 3, 4, 5, 6};
test intTest = new test(ia);
System.out.println(intTest.findTotal());
}
}
Any help on how to fix this would be amazing.
You forgot use the setx method in the constructor. You're passing the integer array to constructor but not actually initializing the integer array inside the class. You can do this by calling the setx method in your constructor and passing the integer array x to setx method.
Hope this helps.

Resources