2014-10-26 55 views
-2

所以我已經頭腦風暴了一段時間了,即時在我的作業的最後一步和最後一步。我想我究竟做了,這只是我需要幫助擺脫這些空值:部分填充陣列空值

下面的代碼:

public static char[] readArray(char[] words){ 
     char[] letters = new char[words.length]; 
     letters = myInput(); //get input message 

     for (int i = 0 ; i < letters.length ; i++) 
      letters[i] = words[i] ; //store message to array of words 

     return words; 
    } 
    public static char[] myInput(){ 
     // method to take message from user 
     String myMessage; 
     System.out.print("Input message: "); 
     Scanner myIn = new Scanner(System.in); 
     myMessage = myIn.nextLine();// Read a line of message 
     return myMessage.toCharArray(); 
    } 
    public static void printOneInLine(char[] words){ 
     //for every word, print them in a line 
     for (int i = 0 ; i < words.length ; i++){ 
      if (words[i] == ' ') // words separated by space creates a new line 
       System.out.println(); 
      else 
      System.out.print(words[i]); //print the word 
     } 
    } 

測試用例:

input = hello world 
output = 
hello 
world NUL NUL NUL NUL ... 

我知道數組是部分填充並且因爲i < words.length系統會嘗試顯示從0 - 256的數組值。任何建議將很樂意讚賞。 PS:新到Java

+0

你應該改變你的問題。你試圖達到什麼目的?你嘗試了什麼,爲什麼它沒有工作? – 2014-10-26 17:34:50

+1

爲什麼你用'char []'而不是'String'? – 2014-10-26 17:35:19

+0

@cypressious我試圖擺脫NUL NUL NUL NUL。我試圖改變數組的大小,實際上是256.這是一種工作,但不是我真正想要的。 – 2014-10-26 17:42:43

回答

0

它的時間來簡化這個:擺脫readArray方法,它不會對myInput頂部添加值,並使用myInput代替。如果你這樣做的main(),這將很好地工作:

char[] words = myInput(); 
printOneInLine(words); 

你的代碼的其餘部分是好的,因爲它是 - 沒有其他的變化是必要的(demo)。

該指令說,方法readArray應該返回存儲在數組中的字符數。

你需要改變你的readArray方法如下:

public static int readArray(char[] words){ 
    char[] letters = new char[words.length]; 
    letters = myInput(); //get input message 

    for (int i = 0 ; i < letters.length ; i++) 
     words[i] = letters[i] ; //store message to array of words 

    return letters.length; 
} 

現在你printOneInLine需要改變,以及 - 它需要採取側面length,並代替words.length使用知道何時停止:

public static void printOneInLine(char[] words, int len) { 
    //for every word, print them in a line 
    for (int i = 0 ; i < len ; i++){ 
     if (words[i] == ' ') // words separated by space creates a new line 
      System.out.println(); 
     else 
      System.out.print(words[i]); //print the character 
    } 
} 
+0

它確實有效,但指令說,方法'readArray'應該返回數組中存儲的字符數。這些值然後傳遞給printOneInLine方法。 – 2014-10-26 17:52:08

+0

我相應地更改了我的代碼,但出現錯誤:http://ideone.com/gUJhWR – 2014-10-26 18:02:52

+0

@BoytanodPitongulo這是因爲您忘記更改主文件。它需要存儲第一個方法返回的int,並將其傳遞給第二個方法。 – dasblinkenlight 2014-10-26 18:07:37