1

After trying these suggestions for reading int input Scanner is skipping nextLine() after using next() or nextFoo()?

Can't figure out how come the input is not consuming the newline.

This is linux running jdk 11.

import java.util.Scanner;

public class NumbFile {

    public static void main(String[] args) throws Exception {
        int i = 100;
        int powerNumber;
        boolean status = true;

            do {
                try {
                    System.out.print("Type a number: ");
                    Scanner sc = new Scanner(System.in);
                    powerNumber = Integer.parseInt(sc.nextLine());
                    System.out.println(i * powerNumber);
                    sc.close();
                } catch (NumberFormatException exc) {
                    exc.printStackTrace();
                    status = false;
                }

            } while(status);
    }
}

This should stop looping only with no int input.

David Borges
  • 83
  • 2
  • 10
  • 2
    Don't create scanners inside the loop - create it once. You also shouldn't close the scanner when reading from the system input, as this will close the underlying stream (stdin) as well, which isn't going to be helpful – MadProgrammer Sep 08 '19 at 22:54

1 Answers1

2

Remove sc.close();. That closes your Scanner (which should be declared once before your loop), but it also closes System.in (which you can't then reopen).

int i = 100;
boolean status = true;
Scanner sc = new Scanner(System.in);

do {
    try {
        System.out.print("Type a number: ");
        int powerNumber = Integer.parseInt(sc.nextLine());
        System.out.println(i * powerNumber);
    } catch (NumberFormatException exc) {
        exc.printStackTrace();
        status = false;
    }
} while (status);
Elliott Frisch
  • 183,598
  • 16
  • 131
  • 226