I am practicing Java arrays. I managed to create code to successfully extract array of random ints, sum, max element, difference, shift array to left; however, I cannot extract min element, which always comes up as zero(0) even if the array doesn't contain 0. I researched this issue, and it seems min value is always 0 because the array variables are initialized to 0 due to 0 being default value...however, I cannot find any solution to this issue.
I found several posts from users dealing with this issue as well, however, there doesn't seem to be any solution as far as I can tell...Posts seem to explain issue, but not solve it...I tried playing with the code, such as creating separate for loops for max and min, as well as set the below nested if condition for min loop, but nothing works. if (numArray[i] == 0) {continue;}
package june22;
import java.util.Arrays;
import java.util.Scanner;
public class MoreArrayPractice {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of random values you want in your array: ");
int num = sc.nextInt();
int[] numArray = new int[num];
int total = 0;
int diff = 0;
int max = numArray[0];
int min = numArray[0];
int i, temp;
for (i = 0; i < numArray.length; i++)
{
numArray[i] = (int) (Math.random()*num)+1;
total = total + numArray[i];
System.out.print(numArray[i] + " ");
if (numArray[i] > max) {max = numArray[i];}
if (numArray[i] < min) {
if (numArray[i] == 0) {continue;}
min = numArray[i];}
}
temp = numArray[0];
for (i = 1; i < numArray.length; i++) {
numArray[i - 1] = numArray[i];
} numArray[numArray.length-1] = temp;
System.out.println();
System.out.println("Sum is " + total);
System.out.println("Max is " + max);
System.out.println("Min is " + min);
System.out.println("Array shuffled left is ");
for (i = 0; i < numArray.length; i++) {System.out.print(numArray[i] + " ");}
System.out.println();
for (int a: numArray) {
diff = diff - a; }
System.out.println("Difference of numbers is " + diff);
//correct syntax for printing Array
}
}
min,max,sumetc. and just call them passing in the array. This will make your code far easier to read.