[英]This program throws an exception error when the user inputs a letter or word instead of the expected int (java)
This program throws an exception error when the user inputs a letter by accident(typo) when they should enter a number. 当用户在输入数字时偶然输入了一个字母(错别字)时,该程序将引发异常错误。 I need to make it so the user(when asked to input a die number >=1) is able to accidentally enter something other than a number and have the program act like they never entered anything and open up the keyboard again.(while also displaying a message like, "You entered something wrong, please try again.") 我需要做到这一点,以便用户(当要求输入模具编号> = 1时)能够不小心输入数字以外的内容,并使程序的行为就像从未输入任何内容并再次打开键盘一样。显示类似“您输入了错误的消息,请重试”的消息。)
Heres the code: 这是代码:
import java.util.Scanner;
public class EnhancedGameOfPig {
public static void main(String[] args) {
//Scanner for taking input from keyboard
Scanner kb = new Scanner(System.in);
int nPlayer = 0;
do
{
System.out.print("Enter the number of players (between 2 to 10): ");
nPlayer = kb.nextInt();
//validity checking for 2-10
if (nPlayer<2 || nPlayer>10)
{
System.out.println("Ops! the no of supported players are between 2 to 10");
System.out.println("Please enter again: ");
}
}
while(nPlayer<2 || nPlayer>10);
//creating array of nPlayer as supplied by the user
Player [] players = new Player[nPlayer];
for(int i=0; i<nPlayer;i++){
System.out.print("Enter player name: ");
String name = new Scanner(System.in).nextLine();
players[i] = new Player(name);
}
/*starting the game*/
int round = 1;
System.out.print("Enter predetermined win points: ");
int GAME_OVER_POINT = new Scanner(System.in).nextInt();
mark:
while(true){
//start round for each player
for(int i=0;i<players.length;i++){
System.out.println("Player Name: " + players[i].getName() + " you are playing round: " + round);
System.out.print("Enter no of dies (>=1): ");
int nDie = new Scanner(System.in).nextInt();
//validity checking here for die, so that it is not <1
if (!(nDie>=1)){
System.out.println("Oops! You need to enter a die that is greater than or equal to 1...");
}
//datastructure for holding dies for this ith player
Die [] dieForPlayer = new Die[nDie];
//create the die objects
for(int k = 0;k<nDie;k++){
dieForPlayer[k] = new Die();
}
//rolling the dies now
int totalValue = 0;
boolean isThereOne = false;
System.out.println("Rolling " + nDie + " for " + players[i].getName());
for(int k = 0;k<dieForPlayer.length;k++){
int value = dieForPlayer[k].roll();
System.out.println(" Die No: " + (k+1) + " value: " + value);
if(value==1) //atleast one 1 is there
isThereOne = true;
totalValue += value;
}
//roll is over.. now checking
if (isThereOne && totalValue==nDie){
//all of them 1
//reset the banked point for this player
players[i].resetBankedPoint();
System.out.println(players[i].getName() + "Oops! all the dies showed 1's\n "
+ "You get nothing for this round and \n"
+ "your banked point has been reset to 0");
}
else if (!isThereOne){
//no one(s) rolled
//add the points to the banked pont of the user
players[i].addBankedPoints(totalValue);
System.out.println(players[i].getName() + ", great! u get total of : " + totalValue + " for this round");
System.out.println("Your total Banked Point is: " + players[i].getBankedPoint());
}
else{
//there is atleast one 1, get no points for this round
players[i].addBankedPoints(0);
System.out.println(players[i].getName() + ", Sorry! one of the die turned with one! \n" +
"You get nothing for this round ");
System.out.println("Your total Banked Point is: " + players[i].getBankedPoint() + "\n");
}
if (players[i].getBankedPoint()>=GAME_OVER_POINT){
//the game over point has been reached, so breaking out of the outer while
break mark;
}
}
round++;
}//end of the undeterministic while
System.out.println("================The Game is Over=====================");
System.out.println("Total Round played: " + round);
System.out.println("=====================================================");
for(int i=0;i<players.length;i++){
System.out.print("Player Name: " + players[i].getName() + " Score: " + players[i].getBankedPoint());
if(players[i].getBankedPoint()>=GAME_OVER_POINT){
System.out.println(" WINNER");
}
else
System.out.println();
}
System.out.println("======================================================");
kb.close();
}
}
If you use kb.nextLine()
instead, it will return a String. 如果改为使用kb.nextLine()
,它将返回一个String。 Then use Integer.parseInt()
within a try/catch block, to make sure your program doesn't break if it isn't a valid number. 然后在try / catch块中使用Integer.parseInt()
,以确保您的程序如果不是有效数字也不会中断。 You could do it like this: 您可以这样做:
String input = kb.nextLine();
int output = 0;
try {
output = Integer.parseInt(input);
catch (NumberFormatException e) {
System.out.println("Invalid input type");
}
if(kb.hasNextInt())
{
// Do something
}
else
{
System.out.println("You entered something wrong, please try again");
}
You could catch the InputMismatchException
thrown if nextInt()
is called and the next token is not an int. 如果调用nextInt()
并且下一个标记不是int,则可以捕获抛出的InputMismatchException
。
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt() http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.