我最近开始了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");
}
发布于 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");
}
}
}
发布于 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");
}
}
发布于 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
}
https://stackoverflow.com/questions/52045381
复制相似问题