mut*_*y91 1 java stringtokenizer
所以我试着查看一个输入,并计算符合某个标准的单词(或者更确切地说,排除我不想计算的单词).错误在以下代码中:
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();
}
Run Code Online (Sandbox Code Playgroud)
这是输入文件:
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
Run Code Online (Sandbox Code Playgroud)
如上面代码中的注释所述,第一个println语句重复打印6(指示while循环无休止地重复).第二个"测试目的"println语句不断INT f2(INT x重复打印.
看起来你实际上从未真正阅读过该文件的下一行.改变这一点:
try
{
br = new BufferedReader(new FileReader("A1.input"));
line = br.readLine();
while(line != null)
{
Run Code Online (Sandbox Code Playgroud)
对此:
try
{
br = new BufferedReader(new FileReader("A1.input"));
while((line = br.readLine()) != null)
{
Run Code Online (Sandbox Code Playgroud)