java - 如何让我的脚本循环?

标签 java

在“请重新启动并重试”之后,我试图让程序循环开始到“你好,你叫什么名字?”

import java.util.Scanner;


public class Learning {

public static void main(String[] args) 

{
    System.out.println("Hello, What is your name?");
    Scanner scanner = new Scanner(System.in);
    String yourName = scanner.nextLine();
    System.out.println("Is: " +yourName + " your name?");

    Scanner scanner1 = new Scanner(System.in);
    String isCorrect = scanner1.nextLine();

    if (isCorrect.equals("Yes"))
    {
        System.out.println("Thank you, Please proceed with the quiz!");
    }
    else
    {
        System.out.println("Please restart and try again.");
        System.exit(0);
    }

最佳答案

我添加了一个 while 语句:

while(isCorrect.equals("noValue")&&(!isCorrect.equals("yes")||!isCorrect.equals("yes"))) {

所以它一直持续到 isCorrect 不等于“noValue”并且等于“yes”或“Yes” 完整代码如下:

import java.util.Scanner;

public class Learning {

public static void main(String[] args) {

String isCorrect = "noValue";
//If isCorrect equals noValue, keep going until it equals yes or Yes
while(isCorrect.equals("noValue")&&(!isCorrect.equals("yes")||!isCorrect.equals("Yes"))) {
    System.out.println("Hello, What is your name?");
    //You don't really need two scanners if they are both for the same thing
    Scanner scanner = new Scanner(System.in);
    String yourName = scanner.nextLine();
    System.out.println("Is: " +yourName + " your name?");

    isCorrect = scanner.nextLine();
    //include the if and else statements so the program knows what to say
    //and if it should repeat or not
    if(isCorrect.equals("yes")||isCorrect.equals("Yes")) {
        System.out.println("Thank you, please proceed with the quiz!");
    } else {
        System.out.println("Please try again");
        isCorrect = "noValue";
    }
}
//Continue with the quiz here!
}
}

希望对您有帮助!

关于java - 如何让我的脚本循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21894584/

相关文章:

java - 按黑莓手机上的绿色键

java - 页面未重定向

java - 非常大的字符串出现 StringIndexOutOfBoundsException

java - 如何向调用者线程发出 ExecutorService 已完成任务的信号

java - 在 Apache Beam 中写入不同的源

java - 如何使用 Maven 的程序集插件将 Implementation-Version 值添加到 jar list ?

java - Tomcat 服务器 - JBPM - 启动需要 3 小时

java - 如何解决 Pane.setConstraints() 方法的不可见性

java - Java中每个循环的可迭代反向

java - 运行斯坦福大学 NER 和斯坦福大学 POS 标记器时出现不兼容的类更改错误