import java.util.*;
import java.util.Arrays;
import java.util.Random;
class EZD_maxTester
{
static int variables[] = new int[10];
static int maximum()
{
Random rand = new Random();
int max = variables[0];
for (int i = 0; i < 10; i++)
{
variables[i] = rand.nextInt(100)+1;
}
for (int a = 0; a < variables.length; a++)
{
if (variables[a] > max)
{
max = variables[a];
}
}
return max;
}
public static void main(String Args[])
{
int option;
do{
Scanner kbReader = new Scanner(System.in);
System.out.println("Integers that will be compared: " + Arrays.toString(variables));
System.out.println("");
System.out.println("The maximum value is " + maximum());
System.out.println("");
System.out.println("Type 1 to run again. Type 0 to end the program.");
option = kbReader.nextInt();
while(option !=1 && option !=0)
{
if (option != 1 && option != 0)
{
System.out.println("Please enter 1 to run again or 0 to end the program.");
option = kbReader.nextInt();
}
}
System.out.println("");
kbReader.close();
}while(option==1);
}
}
(i'm extremely new to coding so my code probably isn't as neat as it could be ! also this is my first time asking a question on here)
we're learning about arrays in class and i have to write a program that finds the largest integer in an array of randomly generated numbers, but when i run the program the array just prints as zeros yet it still gives me the largest value(??). it would print correctly when i used static int variables[] = new Random().ints(10, 0, 100).toArray();
, but it would just print the same set of random numbers when i ran the program again. how do i make it print out the array without zeros masking my numbers?
You are calling System.out.println(Arrays.toString(variables));
before maximum()
- the second actually sets the values in the array, thus they are all zero when you print. Move the print to after the call to maximum();
// System.out.println("Integers that will be compared: " + Arrays.toString(variables));
System.out.println("The maximum value is " + maximum());
System.out.println("Integers that were compared: " + Arrays.toString(variables));