开发者

Java reading a file of numbers and printing them out

开发者 https://www.devze.com 2023-01-18 02:28 出处:网络
I have this code Scanner scanner = new Scanner(\"hello.txt\"); while(scanner.hasNextInt()){ int i = scanner.nextI开发者_StackOverflow中文版nt();

I have this code

Scanner scanner = new Scanner("hello.txt");
   while(scanner.hasNextInt()){
       int i = scanner.nextI开发者_StackOverflow中文版nt();
       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??


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"));


it should be

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

精彩评论

暂无评论...
验证码 换一张
取 消