我已經寫了這段代碼,它編譯得很好,但是當我嘗試運行它時,給了我一個錯誤,指出字符串索引超出範圍:11.有誰能告訴我什麼即時通訊做錯了?字符串索引超出範圍11錯誤java
import java.util。*; 類問題2 {
public static void main(String[] args)
{
String[] section1 = {"Curie, Marie", "Feynman, Richard", "Germain, Sophie",
"Turing, Alan"};
String[] section2 = {"Bolt, Usain", "Graf, Steffi","Hamm, Mia",};
String[] section3 = {"Bach, Johann Sebastian", "Beethoven, Ludwig van",
"Mozart, Wolfgang Amadeus", "Schumann, Clara"};
String [] merged = mergeSortedArrays(section1,section2);
//String[] merged = mergeSortedArrays(mergeSortedArrays(section1, section2),section3);
for (int z =0; z < merged.length-4; z++) {
System.out.println(merged[z] + ", ");
}
}
// Do not change the method header
public static String[] mergeSortedArrays(String[] a1, String[] a2) { //method for merging and ordering
String[] temp = new String[a1.length + a2.length]; // new array with size of the two input arrays
int x; // variable declared for a for loop and other purposes
for(x = 0; x< a1.length -1; x++){ //1st for loop to put in names from a1 to the new array
temp[x] = a1[x]; // code to store the strings from one array to the other
}
for(int y = 0; y <a2.length -1; y++) { //2nd for loop to put in names from a2 to the new array
temp[x] = a2[y]; // code to store the strings from one array to the other
x = x +1; //increments x, to help incease the index of the new array
}
String[] tempor = new String[1];
boolean finish = true; // boolean to help break the while loop used later
while(finish == true) { // while loop to check the names to make them in order
finish = false; //makes the boolean false
for(int i = 0; i < temp.length-1 ; i ++) { // 3rd for loop. To check between two strings
String temporary1 = temp[i]; // string variable that stores a string from the new array
String temporary2 = temp[i+1]; // string variable that stores the next string from the same new array
int minimum = Math.min(temporary1.length(), temporary2.length());
for(int j = 0; j < minimum -1; j++) { //4th for loop. To check between characters of the two strings
if((int)(temporary1.charAt(j)) == (int)(temporary2.charAt(j))) { //ascii value of same index characters of the two strings are compared. An int casting is done here.
//do nothing. If the two ascii values are same we iterate the for loop and compare the ascii values of the next two same index characters
//move to next character
}
else{ //if two asciis are not same, we compare to see which one is bigger/smaller.
if((int)temporary1.charAt(j) > (int)temporary2.charAt(j)) { //condition, if ascii of first char is greater, we swap the two strings
tempor[0] = temp[i + 1];
temp[i + 1] = temp[i];
temp[i] = tempor[0];
finish = true;
j = j + 100;
}
else{
j = j + 100;
//do nothing
}
}
}
}
}
return temp;
}}
代碼正在訪問長度小於12的數組的第12個元素(索引11)。*搜索*以獲取錯誤消息和*讀取其他人提出的問題,以便您可以得到一些建議。 – user2864740
首先表達你想做什麼? – mok