gpt4 book ai didi

java - 如何在 Try Catch 猜猜游戏中继续循环

转载 作者:行者123 更新时间:2023-12-02 05:21:30 24 4
gpt4 key购买 nike

所以我的问题是,当我尝试并捕获输入错误时,我不知道如何继续我的程序。我尝试使用“继续;”我的 catch 语句之后的代码,但这只是无法控制地循环我的程序。我需要程序在用户输入错误后从停止的地方开始。任何帮助,将不胜感激。请注意,这是一项作业,但我将通过处理代码中的垃圾来超越。

      //Import library
import java.io.*;
import java.util.*;

//File name
public class GuessingGame
{

//Main throws Input and output error
public static void main (String [] args) throws IOException
{
//inputs for users
Scanner in = new Scanner (System.in);
Scanner i = new Scanner (System.in);
//variables for the loop, random number, character and counter
int guess = 0;
int rnd;
char decision;
boolean loop = false;
//random number generator
Random random = new Random();
rnd = random.nextInt(100) + 1;

//loops the guess and input
while (!loop){
try{
System.out.println(rnd);
//prompt the user
System.out.println(" Please guess a number between 1-100. Press 0 to exit.");
int num = in.nextInt();
//if statements

if (num==0)
{
//when user types '0' it ends the program
System.exit(0);
System.out.println("You gave up!.... Reseting program...");
}
else if (num>rnd)
{
//prints too big, adds to counter 'guess'
System.out.println("The number is too big!");
guess++;
}
else if (num<rnd)
{
//prints too small, adds to counter 'guess'
System.out.println("The number is too small!");
guess++;
}
else
{
//prints correct, adds to counter, dsiplays # of guesses and ends loop
System.out.println("You guessed the number right!!");
guess++;
System.out.print(" # of guesses: " + guess);
//Note**: i could've just put 'break;' but the compiler would'nt read the rest of the code below
loop = true;
//loops the case untill correct input is chosen either 'Y' or 'N'
while(true){
//prompt the user if they want to play again
System.out.println(" Would you like to play again? Y/N?");
decision = i.nextLine().charAt(0);

switch (decision) {
case 'Y':
case 'y':
//calls main, basically restarts the game
GuessingGame.main(args);
break;

case 'N':
case 'n':
System.out.println("Bye!");
//exits the program completely
System.exit(0);
break;

default:
//if incorrect input, this prints
System.out.println("Please enter a Yes or No <Y/N>");

}
}
}



}
//catches input errors
catch (Exception e){
System.out.println("Only numbers!!!");
//GuessingGame.main(args);
continue;

}
}
}

最佳答案

请尝试执行此操作,因为您只是测试输入。还要在捕获中添加 in.nextLine() 以吃掉留下的角色。

while (!loop){
int num;
try{
System.out.println(rnd);
//prompt the user
System.out.println(" Please guess a number between 1-100. Press 0 to exit.");
num = in.nextInt();
}
catch (Exception e){
System.out.println("Only numbers!!!");
//GuessingGame.main(args);
in.nextLine();
continue;

}

关于java - 如何在 Try Catch 猜猜游戏中继续循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26472862/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com