下面是我正在努力工作的一些代碼。Java StringOutOfBounds僅在循環中出現錯誤
public class Main
{
public static void main(String[] args)
{
try
{
BufferedReader reader = new BufferedReader(new FileReader(args[0]));
String line = reader.readLine(); // start with the first line
String[] a = new String[3];
a = line.split(" ");
int n = a[0].charAt(0) - '0';
int m = a[1].charAt(0) - '0';
int k = a[2].charAt(0) - '0';
DisjointUnionSets dus = new DisjointUnionSets(n);
line = reader.readLine();
while(line != null)
{
String[] b = new String[2];
b = line.split(" ");
int tmp1 = b[0].charAt(0) - '0';
int tmp2 = b[1].charAt(0) - '0';
dus.union(tmp1,tmp2);
line = reader.readLine();
}
reader.close();
// Check if 4 is a neighbour of 1
if (dus.find(4) == dus.find(1))
System.out.println("Yes");
else
System.out.println("No");
// Check if 1 is a neighbour of 2
if (dus.find(1) == dus.find(2))
System.out.println("Yes");
else
System.out.println("No");
}
catch(IOException ex){}
}
}
它編譯沒有任何錯誤,但是當我嘗試運行它,我定義TMP1時得到一個異常:
java.lang.StringIndexOutOfBoundsException:字符串索引超出範圍:0
我真的不明白爲什麼當我定義n,m和k時不會發生這種情況。我使用b的方式與使用a相同,至少這就是我的想法。
在此先感謝!
給你輸入以及 –
告訴您試圖運行代碼的命令? –
我的輸入是第一行中的3個數字,然後是兩個數字的行。數字由一個空格分隔。 @Nixal Saxena不確定你的意思,但我只是從終端運行Java main input.txt,如果這是你的問題。 – cgss