我試圖創建代碼以消除用戶輸入字符串中的空格刪除空格,但是我收到一個錯誤在第16行從用戶輸入字符串
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 15 at practice5.main(practice5.java:16)
注:我們不允許使用Java的替換方法。我需要手動編碼。
這裏是我的代碼:
import java.util.Scanner;
public class practice5{
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
String line;
System.out.print("Sentence: ");
line = scanner.nextLine();
char phrase[] = line.toCharArray();
int i = 0;
int n = 0;
while(phrase[i] != '\0') {
if(phrase[i] == ' ') {
for(n=i; n<phrase.length; n++) {
phrase[n] = phrase[n+1];
}
}
i++;
}
String output = new String(phrase);
System.out.print(output);
}
}
謝謝!
你必須停止你的循環,如果你到達字符串的結尾 – Jens