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