I'm struggling with an exercise to find the max input of N values. I'm being able to print the max value but the exercise asks to print ONLY the max value and I'm not being able to return it from outside the IF statement.
Exercise's instructions:
Write a program that:
- reads a number N (must be greater than 0) from the console
- reads N numbers from the console
- Displays the maximum of the N entered numbers.
My code:
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int i=0;
int count=1;
int max=Integer.MIN_VALUE;
for (i=0; i<count; i++) {
int cur = sc.nextInt();
count++;
if (cur>0){
if (cur>max) {
max=cur ;
System.out.println(max);
}
}
}
}}
In the console I'm getting the desired inputs plus this error
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
forloop continues as long asi < count. But inside the loop, you havecount++.istarts out zero, advances by one on each loop iteration;countstarts out1and advances by one on every loop iteration. How williever catch up tocountand thus stop the loop?