2017-03-03 84 views
1

我試圖創建代碼以消除用戶輸入字符串中的空格刪除空格,但是我收到一個錯誤在第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); 
    } 
} 

謝謝!

+4

你必須停止你的循環,如果你到達字符串的結尾 – Jens

回答

1

您可以使用String類的函數。只需使用line.replace(「」,「」)

+0

嗨,我的教授要求我們手動編碼。但是,謝謝你,我會搜索它。 – Katrina

+0

然後你需要停止循環,例如 if(i> phrase。長度)休息; – Markus

0

爲什麼要重新發明輪子?只要使用字符串的方法replace

String output = line.replace(" ", ""); 
+0

嗨,謝謝你,但我的教授要求我們手工編碼:) – Katrina

+0

@Katrina你應該爲你的問題添加這條信息,以便其他人可以發表他們的答案。 – QBrute

+0

你說得對,我現在編輯它。我沒有意識到已經存在一種方法。 :) – Katrina

1

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 15 at practice5.main(practice5.java:16)

當數組元素的調用是不存在的指數是由該則拋出ArrayIndexOutOfBoundsException。

在你的代碼中,在第16行,你打電話phrase[n+1],除了n==(phrase.length-1)因爲那麼n + 1將等於phrase.length,所有情況下都可以正常工作。

長度從1開始計數,而索引從0開始計數。因此,在最後一次迭代期間,phrase[n+1]等於phrase[phrase.length],這是一個超出限制的索引。

您可以通過減少循環迭代1。

+1

嗨,請問是否每次人物移動時,這裏:phrase [n] = phrase [n + 1]; phrase.length也變小了嗎?另外,感謝您的回覆。我明白你在說什麼,但我仍然不確定如何編碼:/我試過(n = i-1; n Katrina

+0

@Katrina你的循環需要'for(n = i; n

+0

嗨@ adeen-s,我也試過這個,我仍然得到相同的錯誤:( – Katrina

1

原因錯誤更正:ArrayIndexOutOfBound

假設侑一句話是:ABC。現在當你將執行代碼...這是發生...

第一迭代:是在索引0(即,在一個).2nd迭代,是指數1(即,在b)一種ND上第三迭代中,是索引3(上c)中,並再次遞增1,所以現在i = 4的。現在

while(phrase[i]!='\0') 

將返回這樣的例外,因爲你是比較索引4處的值而不可用。因此,發生這種異常。

0

使用CharMatcher確定

whether a character is whitespace according to the latest Unicode standard

CharMatcher.whitespace().trimAndCollapseFrom("user input",""); 
2

嘗試使用下面的代碼,它可以幫助

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(); 
    String result = ""; 

    for (int i = 0; i < phrase.length; i++) { 
     if (phrase[i] != ' ') { 
      result += phrase[i]; 
     }   
    } 

    System.out.println(result); 
} 
+0

工作良好,如果要求不是一直保存在char數組中的話,也可以刪除繼續,如果你移動+號裏面的if和否定條件 – XtremeBaumer

+0

@XtremeBaumer謝謝你的建議,更新回答!!! – Naman