gpt4 book ai didi

java - 循环不能正常工作

转载 作者:行者123 更新时间:2023-12-01 06:32:58 24 4
gpt4 key购买 nike

我的程序目前遇到问题,它无法正确循环,请帮助我解决。代码如下。提前致谢!

import java.util.Scanner;
import javax.swing.JOptionPane;
import javax.swing.*;
public class Wewe{
public static void main(String[]args){
Scanner inp = new Scanner(System.in);
boolean tryAgain;
do{
System.out.print("\nInput username: ");
String user = inp.nextLine();
System.out.print("\nInput password: ");
String pass = inp.nextLine();
if(user.equals("admin") && pass.equals("admin")){
System.out.print("Success!");
tryAgain = true;
}
if(user!="admin" && pass!="admin"){
JOptionPane.showMessageDialog(null, "Try again! Invalid username or password!","Error Logging-In", JOptionPane.ERROR_MESSAGE);
tryAgain = false;
}
}while(tryAgain = true);
}
}

我想要发生的是,一旦用户输入错误的用户名或密码,程序就会循环。但如果用户输入了正确的用户名或密码,它不会循环询问用户正确的用户名或密码。

最佳答案

尝试这样:

public static void main(String[]args){
Scanner inp = new Scanner(System.in);
boolean tryAgain = true;
do{
System.out.print("\nInput username: ");
String user = inp.nextLine();
System.out.print("\nInput password: ");
String pass = inp.nextLine();
if(user.equals("admin") && pass.equals("admin")){
System.out.print("Success!");
tryAgain = false;
}
if(!user.equals("admin") || !(pass.equals("admin")){
JOptionPane.showMessageDialog(null, "Try again! Invalid username or password!","Error Logging-In", JOptionPane.ERROR_MESSAGE);
tryAgain = true;
}
}while(tryAgain);
}
}

关于java - 循环不能正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14999211/

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