英文:
How to display error message instead of java exception?
问题
package guessNumber;
import java.util.Scanner;
public class GuessNumberApp {
public static void main(String[] args) {
final int LIMIT = 10;
System.out.println("猜数字游戏!");
System.out.println("我想一个1到" + LIMIT + "之间的数字。");
System.out.println();
// 获取一个1到限制之间的随机数
double d = Math.random() * LIMIT; // d >= 0.0 且 < limit
int number = (int) d; // 将double转换为int
number++; // int >= 1 且 <= limit
// 准备从用户读取输入
Scanner sc = new Scanner(System.in);
int count = 1;
while (true) {
try {
int guess = sc.nextInt();
System.out.println("你猜的数字是:" + guess);
if (guess < 1 || guess > LIMIT) {
System.out.println("你的猜测无效。");
continue;
}
if (guess < number) {
System.out.println("太低了。");
} else if (guess > number) {
System.out.println("太高了。");
} else {
System.out.println("你在第 " + count + " 次猜中了。\n");
break;
}
count++;
} catch (java.util.InputMismatchException e) {
System.out.println("输入格式错误,请输入一个数字。");
sc.nextLine(); // 清除输入缓冲区中的无效输入
}
}
System.out.println("再见!");
}
}
英文:
I am trying to make a Guessing Game for a Java assignment, I have everything I need except exception handling, you see I'm trying to make it display an error message instead of displaying Exception in thread "main" java.util.InputMismatchException when someone tries to enter a numerical number in alphabetical form. The code I have is followed.
(I know I need a try and catch but I don't know what to put exactly.)
package guessNumber;
import java.util.Scanner;
public class GuessNumberApp {
public static void main(String[] args) {
final int LIMIT = 10;
System.out.println("Guess the number!");
System.out.println("I'm thinking of a number from 1 to " + LIMIT);
System.out.println();
// get a random number between 1 and the limit
double d = Math.random() * LIMIT; // d is >= 0.0 and < limit
int number = (int) d; // convert double to int
number++; // int is >= 1 and <= limit
// prepare to read input from the user
Scanner sc = new Scanner(System.in);
int count = 1;
while (true) {
int guess = sc.nextInt();
System.out.println("You guessed: " + guess);
if (guess < 1 || guess > LIMIT) {
System.out.println("Your Guess is Invalid.");
continue;
}
if (guess < number) {
System.out.println("Too Low.");
} else if (guess > number) {
System.out.println("Too High.");
} else {
System.out.println("You guessed it in " + count + " tries.\n");
break;
}
count++;
}
System.out.println("Bye!");
}
}
答案1
得分: 1
请尝试这样做:
尝试 {
int guess = sc.nextInt();
} 捕获(InputMismatchException e) {
System.out.println("一些友好的错误消息");
继续;
}
这将替换
int guess = sc.nextInt();
英文:
try something like that:
try {
int guess = sc.nextInt();
} catch(InputMismatchException e) {
System.out.println("some nice error message");
continue;
}
This would replace
int guess = sc.nextInt();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论