Reusing Java Scanner

不打扰是莪最后的温柔 提交于 2020-01-16 08:41:30

问题


Ive written a small Java code to calculate the product of two integers input by the user using Scanner. The user is forced to input integer values. The code is shown below.

import java.util.Scanner;
public class Principal {
    public static void main(String[] args) {
        int x=0,y=0;
        Scanner sc=new Scanner(System.in);
        //Asks for the first number until the user inputs an integer
        System.out.println("First number:");
        while(!sc.hasNextInt()){
            System.out.println("Not valid. First number:");
            sc.nextLine();
        }
        x=sc.nextInt();
        //Asks for the second number until the user inputs an integer
        System.out.println("Second number:");
        while(!sc.hasNextInt()){
            System.out.println("Not valid. Second number:");
            sc.nextLine();
        }
        y=sc.nextInt();
        //Show result
        System.out.println(x+"*"+y+"="+x*y);
    }
}

The loop for the first number works fine. But, the second doesn't: if the user inputs something that is not an integer value, the message "Not valid. Second number:" is shown twice!
First number:
g
Not valid. First number:
2
Second number:
f
Not valid. Second number:
Not valid. Second number:
4
2*4=8

What is the reason for this behaviour? I guess I'm doing something wrong.
I've tried to use two different Scanners (one for each number) and the problem dissapears, but I don't think that creating lots of instances is the correct path.
Can anybody help?

Thanks.


回答1:


Because even after accepting the first int value there is still the newline character to consume,

so change to

x=sc.nextInt();
sc.nextLine();


来源:https://stackoverflow.com/questions/59675833/reusing-java-scanner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!