Вопрос

This is a relatively simple question but I couldn't see what is wrong. This is my code:

public class Average {
public double findAverage(){
    try {
        long total = 0;
        int count = 0;
        FileWriter f = new FileWriter("C:\\Users\\Bob\\Desktop\\numbers.txt");
        Scanner in = new Scanner(f); 
        while (in.hasNext()){
            total += in.nextInt();
            count++;
        }
        return total/count;
    } catch (IOException e){
        System.out.println(e.getMessage());
        return 0;
    }
  }

Under (f) the compiler says "Cannot resolve constructor Scanner(java.io.FileWriter). I don't understand what I am doing wrong.

I tried doing:

Scanner in = new Scanner(new File("numbers.txt")); and placing my file where all my java files are located and it worked. However I explicitly need to have it working when the file is somewhere else, and I can't seem to know how to do that. So what am I doing wrong?

EDIT:

I found my mistake. In case anyone else might fins this useful I was supposed to use new File instead of new fileWriter.

Это было полезно?

Решение

You cannot pass a FileWriter to Scanner. Have a look at the documentation.

Другие советы

import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class Average {

public double findAverage(){
    try {
        long total = 0;
        int count = 0;
        FileReader f = new FileReader("C:\\Users\\xyz\\Desktop\\numbers.txt");
        Scanner in = new Scanner(f); 
        while (in.hasNext()){
            total += in.nextInt();
            count++;
        }
        return total/count;
    } catch (IOException e){
        System.out.println(e.getMessage());
        return 0;
    }
}
public static void main(String[] args) {

    Average ob=new Average();
    ob.findAverage();
}   

}

try

    FileWriter f = new FileWriter(new File("C:\\Users\\Cristian\\Desktop\\numbers.txt"));

Thats not a solution, it just removes the compilation error.

    return total/count; // Integer division 
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top