about array exception
When I run the code below, why does it throw this error?
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:开发者_如何学编程2050)
at GuessNumber.main(GuessNumber.java:35)
This is my code, thank you:
public class GuessNumber {
public static void main(String[] args) {
int[][] num = new int[5][16];
int[] len = new int[5];
char[] bit;
for (int i = 1; i <= 32; i++) {
bit = ToBinary(i);
//bit的大小为5:把二进制数存储到数组中num
for (int j = 0; j < bit.length; j++) {
if (bit[j] == '1') {
//11000
num[j][len[j]++] = i;
}
}
}
Random r = new Random((new Date()).getTime());
int numRoad = r.nextInt(31);
bit = ToBinary(numRoad);
String cardRand = "";
for (int i = 0; i < bit.length; i++) {
if (bit[i] == '1') {
cardRand = cardRand + (i + 1) + ",";
}
}
System.out.println("在卡片" + cardRand + "上的数字是:");
System.out.println("请玩家输入猜测数字:");
Scanner c = new Scanner(System.in);
int number = c.nextInt();
if (number == numRoad) {
System.out.println("恭喜您,猜对了.");
} else {
System.out.println("对不起!猜错了,该数应该为:" + numRoad);
}
}
/**
* 将十进制数转成二进制数
*
* @param i
* @return
*/
public static char[] ToBinary(int c) {
char[] bit = new char[5];
String a = Integer.toBinaryString(c);
bit = a.toCharArray();
char temp;
for (int i = 0; i < bit.length / 2; i++) {
temp = bit[i];
bit[i] = bit[bit.length - 1 - i];
bit[bit.length - 1 - i] = bit[i];
}
return bit;
}
}
Most likely because the Scanner expected an integer value and found something else. The exception is a result of your actual input at the console.
Looks like you see a binary number (10011
) and have to enter the decimal value (19
)
Javadoc to the rescue:
Throws: InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
You probably don't enter a valid integer whan asked for it by your program.
精彩评论