0

My CS class was given the following assignment:

Write a method called boyGirl that accepts a Scanner that is reading its input from a file containing a series of names followed by integers. The names alternate between boys’ names and girls’ names. Your method should compute the absolute difference between the sum of the boys’ integers and the sum of the girls’ integers.

Here is my code:

import java.io.*;
import java.util.*;
public class Chapter_6_Exercises
{
    public static void main(String[] agrs)
                        throws FileNotFoundException {
        Scanner a = new Scanner(new File("c6e1.txt"));
        boyGirl(a);
    }

    public static void boyGirl(Scanner input)
                       throws FileNotFoundException {
        int boySum = 0;
        int girlSum = 0;
        int count = 0;
        int sumDifference = 0;
        while(input.hasNextInt()) {
           count++;
           if(count%2 == 0) {
              girlSum += input.nextInt();     
           } else {
              boySum += input.nextInt();    
           }
        }
        sumDifference = Math.abs(boySum-girlSum);
        System.out.println("boySum = " + boySum);
        System.out.println("girlSum = " + girlSum);
        System.out.println("Difference between boys' and girls' ");
        System.out.println("sums is " + sumDifference);
    }
}

The code compiles file but when I try to run it I get the following error:

java.io.FileNotFoundException: c6e1.txt (The system cannot find the file specified)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.util.Scanner.<init>(Scanner.java:611)
    at Chapter_6_Exercises.main(Chapter_6_Exercises.java:7)

However, I have already created file c6e1.txt and i'm not sure how to fix the error.

gogov
  • 9
  • 5

3 Answers3

1

You have to give proper path to the file like so,

Scanner a = new Scanner(new File("C:\\data\\c6e1.txt"));

If you give the path as c6e1.txt, it can't identify it. You either have to give relative path if the file is in your project, resources directory, or else consider giving the absolute path of the file as I have done above.

Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63
-1
Scanner a = new Scanner(new File("c6e1.txt"));

Java will accept it only if the '.txt' file is at the location where '.java' file is located. In other case you have to mention the full location(path) of '.txt' file as ("C:(folder\c6e1.txt")

Pang
  • 9,564
  • 146
  • 81
  • 122
-2

You should give fully qualified name for that file. For Ex: File in your system D: Drive D:/download/file name.txt

PAWAN KPK
  • 37
  • 1
  • 3