我對Java完全陌生,而且卡住了。我必須製作遊戲「猜數字」。我能夠完成大部分工作,但是現在我不知道如何處理用戶輸入,如果它的字符串。 我希望能夠告訴用戶輸入字符串時輸入不正確,並重復詢問輸入。這將是巨大的,如果有人可以幫助我在這裏:)
這裏是我的代碼: Java - 字符串輸入異常處理
import java.util.Scanner;
import java.util.Random;
public class SWENGB_HW_2 {
public static void main(String[] args) {
System.out.println("Welcome to the guess the number game!\n");
System.out.println("Please specify the configuration of the game:\n");
Scanner input = new Scanner(System.in);
System.out.println("Range start number (inclusively):");
int startRange;
startRange = input.nextInt();
System.out.println("Range end (inclusively):");
int endRange;
endRange = input.nextInt();
System.out.println("Maximum number of attemps:");
int maxAttemp;
maxAttemp = input.nextInt();
System.out.println("Your Task is to guess the random number between "
+ startRange + " and " + endRange);
Random randGenerator = new Random();
int randNumber = randGenerator.nextInt((endRange - startRange) + 1)
+ startRange;
int numberOfTries = 0;
System.out
.println("You may exit the game by typing; exit - you may now start to guess:");
String exit;
exit = input.nextLine();
for (numberOfTries = 0; numberOfTries <= maxAttemp - 1; numberOfTries++) {
int guess;
guess = input.nextInt();
if (guess == randNumber) {
System.out.println("Congratz - you have made it!!");
System.out.println("Goodbye");
} else if (guess > randNumber) {
System.out.println("The number is smaller");
} else if (guess < randNumber) {
System.out.println("The number is higher");
}
}
if (numberOfTries >= maxAttemp) {
System.out.println("You reached the max Number of attempts :-/");
}
}
}
可能重複http://stackoverflow.com/questions/25940276/understanding-try-catch-and-error -handling) – StackFlowed 2014-10-09 13:14:26
打印'Goodbye'後可能要添加'break;'以退出for-loop並終止程序。 – aioobe 2014-10-09 13:31:03