部分填充数组空值

时间:2014-10-26 17:32:44

标签: java null

所以我现在已经集思广益了,我即将完成作业的最后一步。我认为我实际上已经完成了,我只需要帮助摆脱这些空值:

这里是代码:

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新手

1 个答案:

答案 0 :(得分: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
    }
}