如果Scanner布尔语句带有2 nextInt()和hasNextInt()问题

时间:2019-01-20 10:05:09

标签: java if-statement boolean java.util.scanner

我写了这段代码,但是当我的密码正确时我遇到了问题。请指导我。我是java编码的新手

import java.util.Scanner;

public class PasswordProjectQ {

    private static Scanner passwordInput;

    public static void main(String[] args) {

        passwordInput = new Scanner(System.in);

        int builtInPassword = 3720118;

        System.out.println("Please enter your password:(just integer)");

        if(passwordInput.hasNextInt() && passwordInput.nextInt() != builtInPassword) {
            System.out.println("You entered the right format \nbut the password is WRONG!");
        }else if(passwordInput.hasNextInt() && passwordInput.nextInt() == builtInPassword) {
            System.out.println("Thanks,your password is correct");
        }else {
            System.out.println("WRONG format!");
        }

    }

}

1 个答案:

答案 0 :(得分:1)

您只需调用一次hasNextInt()passwordInput.nextInt()即可获得密码,如下所示:

if (passwordInput.hasNextInt()) {
    if (passwordInput.nextInt() != builtInPassword) {
        System.out.println("You entered the right format \nbut the password is WRONG!");
    } else {
        System.out.println("Thanks,your password is correct");
    }
} else {
    System.out.println("WRONG format!");
}