0

I'm coming here with another question because I've ran into a snag and haven't been able to figure out what the issue is..

My problem: Create an array of 256 characters, and read a message character by character from keyboard and store them in the array up to 256 symbols. The method should return number of the characters stored in the array. Then pass the array to another method to print each word of the message in a line.

My attempted solution:

public static void main(String[] args){
    char[] arrItem7 = new char[256];
    readArray(arrItem7);
    printOneInLine(arrItem7);
}

public static char[] getMsg(){
    String myMessage;
    System.out.print("Input Message: ");
    Scanner input = new Scanner(System.in);
    myMessage = input.nextLine();// Read a line of message
    return myMessage.toCharArray();
}  

public static char[] readArray(char[] arr){
    arr = getMsg();
    return arr;
}

public static void printOneInLine(char[] arr){
    for(int i = 0; i < arr.length; i++){
        if(arr[i] == 0){
            System.out.print(" ");
        }else{
            System.out.print(arr[i]);
        }
    }
    System.out.println();
}   

The program prompts for input but then, unfortunately, prints NULL. I must be doing something wrong when setting the array to my message method.. Can someone help me? I've been trying to wrack my brain for the past 20 minutes.. Thanks so much

BUY
  • 705
  • 1
  • 11
  • 30

1 Answers1

1

Have a look at this answer: Is java pass by reference or pass by value.

In short, Java is pass by value. Which means when you pass the array into your readArray() method, you in fact just pass the reference to that array into it. When you then assign a new array to the input parameter, you are overwriting the reference it's pointing to. You're not changing the original array. So the arrItem7 in the main method still points to the originally created array.

As you have found out, this does not work in the way you're using it. You could remove readArray() completely and just assign the value of getMsg directly to arrItem7:

public static void main(String[] args){
    char[] arrItem7 = getMsg();
    printOneInLine(arrItem7);
}
Catherine
  • 99
  • 9
Lino
  • 19,604
  • 6
  • 47
  • 65
  • Hi there, I have to use readArray method to get the message. My assignment requires it.. I've been trying to figure out how the pass by value and pass by reference works but I haven't come to a solution – countercoded Jun 29 '18 at 22:44