Read a message character by character from keyboard and store in an array up to 256 characters
Read a message character by character from keyboard and store in an array up to 256 characters
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
input.nextLine()
return number of the characters stored in the array -
char readArray
- looks like you have failed– David Conrad
Jun 29 at 7:35
char readArray
1 Answer
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.
readArray()
arrItem7
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
:
readArray()
getMsg
arrItem7
public static void main(String args){
char arrItem7 = getMsg();
printOneInLine(arrItem7);
}
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
2 days ago
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
read a message character by character from keyboard -
input.nextLine()
- looks like you have failed– Scary Wombat
Jun 29 at 6:49