Java 中的无限循环
因此,我尝试查看输入,并计算符合特定条件的单词(或者更确切地说,排除我不想计算的单词)。错误出现在以下代码中:
BufferedReader br;
BufferedWriter bw;
String line;
int identifiers = 0;
boolean count = false;
try
{
br = new BufferedReader(new FileReader("A1.input"));
line = br.readLine();
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();
}
这是输入文件:
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
正如上面代码中的注释所述,第一个 println 语句重复打印 6 (向我表明 while 循环无限重复)。第二个“测试目的”println 语句连续重复打印INT f2(INT x
)。
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.readLine();
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来您从未真正阅读过文件的下一行。将此位:更改
为:
It looks like you're never actually reading the next line of the file. Change this bit:
to this:
您使用
while()
仅评估当前行;因此,它永远不会null
。将其更改为if()
。Your use of
while()
is evaluating the current line only; thus, it's nevernull
. Change it toif()
.