Inputting characters in a loop
I have developed a program which inputs characters in a loop & when I press 'q', it should come out of the loop. But when i PRESS 'q' its not coming out of the loop. The code is as follows:
import java.io.*;
class BRRead {
public static void main (String args[ ] )
throws IOException
{
char c;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters 'q' to quit");
do {
c = (char) br.read();
System.out.println(c);
}
System.out.println(c);
}while (c!= 'q');
}
}
I am working on Java Workshop 2.0 in NT enviroment.
Zulfi.
[704 byte] By [
Zulfi Khan] at [2007-11-15 19:12:30]

# 1 Re: Inputting characters in a loop
it seems like that your while statement and condition is not located correctly, they should be right after the do scope ends.
beside, i can count 3 opening curly brackets, and 4 closing...
slepax at 2007-11-10 3:01:50 >

# 3 Re: Inputting characters in a loop
It's the line "while (c != 'q')"
The following would work:
String myChar = new String(c);
while(!myChar.Equals("q"))
# 4 Re: Inputting characters in a loop
I am still getting errors. I did the following things:
char c[];
while (1) {
c[0] = (char)br.read();
String myChar = new String(c);
System.out.println(c);
if (myChar.equals("q"))
break;
}
The error message is as follows:
"Variable c may not have been initialized"
# 5 Re: Inputting characters in a loop
char c[];
while (1) {
c[0] = (char)br.read();
String myChar = new String(c);
System.out.println(c);
if (myChar.equals("q"))
break;
}
There is a number of things wrong with this. Your error message "Variable c may not have been initialized"
is somewhat true, in actual fact, variable c has NOT been initialized at all.I don't really get why you have
a char arrary and call char[0], usually you would have a loop with something such as char [i], it makes me wonder
why you are even using an array. Assuming you know what you are doing the first thing you must do is come
up with an array size:
char c[];
c = new char[///some function that returns an int, or an actual number]
for simplicity we will use an actual number:: c = new char[4]
I don't know if Java sets the array to some default values, but I usually do it myself such as:
for (int i = 0; i<myCharsize(); i++)
char[i]=//whatever default value I need
Now everything has been initilized and you won't get the error message.