我想要用戶插入他們想要從桌子上取下多少支桿(從1支到3支),然後我想讓程序輸出移動後留在桌上的支桿數量。爲什麼每次都連續要求用戶輸入2次?
我明白了這一點,但我不明白爲什麼它要求我在打印結果(並且第二個用戶輸入是計數的)之前將用戶輸入放在一行中兩次。
import java.util.Scanner;
import java.io.InputStream;
public class GameOfSticks {
public static int sticks = 10;
public static int sticksToTake;
public static void main(String[] args) {
Scanner userInputScanner = new Scanner(System.in);
System.out.println("The number of sticks on the table is " + sticks + ".");
System.out.print("Insert how many sticks you want to take: ");
makeHumanMove(sticksToTake);
System.out.println(getNumberOfSticksOnBoard());
}
public static int getNumberOfSticksOnBoard() {
sticks = sticks - makeHumanMove(sticksToTake);
return sticks;
}
public static int makeHumanMove(int sticksToTake) {
Scanner userInputScanner = new Scanner(System.in);
while (true) {
int enteredNumber;
try {
enteredNumber = userInputScanner.nextInt();
} catch (Exception e) {
System.out.print("Not a number, enter a number from 1 to 3: ");
userInputScanner = new Scanner(System.in);
continue;
}
if (enteredNumber < 1 || enteredNumber > 3) {
System.out.print("Incorrect number, enter a number from 1 to 3: ");
continue;
} else {
sticksToTake = enteredNumber;
return(sticksToTake);
}
}
}
}
謝謝!我無法相信我無法意識到這一點。 – Tymu888 2015-02-23 12:26:40