简体   繁体   English

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

[英]if Scanner Boolean statement with 2 nextInt() and hasNextInt() issue

i write this code but when my password is correct i have issue.please guide me.i am new at java coding 我写了这段代码,但是当我的密码正确时我有问题。请指导我。我是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!");
        }

    }

}

You must call hasNextInt() and passwordInput.nextInt() only once to get the password, like this: 您必须只调用一次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!");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM