简体   繁体   English

Java扫描仪而循环不会停止

[英]java scanner while loop wont stop

Im a first year CS student and I am working on an assignment but I ran into this while loop that won't stop... 我是CS大学一年级的学生,正在做作业,但是遇到了这个while循环,不会停止...

import java.io.*;
import java.util.Scanner;

class Ass1{
public static void main(String[] args){
    int i=0;

    try{
        File myfile = new File ("./ages.txt");
        Scanner scanner = new Scanner(myfile);

        while(scanner.hasNext()){
            i++;
        }
        System.out.println("ages.txt contains " + i + " lines");
        scanner.close();
    }catch(IOException e){}
}
}

and the ages.txt file looks like the following (They are meant to be all in separate lines but somehow I can only show them in a line here :( ) 和ages.txt文件如下所示(它们本应全部放在单独的行中,但不知何故我只能在这里显示它们:()

200 201 202 203 205 205 207 208 210 213 214 217 218 219 219 221 225 226 227 227 231 232 238 238 240 309 313 314 200 201 202 203 205 205 207 208 210 213 214 217 218 219 219 221 225 226 227 227 231 232 238 238 240 240 309 313 314

I am trying to read all the lines from the text file and at the end print how many lines it contains. 我试图从文本文件中读取所有行,最后打印出它包含多少行。

Thank you in advance for your help. 预先感谢您的帮助。

You need to advance your scanner by calling scanner.next(); 您需要通过调用scanner.next();来推进扫描仪scanner.next();

If you were counting lines, it would be better to use scanner.hasNextLine() and scanner.nextLine() respectively. 如果要计算行数,最好分别使用scanner.hasNextLine()scanner.nextLine()

The way you have it written, scanner.hastNext() will always evaluate to true as the scanner has never actually left it's initial position, so there will always be a hasNext() 编写方式, scanner.hastNext()将始终为true,因为扫描器从未实际离开其初始位置,因此始终会有hasNext()

那是因为您没有在while循环内调用nextInt()方法,这意味着扫描器永远不会前进到下一个标记。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM