gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:08:13 24 4
gpt4 key购买 nike

我对 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com