This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 7 years ago.
This program is supposed to find Max and Min in an array,
but it send error:
"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 23
at Mine_EnhancedForLoop.main(Mine_EnhancedForLoop.java:17)"
Does anyone know, what the problem is?
public class Mine_EnhancedForLoop {
public static void main(String[] args) {
int[] array1 = {23, 98, 10, 1, 45, 2, 7, 90};
int max = array1[0];
int min = array1[0];
for (int i : array1){
if (array1[i] > max)
max = array1[i];
else if (array1[i] < min)
min = array1[i];
}
System.out.println("Maximum is: " + max);
System.out.println("Minimum is: " + min);
}
}
In for (int i : array1), i is a value contained in the array, not an index of the array. Therefore array1[i] will throw the exception you got whenever i >= array1.length (which is the case for most of the values in your input array).
If you don't need to know the index of the highest and lowest values, this will work :
for (int i : array1) {
if (i > max)
max = i;
else if (i < min)
min = i;
}
for (int i : array1)
i gives the element of array not the index of array
So in the first iteration
if(array1[23] > max) //gave you ArrayIndexOutOfBoundsException 23
you can do
int[] array1 = {23, 98, 10, 1, 45, 2, 7, 90};
int max = array1[0];
int min = array1[0];
int i=0;
while(i< array1.length){
if (array1[i] > max)
max = array1[i];
else if (array1[i] < min)
min = array1[i];
i++;
}
System.out.println("Maximum is: " + max);
System.out.println("Minimum is: " + min);
Demo
You have to iterate the array elements as:
for (int i=0; i<array1.length; i++){
if (array1[i] > max)
max = array1[i];
else if (array1[i] < min)
min = array1[i];
}
Change the for loop to
for (int i = 0; i < array1.length; i++) {
if (array1[i] > max) {
max = array1[i];
} else if (array1[i] < min)
min = array1[i];
}
}
Because variable i contains 23 when making the comparison here if (array1[i] > max), hence array1[23] gave the exception.
Loop over the array instead:
for (int i = 0; i < array1.length; i++) {
if (array1[i] > max)
max = array1[i];
else if (array1[i] < min)
min = array1[i];
}
Actually it is much easier to use Java 8 streams:
int[] array1 = {23, 98, 10, 1, 45, 2, 7, 90};
System.out.println("Maximum is: " + Arrays.stream(array1).max().getAsInt());
System.out.println("Minimum is: " + Arrays.stream(array1).min().getAsInt());
Related
This question already has answers here:
Finding minimum and maximum in Java 2D array
(4 answers)
Closed 2 years ago.
This is my sample code, I am having trouble with finding the smallest variable. It always returns zero while finding the largest variable works fine.
I have used the same technique but don't know where I am going wrong.
Please help me.
for (int i = 0; i < n; i++) {
smallest = array[i][0];
largest = array[i][0];//set largest to 0 at each round
mean = 0;
System.out.print("Round " + (i + 1) + " Cards: ");
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
if (in.hasNextInt()) {
for (int j = 0; j < m; j++) {
array[i][j] = in.nextInt();
if (array[i][j] > 9) {
System.out.println("Must be between 1-9");
// Arrays.fill(array, null);
j = 0;
System.out.print("Round " + (i + 1) + " Cards: ");
}
// Largest value
if (array[i][j] >= largest) {
largest = array[i][j];
}
// Smallest value
//smallest = array[i][0];
if (array[i][j] < smallest) {
smallest = array[i][j];
}
// total
mean += array[i][j];
}
break;
} else {
in.next();
}
}
//mean calculation
array[i][m] = largest;
array[i][m + 1] = smallest;
array[i][m + 2] = (int) mean / m;
}
This would be a clean way to find the minimum and maximum value in a 2D array.
You can replace i < array.length with m and i < array[i].length with n, if I understood correctly what you were trying to say in the comments.
public static void main(String[] args) {
int[][] array = new int[][]{{7, 8, 32439, 0}, {1, -32, 3, 5}};
int smallest = Integer.MAX_VALUE;
int largest = Integer.MIN_VALUE;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
if (array[i][j] < smallest) {
smallest = array[i][j];
}
if (array[i][j] > largest) {
largest = array[i][j];
}
}
}
System.out.println(smallest);
System.out.println(largest);
}
Output:
-32
32439
public static void printOrganizedList(int[] array) {
int[] temp = array;
System.out.println("N Count");
for(int i = 0; i < array.length; i++) {
int count = 0;
for (int j = 0; j < array.length; j++) {
if(array[i] == array[j]) {
count++;
}
}
for(int n = i-1; n > 0; n--) {
if(array[n] == array[i]) {
break;
}
else {
System.out.println(array[i] + " " + count);
}
}
}
}
This method is made to take in an array and print the duplicate values along with the amount of times it appears in the array. Like this:
-12, 3, -12, 4, 1, 1, -12, 1, 1, 2, 3, 4, 2, 3, -12
The program output should be:
N Count
4 2
3 3
2 2
1 4
-1 1
-12 4
My issue is that no matter what I try the method always spits out the duplicate number along with its amount of repeats as many times as it is repeated. So instead of outputting
"-12 4"
It will output :
"-12 4"
"-12 4"
"-12 4"
"-12 4"
Also I'm aware that there are more advanced and efficient techniques but we haven't learned a lot of that stuff yet.
Thanks in advance.
This can be easily acheived using a HashMap. You can create a Hashmap which would save the element as key and keep the number of occurrences as the value.
public static void printOrganizedList(int[] array) {
System.out.println("N Count");
HashMap<Integer, Integer> countMap = new HashMap<>();
for (int i = 0; i < array.length; i++){
if (countMap.containsKey(array[i])){
int count = countMap.get(array[i]);
countMap.replace(array[i], count + 1);
}else{
countMap.put(array[i], 1);
}
}
Iterator iterator = countMap.entrySet().iterator();
while (iterator.hasNext()){
Map.Entry mapElement = (Map.Entry) iterator.next();
int key = (int) mapElement.getKey();
int count = (int) mapElement.getValue();
System.out.println(key + " " + count);
}
}
Also the time complexity of the program that you have written goes to O(N^2) which can be a really big bottleneck when it comes to large programs.
The above program with hashmap implementation would only cost you O(N)
If the range of the input array is reasonable (for instance, from -12 to 12, not from Integer.MIN_VALUE to Long.MAX_VALUE), you may apply count sorting:
define min and max values in the array,
count the frequencies,
and print out the numbers whose frequencies are greater than 1:
int min = arr[0], max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] < min) min = arr[i];
else if (arr[i] > max) max = arr[i];
}
int[] freq = new int[max - min + 1];
for (int i = 0; i < arr.length; i++) {
freq[min + i]++;
}
for (int i = 0; i < freq.length; i++) {
if (freq[min + i] > 1) {
System.out.println((min + i) + " " + freq[min + i]);
}
}
public static void main(String[] args) {
printOrganizedList(new int[] { -12, 3, -12, 4, 1, 1, -12, 1, 1, 2, 3, 4, 2, 3, -12 });
}
public static void printOrganizedList(int[] array) {
System.out.println("N\tCount");
Map<Integer, Integer> freq = new TreeMap<>();
for (int i = 0; i < array.length; i++) {
if (freq.containsKey(Integer.valueOf(array[i])))
freq.put(Integer.valueOf(array[i]), freq.get(Integer.valueOf(array[i])) + 1);
else
freq.put(Integer.valueOf(array[i]), 1);
}
for (Integer key : freq.keySet()) {
System.out.println(key + "\t" + freq.get(key));
}
}
, output
N Count
-12 4
1 4
2 2
3 3
4 2
, Another solution to match your code
public static void printOrganizedList(int[] array) {
System.out.println("N\tCount");
Arrays.sort(array);
for (int i = 0; i < array.length; i++) {
int count = 0;
// calc freq
for (int j = 0; j < array.length; j++) {
if (array[i] == array[j])
count++;
}
if (count > 1)
System.out.println(array[i] + "\t" + count);
i += count;
}
}
I am currently learning java arrays. Is there any way I can loop through an array of size 9
and do the following
sum1 = array[0] + array[1] + array[2]
sum2 = array[3] + array[4] + array[5]
sum3 = array[6] + array[7] + array[8]
I tried but I could not achieve my desired output.
public class Sum {
public static void main(String[] args) {
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int sum = 0;
for (int i = 0; i < array.length; i++) {
// if it's divisible by 3, reset the sum to 0
if (i > 1 && i % 3 == 0) {
sum = 0;
}
else {
sum += array[i];
System.out.println(sum);
}
}
}
}
you can use
for (int i = 0; i < array.length; i++) {
sum += array[i];
if (i > 0 && (i + 1) % 3 == 0) {
System.out.println(sum);
sum = 0;
}
}
You're resetting the sum to 0 ok, but then not adding the number that you've reset it on (because of your else condition.)
Use for loop by increasing by 3, knowing that the length of the array is a multiple of 3.
public class Sum {
public static void main(String[] args) {
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int sum = 0;
for (int i = 0; i < array.length; i+=3) { // increase i by 3
sum += array[i] + array[i+1] + array[i+2];
System.out.println(sum);
sum=0;
}
}
}
I would like to write a function in java that receives a parameter and returns 1 or 0, in the following conditions:
If the length of the array is odd, return 1 if the sum of the odd numbers is greater than the sum of the even numbers, and 0 otherwise.
If the length of the array is even, check the largest number less or equal then 10. If it is odd, return 1. If it is even, return 0.
For example, using the following arrays:
array1 = {13, 4, 7, 2, 8}
array2 = {11, 7, 4, 2, 3, 10}
The first array returns 1, because there 13(odd) + 7(odd) = 20 is greater then 4 + 2 + 8 = 14.
The second array returns 0, because there 11, 7 are odd but, 10 is greater then 7.
What I already tried, please check below:
public static int isOddHeavy(int[] arr) {
int summationOd = 0;
int summationEv = 0;
for (int i = 0; i < arr.length; i++) {
if (i % 2 != 0) {
summationOd = sumOddEven(arr);
} else {
summationEv = sumOddEven(arr);
}
}
if(summationOd > summationEv) {
return 1;
} else {
return 0;
}
}
public static int sumOddEven(int[] arr) {
int total = 0;
for (int i = 1; i < arr.length; i++) {
total += arr[i];
}
return total;
}
Here is a Java function that does what you want. Just iterate through the array, updating the variables and check your conditions in the end.
public static int yourFunction(int[] arr) {
int sumOdd = 0;
int sumEven = 0;
int maxOdd = 0;
int maxEven = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) {
sumEven += arr[i];
if (maxEven < arr[i] && arr[i] <= 10)
maxEven = arr[i];
}
else {
sumOdd += arr[i];
if (maxOdd < arr[i] && arr[i] <= 10)
maxOdd = arr[i];
}
}
if (arr.length%2 != 0)
return (sumOdd > sumEven) ? 1 : 0;
return (maxOdd > maxEven) ? 1 : 0;
}
So this is an unique question and I would appreciate any help.
The objective:
To count and return an integer of 'distance' from min value to max value.
The list is not sorted and should not be sorted.
Min value might be before max or vise-verse.
In a list of { 2, -5, -7, 8, 22, -10 } answer = 1 (the distance from -10 to 22)
In a list of { 2, -5, -7, 8, 22, -6 } answer = 2 (the distance from -7 to 22)
Thank you for any help.
Just keep track of the corresponding index:
double min = list[0];
int minIndex = 0;
double max = list[0];
int maxIndex = 0;
for (int i =1 ; i < list.length ; i++) {
if(min > list[i]){
min = list[i];
minIndex = i;
}
if(max < list[i]){
max = list[i];
maxIndex = i;
}
}
int res = Math.abs(minIndex - maxIndex);
Keep the indice while finding max and min :
int indMin = 0;
int indMax = 0;
double min = list[0];
double max = list[0];
for (int i =0; i<list.length;i++){
if(min>list[i]){
min=list[i];
indMin = i;
}
if(max<list[i]){
max = list[i];
indMax = i;
}
}
int distance = Math.abs(indMax - indMin);