I've searched for answers to this specific question, but haven't been able to find anything. I need to find the maximum and minimum of the input numbers but the values I need are inside the for loop and I can't figure out how to use them outside of it.
System.out.print("How many numbers do you want to input?");
int totalNumbers = console.nextInt();
int minMax = 0;
for(int i = 1; i <= totalNumbers; i++){
System.out.print("Number " + i + ": ");
int inputNumbers = console.nextInt();
}
System.out.println();
int smallest = Math.min(minMax);
System.out.println("Smallest = " + smallest);
int largest = Math.max(minMax);
System.out.println("Largest = " + largest);
I don't need changed code just something that will get me on the right track.Thank you!
Define the function, max_num, which accepts a list as input. Define the variable, max_val, which has the first element of the list posited in it. Create a for loop, which iterates through the length of the list. If the element in the list is more than max_val then max_val becomes the value of that element.
If you want to use a loop, then loop with the current max value and check if each element is larger, and if so, assign to the current max. @TheodrosZelleke for i in range(len(list)): # for loop iterates through it . That's an explicit way of repeating something for the length of the list.
Can you notice the problem with the following loop?
for(int i = 1; i <= totalNumbers; i++){
System.out.print("Number " + i + ": ");
int inputNumbers = console.nextInt();
}
You are running the loop totalNumbers
times and every time you create a new int
with name inputNumbers
and store the value received from console. Also where are you changing the value of minMax
? Also Math.min(or max)
does not take single paramtere and wont even compile.
Now you have few options:
I am not writing any solution as I want you to try it yourself.
The Math.min() and Math.max() methods, according to the oracle documentation, can only compare two values. Importing the values into an array, and then performing operations on the array, should allow you to find minimums and maximums, as well as any other data operation quite easily.
int[] numbers = new int[totalNumbers];
for (int i = 0; i < totalNumbers; i++) {
numbers[i] = console.nextInt();
}
//Other Operations
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With