简体   繁体   中英

Java while(input.hasnextline) loop not exiting?

SO I'm supposed to determine the number of lines in a text file (a 100 lines containg numbers) and then create an array with the the number of lines, but the first while loop used to find out the number of lines in the text file never exits. The second loop which is the exacts same one works just fine. Please help me out!

static void main(String[] args) throws Exception{
    java.io.File file = new java.io.File("seriesOfNumbers.txt"); //file instance                
    Scanner input = new Scanner(file); //Scanner
    int M =0 ;
    while (input.hasNextLine() && !input.equals(null))// ** Loop never exits, tried almost everything
    {
        k++;
    }
    double[] numberArray = new double[k];
    int V = 0;
    while (input.hasNextLine())// When I exit the first loop this one exits just fine
    {
        numberArray[j] = (double) input.nextInt();
        j++;
    }               

You are never consuming your input in the first loop, do that with input.nextLine() .

You are now looping until input.hasNextLine() becomes false, but that never happens, because you do not consume the input.

Use input.next() to move to next line. In While condition you are checking the has next line and not null. Thats y it is in infinite loop.

In this below code, this is initialising

Scanner input = new Scanner(file); //Scanner

This is reading

int M =0 ;
while (input.hasNextLine() && !input.equals(null))
{
    input.nextLine();  // Use this to advance the lines from scanner
    k++;
}

It seems to me that you could use FileUtils class from apache.commons.io project to do the trick.

static void main(String[] args) throws Exception{
    List<String> lines = FileUtils.readLines(new File("..."));

Now, if you really need the numberArray for some other computation, you can

    double[] d = new double[lines.size()];

Or you can use the Collection to iterate

    for (String line : lines) {
        double n = Double.parseDouble(line);

To use FileUtils, take a look at http://commons.apache.org/proper/commons-io/

But, iof all that you want is to know what is wrong with your code, you should call the method Scanner.nextLine() inside your first while loop.

In order to stop the infinite looping of the while loop even after consuming the required inputs, we can use a break statement.

Here is an example,

    while (scanner.hasNextLine()) {
            String[] arr = scanner.nextLine().split(" ");
            long[] ar = new long[n];
            for (int i = 0; i < n; i++) {
                ar[i] = Long.parseLong(arr[i]);
            }
            long result = sum(ar);
            System.out.println(result);
            break;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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