所以我试着查看一个输入,并计算符合某个标准的单词(或者更确切地说,排除我不想计算的单词)。错误在以下代码中:
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
。
答案 0 :(得分:6)
看起来你实际上从未真正阅读过该文件的下一行。改变这一点:
try
{
br = new BufferedReader(new FileReader("A1.input"));
line = br.readLine();
while(line != null)
{
到此:
try
{
br = new BufferedReader(new FileReader("A1.input"));
while((line = br.readLine()) != null)
{
答案 1 :(得分:5)
您对while()
的使用仅评估当前行;因此,它永远不会null
。将其更改为if()
。