java - 如何在Java中使用Scanner和条件?

标签 java input

我对 java 还很陌生,现在我正在测试 Scanner!这是我的代码:

package Examples;

import java.util.Scanner;

public class UserLogin
{
    public static void main(String[] args)
    {
        Scanner in= new Scanner (System.in);
        System.out.println("Please enter your name!");
        String keyboard= in.nextLine();    

        System.out.println("Welcome: " + keyboard);
        System.out.println("What is your password?");

        Scanner x= new Scanner (System.in);
        int password= x.nextInt();


        if(password ==14567) 
        {
            System.out.println("Password accepted ! you are welcome!");
        }
        else
        {
            System.out.println("Sorry wrong password! Try again");
            Scanner input = new Scanner(System.in);
            int password2=input.nextInt();
            while (password2==password);
            {
                System.out.println("Welcome!!!!");
            }   
        }
    }   
}        

我想要用户名、密码,仅此而已!但我注意到,当我询问姓名时,即使按回车键,它也会立即询问我密码。所以我想确保我得到一个名字。另外,当我询问密码时,我希望在说再见之前能够给他一些机会。

Please enter your name!
michel
Welcome: michel
What is your password?
12345
Sorry wrong password! Try again
12345

这是我在控制台上得到的内容。

谢谢!

最佳答案

首先,您声明了不必要的 scanner 对象。您只需创建一次 scanner 对象。您可以根据需要多次使用该对象获取输入。

第二件事是您需要删除在 while (password2==password); 末尾放置的分号,因为在那里放置一个分号无论while循环的条件是true还是false,都会执行while循环的 block 。

现在要做你想做的事,尝试下面的代码。

public static void main(String[] args) {
 Scanner in= new Scanner (System.in);
 int default_password = 14567;
 int counter = 3;

System.out.println("Please enter your name!");
String keyboard= in.nextLine();    

System.out.println("Welcome: " + keyboard);
System.out.println("What is your password?");

int password= in.nextInt();

if(password == default_password) 
{
    System.out.println("Password accepted ! you are welcome!");

}
else
{
    while(counter > 0)
    {
      System.out.println("Sorry wrong password! Try again");

       password = in.nextInt();

       if (password == default_password)
       {
         System.out.println("Welcome!!!!");
         break;
       }
       else
       {
        counter--;
       }  


    }
    if(counter== 0)
           System.out.println("Good Bye !!");
}

}

关于java - 如何在Java中使用Scanner和条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41081974/

相关文章:

java - 为什么 "=="有时会与 String.trim 一起使用?

java - 使用scanner.useDelimiter读取输入文件的第一个字符不正确

hadoop - 在Hadoop中输入 block 路径

arrays - 将文件读入 Julia 中的一维数组

python - 如何将来自用户的许多输入存储在一个集合中

java - Maven - 在运行时查找依赖项

java - Android 相机,地理标记上的秒数四舍五入为整数

java - Solr-并发提交时OverlappingFileLockException

python - 创建 Ipython magic 命令以将最后一个控制台输入保存到文件中

java - 如何编写当用户仅按 Enter 时执行的方法?