Java Basics of Programming: Store word in an Array and output it

So for my programming class I'm supposed to write a program which stores characters in a array and removes things and adds things to the input etc. But my problem starts at the very beginning I can't even get it to store the information in the array and then output it. So basically if I write Hello, it should simply return Hello.

import java.io.IOException;

public class CharArrayOps {
public static void main(String [] args) throws IOException{
final int buffersize = 50;
char [] buffer = new char [buffersize];
char c;
int counter = 0;

	for (int i= 0; i< buffer.length; i++)
		buffer[i]= ' ';
	System.out.println("Type in a letter sequence: ");
	while ((c = (char) System.in.read()) != '\r' && (c!= '\n')){
		if (counter==buffer.length){
			System.out.println("Entry is too long"); 				

		}

		buffer[counter++] = c;
	}
	System.out.print(c);

}

}

Here's what I got. Any ideas?

i made something yesturday that might help with this
ima go find it

found it
https://forum.teksyndicate.com/t/loop-wont-let-me-input-new-data/92270/2

Could you post the exact problem cause I"m confused on what you really need solved....

I know i've got a java program somewhere that did just this. I'll check.

Your print statement needs to be inside the while loop. Because once the while loop is finished executing, there is nothing left in your "c" variable (well technically there would probably be a new line character). Here is your code working:

public class CharArrayOps {
public static void main(String [] args) throws IOException {
    final int buffersize = 50;
    char [] buffer = new char [buffersize];
    char c;
    int counter = 0;

    for (int i= 0; i< buffer.length; i++)
        buffer[i]= ' ';
    System.out.println("Type in a letter sequence: ");
    while ((c = (char) System.in.read()) != '\r' && (c!= '\n')){
        if (counter==buffer.length){
            System.out.println("Entry is too long");

        }

        System.out.print(c);
        buffer[counter++] = c;
    }
    
}

}
1 Like

Ah thank you that fixed it