Infinite Loop in Java
So I'm trying to look at an input, and count words that fit a certain criteria (or rather, excluding words that I don't want to count). The error is in the following code:
BufferedReader br;
BufferedWriter bw;
String line;
int identifiers = 0;
boolean count = false;
try
{
br = new BufferedReader(new FileReader("A1.input"));
line = br.readLi开发者_运维百科ne();
while(line != null)
{
StringTokenizer t = new StringTokenizer(line);
String word;
System.out.println(t.countTokens()); //for testing, keeps printing 6
for(int c = 0; c < t.countTokens(); c++)
{
word = t.nextToken();
count = true;
if(Character.isDigit(word.charAt(0))) //if word begins with a number
{
count = false; //do not count it
}
if(count == true)
{
for(String s : keywords)
{
if(s.equals(word)) //if the selected word is a keyword
{
count = false; //do not count it
}
}
}
System.out.println(word); //testing purposes
}
word = t.nextToken();
}
Here is the input file:
INT f2(INT x, INT y )
BEGIN
z := x*x - y*y;
RETURN z;
END
INT MAIN f1()
BEGIN
INT x;
READ(x, "A41.input");
INT y;
READ(y, "A42.input");
INT z;
z := f2(x,y) + f2(y,x);
WRITE (z, "A4.output");
END
As stated in the comments in the code above, the first println statement prints 6 repeatedly (indicating to me that the while loop is endlessly repeating). The second "testing purposes" println statement continuously prints INT f2(INT x
repeatedly.
It looks like you're never actually reading the next line of the file. Change this bit:
try
{
br = new BufferedReader(new FileReader("A1.input"));
line = br.readLine();
while(line != null)
{
to this:
try
{
br = new BufferedReader(new FileReader("A1.input"));
while((line = br.readLine()) != null)
{
Your use of while()
is evaluating the current line only; thus, it's never null
. Change it to if()
.
精彩评论