Bob
Bob

Reputation: 51

Java reading a file of numbers and printing them out

I have this code

Scanner scanner = new Scanner("hello.txt");
   while(scanner.hasNextInt()){
       int i = scanner.nextInt();
       System.out.println(i);
    }

the data values I have in a hello.txt are

1 2 3 22 33 123

but when I run the program there is no output. Is there something I am not using / line of code??

Upvotes: 0

Views: 1876

Answers (2)

mezzie
mezzie

Reputation: 1296

it should be

Scanner scanner = new Scanner(new File("hello.txt"));

Upvotes: 0

Richard Fearn
Richard Fearn

Reputation: 25491

The Scanner constructor you are using takes a string from which to read values. It's not a filename. There are no integers in the string hello.txt so you get no output.

If you want to read from the file called hello.txt, try

Scanner scanner = new Scanner(new File("hello.txt"));

Upvotes: 5

Related Questions