如何在第一个真返回值之后停止 if 语句?

How do I stop if statement after the first true return value?

提问人:jorge reyes 提问时间:7/9/2022 最后编辑:Alexander Ivanchenkojorge reyes 更新时间:7/11/2022 访问量:515

问:

此代码应根据用户输入打印出回复,在无效尝试后,用户会尝试 3 次输入。当它们返回所有无效值时,它会起作用,但代码在回答“是”或“否”后仍会要求用户输入。


import java.util.*;
public class Equality {
    public static void main(String[] args) {
        
        Scanner input = new Scanner(System.in);
        System.out.println("Do you have a job?(yes/no): ");
        String response = input.next();
        
        if(response.equalsIgnoreCase("yes")) {
            System.out.println("You are the breadwinner!");
        }
        else if(response.equalsIgnoreCase("no")) {
            System.out.println("Keep trying, you will find one!");
        }
        else {
            System.out.println("Invalid Entry! Try again!");
        }
        
        response = input.next();
        if(response.equalsIgnoreCase("yes")) {
            System.out.println("You are the breadwinner!");
        }
        else if(response.equalsIgnoreCase("no")) {
            System.out.println("Keep trying, you will find one!");
        }
        else {
            System.out.println("Invalid Entry! Try again!");
        }
        
        response = input.next();
        if(response.equalsIgnoreCase("yes")) {
            System.out.println("You are the breadwinner!");
        }
        else if(response.equalsIgnoreCase("no")) {
            System.out.println("Keep trying, you will find one!");
        }
        else {
            System.out.println("Too many invalid entries!");
        }
    }
}
java if-statement while-循环 java.util.scanner

评论


答:

0赞 Kayz 7/9/2022 #1

你真的应该看看循环(以及如何摆脱它们)! 它最终可能会是这样的:(伪代码)

boolean valid = false;
int counter = 0;
while(!valid && counter < 3) {
  if ("yes") {
   ...
   valid = true;
  } else if ("no") {
    ...
   valid = true;
 } else {
   counter++:
 }
}
0赞 Rhett Harrison 7/9/2022 #2

您无需重复键入代码。相反,让我们使用 while 循环。此代码将继续运行,直到使用进行了 3 次尝试。在最底部,只有当我们到达最后时,我们才会将整数变量条目加 1。

代码没有停止的原因是您没有告诉它停止。到达循环中的停止点后,可以使用此 break 语句退出 while 循环。

如果用户收到 3 个(或更多)条目,系统将回复太多条目


import java.util.*;
public class Equality {
  public static void main(String[] args) {
    int entries = 0;
    while(entries < 3) {

      // Get the User's response
      Scanner input = new Scanner(System.in);
      System.out.println("Do you have a job?(yes/no): ");
      String response = input.next();

      // Determine the response from System
      if(response.equalsIgnoreCase("yes")) {
        System.out.println("You are the breadwinner!");
        break; // this will stop the while loop
      }
      else if(response.equalsIgnoreCase("no")) {
        System.out.println("Keep trying, you will find one!");
      }
      else {
        System.out.println("Invalid Entry! Try again!");
      }
      entries++;

      // Let the user know they have had too many entries
      if(entries >= 3) {
        System.out.println("Too many invalid entries");
      }
    }
  }
}

以下是我添加到代码中的新内容的一些资源

while 循环:https://www.w3schools.com/java/java_while_loop.asp

中断语句:https://www.geeksforgeeks.org/break-statement-in-java/

0赞 ArshiaRx 7/9/2022 #3

你不需要重复它。您可以使用 while 循环或 for 循环。下面是一个示例

import java.util.Scanner;

public class Equality {
    public static void main(String args[]) {
        Scanner input = new Scanner(System.in);

        for (int i = 0; i <= 2; i++) {
            System.out.println("Do you have a job? (Yes/No): ");
            String response = input.next();
            if (response.equalsIgnoreCase("Yes")) {
                System.out.println("You are the breadWinner");
                break;   //will exit it out of the loop
            }
            else if (response.equalsIgnoreCase("No")){
                System.out.println("Keep, trying you will find one!");
            }
            else {
                System.out.println("Invalid Value, Try again!");
            }
        }
    }
}

评论

0赞 Rhett Harrison 7/9/2022
响应或?我看到你全是大写字母和全小写字母。您需要 equalsIgnoreCase 而不是 w3schools.com/java/ref_string_equalsignorecase.asp 。或者,您可以将响应小写,并检查YesNoyesno
1赞 ArshiaRx 7/9/2022
这是真的,不知道equalsIgnoreCase方法。很高兴现在知道,谢谢
0赞 Rhett Harrison 7/9/2022
在系统提示符下,示例响应为“是/否”。“是”与“是”不同。看看我创建的这个 repl 来解释示例 replit.com/@reharri7/String-Case-Difference?v=1
3赞 MegaBytten 7/9/2022 #4

因为你有多个 if 语句,所以如果第一个语句回答正确,你就无法脱离后 2 个语句。无论第一个 if() { } 语句的结果如何,将始终调用以下代码及以后的代码。

(您的代码)

if(response.equalsIgnoreCase("yes")){
  System.out.println("You are the breadwinner!");
} else if(response.equalsIgnoreCase("no")){
  System.out.println("Keep trying, you will find one!");
} else {
  System.out.println("Invalid Entry! Try again!");
}

//this following code will always be run after your first if statement!
response = input.next();
if(response.equalsIgnoreCase("yes")){
  System.out.println("You are the breadwinner!");
}
...

完成您要完成的任务的最好方法可能是使用循环。这里有一个关于 Java 中 while 循环如何工作的很好的教程。本教程应有助于理解以下(改进的)代码,该代码:

  • 一旦用户正确,就会退出循环
  • 最多允许 3 次尝试

(新代码)

import java.util.*;
public class Equality {
  public static void main(String[] args) {

    //this int will be increased by 1 everytime the code completes
    int attempts = 0;

    //while attempts < 3, all of the following code will be executed
    //after it is completed, it will be run again! until attempts >= 3
    while(attempts < 3) {
      Scanner input = new Scanner(System.in);
      System.out.println("Do you have a job?(yes/no): ");
      String response = input.next();

      // Determine the User's response
      if(response.equalsIgnoreCase("yes")) {
        System.out.println("You are the breadwinner!");
        break; // 'break' is a keyword used to BREAK out of the loop = stop!
      }
      else if(response.equalsIgnoreCase("no")) {
        System.out.println("Keep trying, you will find one!");
      }
      else {
        System.out.println("Invalid Entry! Try again!");
      }
      attempts++; //this is a fancy line for attempts = attempts + 1

      //After their last attempt, system will print a warning
      if(attempts >= 3) {
        System.out.println("No More Remaining Attempts!");
        //notice how we dont need a break statement here!
        //this is because on the next iteration (loop) of the loop,
        //attempts = 3, and while (attempts < 3) is no longer true! = no loop
      }
    }
  }
}

希望这会有所帮助!这也是我的第一个堆栈溢出答案,因此对于任何格式/技术问题,我深表歉意:D