我開始研究這個小骰子游戲,但我需要一些幫助來弄清楚如何在每次嘗試失敗后重新嘗試部分回圈。
目前游戲重新開始并要求玩家重新輸入他們的名字。我希望用戶每次都重新輸入他們的猜測,直到他們成功。
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main (String[] args) throws IOException {
boolean run = true;
while (run) {
String[] input = new String[]{"1", "2", "3", "4", "5", "6"};
String[] sorry = new String[]{"If at first you don't succeed...", "Your luck will improve...", "Don't give up...", "Not this time..."};
Random dice = new Random();
int select = dice.nextInt(input.length);
Scanner scan = new Scanner(System.in);
System.out.println( "Hi there, may I please have your name?");
String name = scan.nextLine();
System.out.println("What a nice name...");
System.out.println("ok " name ", please choose a number between 1 and 6");
String play = scan.nextLine();
System.out.println(input[select]);
if (!input[select].equals(play)) {
System.out.println(sorry[select] " try again");
if (input[select].equals(play))
System.out.println("Bingo!!! " name " you've won 1 million imaginary dollars!");
System.out.println("would you like to play again \"Y\" or \"N\"");
String yes = "y";
String no = "n";
String answer = scan.nextLine();
if (answer.equals(yes)) {
continue;
}
if (answer.equals(no)) {
System.out.println("Thank you for playing " name ". Good bye!");
break;
}
}
}
}
}
uj5u.com熱心網友回復:
將詢問姓名的列印陳述句放在 while 回圈之外。
Scanner scan = new Scanner(System.in);
System.out.println("Hi there, may I please have your name?");
String name = scan.nextLine();
while(run){
// your code
}
uj5u.com熱心網友回復:
您可以使用while回圈!在再試部分,將 更改if為while回圈。
static String play; // Define it (not assign) outside of method
while (!input[select].equals(play)) {
System.out.println(sorry[select] " try again");
System.out.println("ok " name ", please choose a number between 1 and 6");
play = scan.nextLine();
}
W3Schools中 while 回圈的定義:
只要指定條件為真,while 回圈就會回圈執行一段代碼
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/347974.html
