我的代碼是爲了找到倍兩個字相交於普通的字母數,然後打印出兩個詞交叉,如果他們做跨錯誤。我收到關於我的索引越界
當我編譯它是好的,但是當我運行它,我得到一個錯誤。我知道這與我的索引超出範圍有關,但我不知道該怎麼辦。
public class Assg23
{
public static void main(String[] args)
{
String w1 = args[0];
String w2 = args[1];
int numberOfCrosses = 0;
int pos1 = 0;
int pos2 = 0;
for(int i=0; i < w1.length(); i++)
{
for(int j=0; j < w2.length(); j++)
{
if(w1.charAt(i) == w2.charAt(j))
{
numberOfCrosses++;
crossesAt(w1, pos1, w2, pos2);
printCross(w1, pos1, w2, pos2);
}
}
}
if(numberOfCrosses == 0)
{
System.out.println("Words do not cross");
}
}
private static boolean crossesAt(String w1, int pos1, String w2, int pos2)
{
if(w1.charAt(pos1) == w2.charAt(pos2))
{
return true;
}
else
{
return false;
}
}
private static void printCross(String w1, int pos1, String w2, int pos2)
{
for(int i=0; i < w1.length(); i++)
{
for(int j = 0; j < w2.length(); j++)
{
if(j == pos1)
{
System.out.print(w2.charAt(i));
}
if(i == pos2)
{
System.out.print(w1.charAt(j));
}
else
{
System.out.print(" ");
}
}
}
}
我收到此錯誤:
59號線:是System.out.print(w2.charAt(I)); 第27行是:printCross(w1,pos1,w2,pos2);
x-10-250-57-156:csci1103 Katie$ java Assg23 lottery boat
blotto a t Exception in thread "main" `java.lang.StringIndexOutOfBoundsException: String index out of range: 4`
at java.lang.String.charAt(String.java:658)
at Assg23.printCross(Assg23.java:59)
at Assg23.main(Assg23.java:27)
你想要的長度 - 1 – csmckelvey