我有这段代码,我想把try-catch放在while循环中。逻辑是,“当出现输入错误时,程序将继续询问正确的输入”。我将如何做到这一点?提前致谢。while循环中的try-catch方法?
public class Random1 {
public static void main(String[] args) {
int g;
Scanner input = new Scanner(System.in);
Random r = new Random();
int a = r.nextInt(10) + 1;
try {
System.out.print("Enter your guess: ");
g = input.nextInt();
if (g == a) {
System.out.println("**************");
System.out.println("* YOU WON! *");
System.out.println("**************");
System.out.println("Thank you for playing!");
} else if (g != a) {
System.out.println("Sorry, better luck next time!");
}
} catch (InputMismatchException e) {
System.err.println("Not a valid input. Error :" + e.getMessage());
}
}
你的while循环和你自己试图首先解决这个问题的地方在哪里?这样做将a)帮助你学习更多,b)向我们展示你的假设是不正确的,并让我们提供更好的指导帮助,并且c)大大提高我们对你的尊重。 – 2012-03-20 04:32:21
为什么要写这个问题的答案?让OP首先明确问题。 – 2012-03-20 04:37:26
你是对的。对不起。也谢谢你。我只是不擅长自学。再次,我很抱歉。 – singko 2012-03-20 04:38:52