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);
}
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;
}
}
}