【发布时间】:2017-02-25 19:29:48
【问题描述】:
我的代码打印出一个已经声明的数组,然后要求用户输入。用户应该输入 xy 格式的数字或键入 quit 以停止使用该程序。在获得用户输入后,它使用 x 作为行和 y 作为列号打印出数组的元素,然后将该索引设置为 0 并打印新数组。 到目前为止,除了只接受整数或用户“退出”之外,我已经完成了大部分工作。如果用户输入除“退出”之外的另一个字符串,则程序崩溃。 这是我的代码。 导入 java.util.Scanner;
public class Exercise23 {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int [][] array = {
{0, 1, 4, 5},
{3, 7, 9, 7},
{1, 8, 2, 1}
};
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j]);
}
System.out.println();
}
boolean exitCon = false;
do {
System.out.println("Please enter a number in the format 'xy' with no spaces in between or enter 'quit' to stop");
String xy = read.nextLine();
if (!"quit".equals(xy)) {
String x = xy.substring(0, 1);
String y = xy.substring(1);
int row = Integer.parseInt(x);
int column = Integer.parseInt(y);
if (0 <= row && 0 <= column && row <= 2 && column <=) {
System.out.println();
System.out.println(array[row][column]);
array[row][column] = 0;
System.out.println();
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j]);
}
System.out.println();
}
System.out.println();
} else { System.out.println("The number has to be in range 00-23 inclusive considering the format 'xy'.");
}
} else if (xy.equals("")) {
System.out.println("You can only enter integers or 'quit'.");
} else {
exitCon= true;
}
} while (!exitCon);
}
}
问题出在这个位
String xy = read.nextLine();
if (!"quit".equals(xy)) {
String x = xy.substring(0, 1);
String y = xy.substring(1);
int row = Integer.parseInt(x);
int column = Integer.parseInt(y);
if (0 <= row && 0 <= column && row <= 2 && column <= 3) {
System.out.println();
System.out.println(array[row][column]);
array[row][column] = 0;
System.out.println();
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j]);
}
System.out.println();
}
System.out.println();
} else { System.out.println("The number has to be in range 00-23 inclusive considering the format 'xy'.");
}
} else if (xy.equals("")) {
System.out.println("You can only enter integers or 'quit'.");
} else {
exitCon= true;
我收到此错误“线程“主”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:1 在 java.lang.String.substring(String.java:1963) 在练习23.main(练习23.java:26) "
【问题讨论】:
-
崩溃时出现什么错误?
-
对不起,我忘了添加错误信息。现已编辑。 @史蒂夫101
-
这意味着您的输入字符串 (
next.readLine()) 的长度为零。那么xy.substring(0, 1)抛出异常 -
我认为那是因为我尝试了一个空字符串。当我输入其他内容时,它再次崩溃
-
是的,在没有检查正确输入的情况下做某事有几点。在解析字符串之前,您必须检查它是否输入正确。长度是第一个检查,另一个是检查是否只包含数字。
标签: java validation input user-input