-3

i am trying to read the input of integers such as

17
100
19
18

on a .txt file, but i always get a FileNotFoundException. It will output the result

0000

if i run the code below:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

public class umm {

    public static void main(String[] args) throws FileNotFoundException  {
        // TODO Auto-generated method stub


        Scanner scanner = new Scanner(new File("huhu.txt"));
        int [] tall = new int [100];
        int i = 0;
        while(scanner.hasNextInt())
        {
             tall[i++] = scanner.nextInt();
             System.out.print(tall[i]);
        }

        scanner.close();
    }

}

if i add the integers in the .txt file so that it will have 6 integers like this

17
100
19
18
2
5

it will output

000000

doesn't this mean that the file exists and it can access it? but why does it keep saying FileNotFound?

eleanor
  • 13
  • 4
  • Use the full path of the file not just *huhu.txt* – Nicholas K Oct 25 '18 at 13:58
  • Well. Because the file isn't found. Ensure you locate the file at the right path. You can print the current path during execution by, e.g. `System.out.println(Paths.get(".").toAbsolutePath());` – Mena Oct 25 '18 at 13:59

3 Answers3

0

Use an absolute path for huhu.txt.

You can see where your program is looking for huhu.txt by running this code.

System.out.println("Working Directory = " +
              System.getProperty("user.dir"));
Neo
  • 79
  • 6
  • i did this and changed the line into something like Scanner scanner = new Scanner(new File("C:\\Users\\eleanor\\workspace\\something\\huhu.txt")); but it is still giving me the FileNotFoundException though – eleanor Oct 25 '18 at 14:09
  • nevermind, i got it. thank you! – eleanor Oct 25 '18 at 14:11
0

Look at this code:

 tall[i++] = scanner.nextInt();
 System.out.print(tall[i]);

The array element you read is not the same as the one you print (you print the next one, because the i++ has increased the index).

This explains all the 0 you get.

It is unclear to me how you get the FileNotFoundException.

Henry
  • 42,982
  • 7
  • 68
  • 84
0

thats because you print the next element in the array that is not yet affected ,so try this

 while(scanner.hasNextInt())
{
        tall[i] = scanner.nextInt();
        System.out.println(tall[i]);
        i++;
}