0

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:

  1. reads a number N (must be greater than 0) from the console
  2. reads N numbers from the console
  3. 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)
4
  • Your for loop continues as long as i < count. But inside the loop, you have count++. i starts out zero, advances by one on each loop iteration; count starts out 1 and advances by one on every loop iteration. How will i ever catch up to count and thus stop the loop? Commented Mar 21, 2020 at 2:13
  • 1
    The assignment doesn't mention arrays, why don't you put the user input into an array? Commented Mar 21, 2020 at 2:49
  • @NomadMaker, yeah It doesn't, but if there's a way to do it without arrays I won't sleep if I don't do it hahah Commented Mar 21, 2020 at 2:56
  • Wouldn't an array be easier? Another way is to start with a temp variable set to a minimum value. You compare this variable to each of the inputs in turn. If an input is larger than this variable, then set the variable to the input. Commented Mar 21, 2020 at 2:59

4 Answers 4

2

First of all, you must import java.util.Scanner when you using Scanner class. I changed some lines of your code, I think this is what you want:

import java.util.Scanner;

public class Solution {
    public static void main(String[] args)  {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt(); // get N (how many numbers)
        int number;
        int max = Integer.MIN_VALUE;

        if (n > 0) {
            for (int i = 0; i < n; i++) {
                number = sc.nextInt(); // get numbers
                if (number > max)
                    max = number;
            }

            System.out.println(max); // print the maximum number

        } else
            System.out.println("Please enter greather than 0 number"); // when n is negative or zero

    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

when using that code with the inputs 9,7,-1,6, the results are 777, which means I'm not only getting one print of the max value and it's also not counting the first input. Also I don't understand how. " int n = sc.nextInt(); " is getting N. I thought it would just get the first input? Could you elaborate? Thanks!
I tested my code with inputs for n=4 and numbers 9, 7, -1, 6 and the result was 9 and it works perfectly. Click to see screenshot I don't understand what is your question. You wanna do that with just one input line? like: 4 9 7 -1 6? 4 for n and others as the numbers?
1

You should read the exercise carefully. First, you must read the N number to determine how many numbers should be read from the console in total.

Also you must handle the exception cases with try-catch blocks that might be thrown during reading or parsing. Try this one:

Playground: https://repl.it/repls/OrnateViolentSoftwaresuite (it might take some time to load).

public static void main(String[] args) {
  Scanner sc = new Scanner(System.in);

  // 1. reads a number N (must be greater than 0) from the console
  int N = 0;

  while(N == 0) {
      try {
          System.out.print("Enter N: ");
          // Use sc.nextLine() instead of .next() or .nextInt()
          N = Integer.parseInt(sc.nextLine());
      } catch (Exception ignored) {}
  }

  // 2.reads N numbers from the console
  int max = Integer.MIN_VALUE;
  for (int i = 0; i < N; i++) {
      while(true) {
          try {
              System.out.printf("Enter %d. number: ", i + 1);
              // determine the max during reading
              max = Math.max(max, Integer.parseInt(sc.nextLine()));
              break; // cancels while(true)
          } catch (Exception ignored) {}
      }
  }

  // 3. Displays the maximum of the N entered numbers
  System.out.printf("The max number is %d\n", max);

  System.out.println("Goodbye!");
  sc.close(); // don't forget to close the resource
}

Update

If you really haven't learned the try / catch yet, then you don't have to use it either. You can simply remove the try-catch blocks from the above code, which should also work (for valid integer inputs only)

e.g. instead of

try {
    System.out.print("Enter N: ");
    // Use sc.nextLine() instead of .next() or .nextInt()
    N = Integer.parseInt(sc.nextLine());
} catch (Exception ignored) {}

just use

System.out.print("Enter N: ");
// Use sc.nextLine() instead of .next() or .nextInt()
N = Integer.parseInt(sc.nextLine());

2 Comments

Never close the scanner.
@WJS Good point. I'm sure, the JVM will take care of it, but at the point where he no longer needs the System.in, it's safe to close it.
0

Ok, this is how I solved it. Initially I wasn't understanding that the first input was the number of inputs. Once I understood that, it became a bit easier.

Basically I had to tell the program to only print the max number after the last input (n-1). Thanks to all that helped.

public class Solution {
    public static void main(String[] args)  {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt(); // get N (how many numbers)  
        int number; 
        int max=Integer.MIN_VALUE; 

        for (int i=0; i<n; i++) {
            number = sc.nextInt();

            if (number>max) {
                max=number ;
            } 

            if (i==n-1)
            System.out.print(max);
            }
    }
            }

Comments

0

Here's a step by step explanation.

  1. Read in a number N (N > 0)
int n = sc.nextInt();
  • Check for N > 0
if (n <= 0) {
   System.out.println("Must be >  0, please try again.");
}

To continually do this, use a while loop.

int n = -1;
while (n <= 0) {
    n = sc.nextInt();
     if (n <= 0) {
        System.out.println("Must be > 0, please try again.");
     }
}
  1. Now find the max.
// initialize to first value
int max = sc.nextInt();
  1. Now get the others
// start from 1 since we already have a value
for(i = 1; i < n; i++) {
   int v = sc.nextInt();
   // if current value is greater than max
   // replace max with current value
   if (v > max) {
       max = v;
   }
}

  1. Print the answer.
System.out.println("max = " + max);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.