-2

Everything is outputting the way it should but I am getting compiler error. I am doing this on ZyBooks. Can you let me know what I am doing wrong?

import java.util.Scanner;

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

      String inputString = "";
      int inputInt = 0; 
      
      inputString = scnr.next();
      inputInt = scnr.nextInt();
      
      while ( !inputString.equals("Stop")){
         if ( inputInt <= 35) {
            System.out.println( inputString + ": reorder soon");
         }
         inputString = scnr.next();
         inputInt = scnr.nextInt();
         
      }
            
   }
}

The error I am getting: Exception in thread "main"

java.util.NoSuchElementException
    at java.base/java.util.Scanner.throwFor(Scanner.java:937)
    at java.base/java.util.Scanner.next(Scanner.java:1594)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
    at Inputkey.main(Inputkey.java:18)
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
garcGut
  • 37
  • 5
  • 2
    That's a run time error, not a compiler error. – 001 Jun 01 '23 at 17:20
  • 1
    If you want the user to enter "Stop", don't use `inputInt = scnr.nextInt();`. Read a string. Then if it is not "Stop", convert to an int. [How do I convert a String to an int in Java?](https://stackoverflow.com/q/5585779) – 001 Jun 01 '23 at 17:21

1 Answers1

1

instead of inputString = scnr.next(); use inputString = scnr.nextLine();

Java Scanner’s next() and nextLine() methods is that nextLine() returns every character in a line of text right up until the carriage return, while next() splits the line up into individual words, returning individual text Strings one at a time.

import java.util.Scanner;

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

        String inputString = "";
        int inputInt = 0;

        inputString = scnr.nextLine();
        inputInt = Integer.parseInt(scnr.nextLine());

        while ( !inputString.equals("Stop")){
            if ( inputInt <= 35) {
                System.out.println( inputString + ": reorder soon");
            }
            inputString = scnr.nextLine();
            inputInt = Integer.parseInt(scnr.nextLine());
        }
    }
}

Sample Input:

This is stackoverflow
35
stop
999
Stop

scanner.next() will returns This while scanner.nextLine() will returns This is stackoverflow

Rahul
  • 21
  • 5