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.

1
  • 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 Commented Sep 8, 2019 at 22:54

1 Answer 1

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); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.