Question

I have a particular set of code, which is going to read a text from a file (Alice.txt) and then put every word into an array and count the total amount of words and the words individually.

I have a draft of something, but blocking my way towards my goal is an error which I get. First, the code:

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

public class Oblig3A{
    public static void main(String[]args){
    OrdAnalyse O = new OrdAnalyse();
    OrdAnalyse.analyseMet();
    }
}

class OrdAnalyse {
    public static void analyseMet() {
    Scanner Inn = new Scanner(System.in);
    System.out.println("Vennligst oppgi navn til lagringsfilen: ");
    String Filen;
    Filen = Inn.nextLine();

    try {
        File skrivFil = new File(Filen);
        FileWriter fw= new FileWriter(skrivFil);
        BufferedWriter bw = new BufferedWriter(fw);

        File lesFil = new File ("Alice.txt");
        FileReader fr = new FileReader(lesFil);
        BufferedReader br = new BufferedReader(fr);

        int teller=0;
        int i=0;
        while(lesFil.hasNext()){
        teller++;
        lesFil.next();
        }
        String[] ordArray = new String[teller];
        int[] antall = new int[teller]
        do{
        ordArray[i]=lesFil.next();
        }
        while(lesFil.hasNext());
        System.out.println(ordArray.length);

    }catch (Exception e){
        System.out.print(e);
    }
    }
}

And I get this error:

Oblig3A.java:29: error: cannot find symbol
        while(lesFil.hasNext()){
                    ^
  symbol:   method hasNext()
  location: variable lesFil of type File

Is there anyone who could give me a pointer as to why this is happening? I really don't know.

Was it helpful?

Solution

hasNext() is a method in the Scanner class, which parses a stream into tokens.
It doesn't exist in a File.

You want to create a new Scanner(lesFil) and use that instead.

You also don't need your two readers.

OTHER TIPS

The File class doesn't have a hasNext() method. Perhaps you wanted to create a Scanner using the File. The Scanner class has a hasNext() method.

Scanner scanner = new Scanner(lesFil);

You want to call readLine() on br, not hasNext() on lesFil. Files aren't iterators; doing line-by-line reading is why you created the BufferedReader. If you want a hasNext(), create a Scanner like others have said.

Your while isn't supposed to end with a ;

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top