简体   繁体   English

循环无法正常工作

[英]Looping does not work properly

I'm currently having a problem with my program it doesn't loop properly please help me with it. 我的程序目前有问题,无法正常循环,请帮助我。 The code is below. 代码如下。 Thanks in advance! 提前致谢!

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);
        }
    }

What I want to happen is that once the user entered wrong username or password the program will then loop. 我想发生的是,一旦用户输入了错误的用户名或密码,程序就会循环运行。 But if the user entered the correct username or password, it wont loop asking the user for the correct one. 但是,如果用户输入正确的用户名或密码,它将不会循环询问用户正确的用户名或密码。

Try it this way: 尝试这种方式:

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);
        }
    }

Change 更改

if(user!="admin" && pass!="admin") to if(user!="admin" || pass!="admin") if(user!="admin" && pass!="admin")if(user!="admin" || pass!="admin")

If you wan to check for Invalid username or password 如果您想检查无效的用户名密码

while(tryAgain == true) change = to == while(tryAgain == true)将=更改为==

= is for assigning value. =用于分配值。

== is for checking condition. ==用于检查条件。

You can also use . 您也可以使用。

while(tryAgain)

This assigns true to tryAgain (which will always evaluate as true , creating an infinite loop): 这将true分配给tryAgain (它将始终评估为true ,从而创建一个无限循环):

} while(tryAgain = true)

So it should be: 因此应该是:

} while(tryAgain == true)

But the whole problem could have been avoided by following good coding style; 但是,遵循良好的编码样式可以避免整个问题。 it should be simply: 它应该很简单:

} while(tryAgain)

Never compare a boolean variable with a boolean constant, just use booleanVar or !booleanVar as your condition 切勿将布尔变量与布尔常量进行比较,仅使用booleanVar!booleanVar作为条件

Set tryAgain to false after success to break the loop. 成功tryAgain设置为false即可打破循环。 Also utilize an else if after checking to see if the user has successfully logged in to skip the check for an invalid user. else if在检查用户是否成功登录后也可以使用else if来跳过对无效用户的检查。 Also as others mention the comparison of String objects should use the equals method. 就像其他人提到的那样,比较String对象应该使用equals方法。 Finally, the while loop should use the comparison operator == instead of the assignment operator = . 最后,while循环应使用比较运算符==而不是赋值运算符=

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 = false;  //Changed to false to break loop
            }else if (!user.equals("admin") && !pass.equals("admin")) {
                            //^Using equals instead of ==, added else if
                JOptionPane.showMessageDialog(null,
                        "Try again! Invalid username or password!",
                        "Error Logging-In", JOptionPane.ERROR_MESSAGE);
                tryAgain = false;
            }
        } while (tryAgain == true); //using == instead of =
    }

Try this: 尝试这个:

public class Wewe{
    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!="admin" && pass!="admin"){
                JOptionPane.showMessageDialog(null, "Try again! Invalid username or password!","Error Logging-In", JOptionPane.ERROR_MESSAGE);
                tryAgain = true;
            }
        } while(tryAgain);
    }
}

There are couple mistakes in your code: 您的代码中有几个错误:

if(user!="admin" && pass!="admin"){ .... tryAgain = false;

Should be: 应该:

if(user!="admin" || pass!="admin"){ ....  tryAgain = true;

Then: 然后:

System.out.print("Success!");
            tryAgain = true;

Should be: 应该:

System.out.print("Success!");
            tryAgain = false;

And finally: 最后:

while(tryAgain = true);

Should be: 应该:

while(tryAgain == true);

or just while(tryAgain); 或者只是while(tryAgain);

Hope that helps! 希望有帮助!

use equals instead of == and 使用等于代替==

 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( !"admin".equals(user) && !"admin".equals(pass)){
            JOptionPane.showMessageDialog(null, "Try again! Invalid username or password!","Error Logging-In", JOptionPane.ERROR_MESSAGE);
        tryAgain = false;
    }
}while(tryAgain = true);

why not just use else and also tryAgain is used wrongly like this 为什么不仅仅使用else并且tryAgain被这样错误地使用

 if(user.equals("admin") && pass.equals("admin")){
            System.out.print("Success!");
            tryAgain = false; //why repeat again
        }
        else{
            JOptionPane.showMessageDialog(null, "Try again! Invalid username or password!","Error Logging-In", JOptionPane.ERROR_MESSAGE);
        tryAgain = true; //ask again
    }

also it whould be 也是谁

while(tryAgain)

Check the below solutions. 检查以下解决方案。

 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.equals("admin") || !pass.equals("admin")){
            JOptionPane.showMessageDialog(null, "Try again! Invalid username or password!","Error Logging-In", JOptionPane.ERROR_MESSAGE);
        tryAgain = false;
    }
}while(tryAgain);
        }
}

You are comparing the two string object with != . 您正在将两个字符串对象与!=进行比较。 That is wrong. 那是错的。

Problem line in your post is: if(user!="admin" && pass!="admin"){ 您帖子中的问题行是: if(user!=“ admin” && pass!=“ admin”){

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 = false;
            }
            else
            {
                JOptionPane.showMessageDialog(null, "Try again! Invalid username or password!","Error Logging-In", JOptionPane.ERROR_MESSAGE);
                tryAgain = true;
            }
        } while(tryAgain == true);
    }
}

There have been a number of changes made. 进行了许多更改。

Firstly, your code has been indented properly - it makes it a lot easier for anyone wanting to help! 首先,您的代码已正确缩进-对于想要帮助的人来说,它变得容易得多!

Secondly, you don't need to have two if statements. 其次,您不需要两个if语句。 You can have an if-else statement because you want to do this: "if the user has the correct name and password, do this. if the user does not have the correct name and password, do this." 您可以使用if-else语句,因为您想这样做:“如果用户具有正确的名称和密码,请执行此操作。如果用户没有正确的名称和密码,请执行此操作。” which can be shortened to "if you user has the correct name and password, do this. if not, do this.". 可以缩写为“如果用户具有正确的名称和密码,请执行此操作。否则,请执行此操作。”。

Thirdly, your do-while loop will continue when tryAgain is true, and so instead of while(tryAgain = true) , you need while(tryAgain == true) , because two equals signs are for comparison whereas a single one is not. 第三,当tryAgain为true时,您的do-while循环将继续,因此需要while(tryAgain == true)代替while(tryAgain = true) while(tryAgain == true) ,因为两个等号用于比较,而一个不相等。

Fourthly, your loop continues whilst tryAgain is true, and so you want tryAgain to be true if they enter the invalid username or password, to continue the loop, and false if they enter the correct one, to stop the loop. 第四,您的循环继续进行,而tryAgain为true,因此,如果他们输入无效的用户名或密码,则tryAgain为true,以继续循环;如果他们输入正确的用户名或密码,则为false,以停止循环。

Also, don't use == to compare strings. 另外,请勿使用==比较字符串。 == checks if two objects are the same, so user will never == "admin". ==检查两个对象是否相同,所以用户永远不会==“ admin”。 Instead, use the equals() method to compare strings. 而是使用equals()方法比较字符串。

public static void main(String[] args) {
    Scanner inp = new Scanner(System.in);
    boolean tryAgain = false;

    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;
            inp.close();
        } else {
            JOptionPane.showMessageDialog(null,
                    "Try again! Invalid username or password!",
                    "Error Logging-In", JOptionPane.ERROR_MESSAGE);
        }
    } while (tryAgain == false);
}

If I understand your desire out of the code, there are a few critical errors: 如果我从代码中了解到您的需求,则将出现一些严重错误:

Firstly, if the username and password "admin" are correct, and you want to end the loop, the code should be: 首先,如果用户名和密码“ admin”正确,并且您想结束循环,则代码应为:

System.out.print("Success!");
        tryAgain = false;

not: 不:

System.out.print("Success!");
            tryAgain = true;

Setting tryAgain to false means that (as your variable (and later code) is written) the program will not "try again" for the user's name and password (the loop will stop looping). 将tryAgain设置为false意味着(在写入变量(和以后的代码)时),程序将不会“重试”用户名和密码(循环将停止循环)。

Also, you have the same discrepancy in the following statement: 另外,您在以下语句中存在相同的差异:

if(user!="admin" && pass!="admin"){
            ...
        tryAgain = false;

tryAgain should be set equal to true here, as you want to program to "try again" for an input name and password ( tryAgain = true ). 在这里,tryAgain应该设置为true,因为您要编程以“重试”输入名称和密码( tryAgain = true )。

Lastly, and most importantly, your loop while command isn't actually doing anything. 最后,最重要的是,while循环实际上并没有执行任何操作。 This: 这个:

while(tryAgain = true);

is defining a variable, not reading information from it. 正在定义变量,而不是从中读取信息。 You must write: 您必须写:

while(tryAgain == true);

if you want to check if tryAgain is set to true. 如果要检查tryAgain是否设置为true。

Besides all that, there are a few bad coding style choices here: 除此之外,这里还有一些不良的编码样式选择:

  • Having two separate if statements where one would work 具有两个单独的if语句,其中一个将起作用
  • Using '!=' when considering a string 考虑字符串时使用'!='
  • Having any '=' when considering a boolean 考虑布尔值时有任何'='

Your two if statements could be combined into: 您的两个if语句可以合并为:

if(user.equals("admin") && pass.equals("admin")){
            System.out.print("Success!");
            tryAgain = false;
}
else{
JOptionPane.showMessageDialog(null, "Try again! Invalid username or password!","Error Logging-In", JOptionPane.ERROR_MESSAGE);
        tryAgain = true;
}

As there is only one way to succeed, there is no reason to not lump everything else into an else clause. 因为只有一种成功的方法,所以没有理由不将其他所有内容都混入else子句中。

And the while statement at the end can simply be written as: 最后的while语句可以简单地写成:

while(tryAgain)

and while tryAgain is true, it will loop. 而tryAgain为true时,它将循环。

The other issue here, is if the user just clicks enter and pass is read as an empty string. 这里的另一个问题是,如果用户仅单击Enter,并且pass被读取为空字符串。 As the program tries to compare the string to "admin" with nothing it will throw back an exception. 当程序尝试不使用任何内容将字符串与“ admin”进行比较时,它将抛出异常。 I would add an initial: 我要添加一个缩写:

if(user.isEmpty() || pass.isEmpty()){
JOptionPane.showMessageDialog(null, "Try again! Invalid username or password!","Error Logging-In", JOptionPane.ERROR_MESSAGE);
        tryAgain = false
}

to the if statement. 到if语句。

Here is what I would do with the code: 这是我要使用的代码:

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 = true;
        do{
        System.out.print("\nInput username: ");
        String user = inp.nextLine();
        System.out.print("\nInput password: ");
        String pass = inp.nextLine();
if(user.isEmpty() || pass.isEmpty()){
    JOptionPane.showMessageDialog(null, "Try again! Invalid username or password!","Error Logging-In", JOptionPane.ERROR_MESSAGE);
            tryAgain = false
    }
    else if(user.equals("admin") && pass.equals("admin")){
            System.out.print("Success!");
            tryAgain = false;
        }
        else{
            JOptionPane.showMessageDialog(null, "Try again! Invalid username or password!","Error Logging-In", JOptionPane.ERROR_MESSAGE);
        tryAgain = true;
    }
}while(tryAgain);
        }
    }

I certainly hope that helps and I was able to sort out some confusion! 我当然希望能有所帮助,并且能够解决一些困惑!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM