簡體   English   中英

如何使我的腳本循環?

[英]How do I make my script either loop?

在“請重新啟動並重試”之后,我試圖讓程序循環啟動到“你好,你叫什么名字?”

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

只需使用do-while循環並刪除System.exit(0);

do { 

    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.");
    }
} while (!isCorrect.equals("Yes"));

我添加了一個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!
}
}

希望我能幫上忙!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM