首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >java :我如何正确地使用if

java :我如何正确地使用if
EN

Stack Overflow用户
提问于 2018-08-28 02:52:16
回答 3查看 64关注 0票数 0

我最近开始了java编程。

但是我有一个问题,我想写一个程序。我有一个密码,我要求程序的用户输入我想要的密码:如果他输入了一个字符串,我告诉他不要输入字符串,如果密码是正确的,并且他输入的密码类型(Int)是正确的,我告诉他OK。

在程序测试中,我的问题是,当我输入了错误的密码,并期望程序告诉我pass错误时,程序什么也不会告诉我!

下面是我的代码:

    int pass = 123 ;

    Scanner password = new Scanner(System.in);
    System.out.println("Please Enter Your Password : ");


    if (password.hasNextInt() && password.nextInt()==pass)
    {
        System.out.println("ok");
    }
    else if (password.hasNextInt()) 
    {
        System.out.println("wrong pass");
    }
    else
    {
        System.out.println("wrong type");
    }
EN

回答 3

Stack Overflow用户

发布于 2018-08-28 03:12:13

尝试这段代码,如果输入不是整数,那么它将抛出NumberFormatException,它将被捕获并显示。

    public static void main(String[] args){
        int pass = 123 ;
        Scanner password = new Scanner(System.in);
        System.out.println("Please Enter Your Password : ");
        String enteredPassword ="";
        if(password.hasNext() && (enteredPassword = password.next()) !=null){
            try{
                if(Integer.parseInt(enteredPassword) == pass){
                    System.out.println("ok");
                }else{
                    System.out.println("wrong pass");
                }
            }catch (NumberFormatException nfe){
                System.out.println("wrong type");
            }

        }
    }
票数 0
EN

Stack Overflow用户

发布于 2018-08-28 03:12:34

你可以使用下面这段代码。

public static void main(String[] args){
        int pass = 123 ;

        Scanner password = new Scanner(System.in);
        System.out.println("Please Enter Your Password : ");


        if (password.hasNextInt())
        {
            if(password.nextInt()==pass) {
                System.out.println("ok");
            }
            else {
                System.out.println("Wrong password");
            }
        }


        else
        {
            System.out.println("wrong type");
        }
    }
票数 0
EN

Stack Overflow用户

发布于 2018-08-28 03:13:34

那一阵子呢?

int MAX_TRIES = 3

int currentTries = 0;
    while (password.hasNextInt() && currentTries < MAX_TRIES) {
        if (password.nextInt()==pass) {
            // OK!
        } else {
            // Wrong!
        }
        currentTries++;
    }

    if (currentTries == MAX_TRIES) {
        // You tried too much
    } else {
        // Password was a string
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52045381

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档