私のコードは、すでに宣言されている配列を出力してから、ユーザー入力を求めます。ユーザはxyの形式で番号を入力するか、quitを入力してプログラムの使用を停止することになっています。ユーザからの入力を受けた後、xを行として、yを列番号として使用し、そのインデックスを0に設定して新しい配列を印刷することによって配列の要素を出力します。 私はこれまで、整数だけを受け入れるか、ユーザーから「辞める」ことを別にして、ほとんどを達成しました。ユーザーが「終了」とは別の文字列を入力すると、プログラムがクラッシュします。 これは私のコードです。 import java.util.Scanner;範囲外の文字列インデックス:1 れるjava.langでタイプintまたは文字列のみを受け入れるようにユーザー入力を検証する "quit"
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このエラー「スレッドの例外" を取得しています。 String.substring(String.java:1963) at Exercise23.main(Exercise23.java:26) "
それがクラッシュしたとき、あなたはどのようなエラーが出るのですか? – Steve101
申し訳ありませんエラーメッセージを追加するのを忘れました。今編集されました。 @ Steve101 –
これは、入力文字列( 'next.readLine()')の長さがゼロに等しいことを意味します。それで 'xy.substring(0、1)'が例外をスローする – krzydyn