如何解决密码输入中的else / if问题? [英] How to solve the else/if problems in password input?

查看:183
本文介绍了如何解决密码输入中的else / if问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个用户可以登录的程序。下面你看到我为密码输入编写的一些代码,但是第二个如果它们没有正常工作。

I wrote a program that users can login. Below u see some codes that I wrote for the password input but the second if of them does not work properly.

请帮我找到问题所在。为什么它不起作用?

Please help me to find the problem. Why it does not work?

import java.util.Scanner;

public class Password {

    public static void main(String[] args) {
        Scanner passwordInput = new Scanner(System.in);
        System.out.print("Please enter your password: ");
        int builtInPassword = 1254;

        if (passwordInput.hasNextInt() && passwordInput.nextInt() == builtInPassword) {
            System.out.println("Your password is correct.");
        } else if (passwordInput.hasNextInt() && passwordInput.nextInt() != builtInPassword) {
            System.out.println("The password entered is incorrect");
        } else {
            System.out.println("Sorry, please enter the right format");
        }
    }
}


推荐答案

scanner.hasNextInt()检查值是否为int,但不消耗该值。但在您的代码中pasword not matching案例扫描程序将通过两个ifs和两个 hasNextInt()调用。因此,如果它将返回错误值,则为秒。

scanner.hasNextInt() check the value is int or not, but its not consume the value. but in your code "pasword not matching" case scanner will go through two ifs and two hasNextInt() callings. therefore in second if it will return false value.

您可以使用以下例外更正和优化代码。

you can correct and optimize you code using exceptions as follow.

try {
     if(passwordInput.nextInt()==builtInPassword){
         System.out.println("Your password is correct.");
     }else{
         System.out.println("The password entered is incorrect");
     }
 } catch (InputMismatchException e) {
     System.out.println("Sorry, please enter the right format");        
 }

这篇关于如何解决密码输入中的else / if问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆