Read ints from txt file java error

Can you tell me what's the problem? I'm trying to read integers from the file named "tablica.txt" and it looks like that in a file: 8 3 2 1 4 3 2

package Operacje_na_plikach;

import jdk.nashorn.internal.ir.WhileNode;

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

public class Zad1 {
    /*
    Plik tekstowy ‘tablica.txt’ ma postać: 8 3 2 1 4 3 2 Pobierz liczby z pliku tekstowego do tablicy i wypisz na ekranie sumę elementów tej tablicy.
     */
    public static int[] odczyt(String nazwa) {
        int[] arr = null;
        try {
            FileReader reader = new FileReader(nazwa);
            Scanner sc = new Scanner(reader);
            int d = sc.nextInt();
            int suma = 0;
            arr = new int[d];
            for (int i = 0; i < d; i++) {
                arr[i] = sc.nextInt();
                suma += arr[i];
            }

            sc.close();
            reader.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return arr;
    }

    public static void main(String[] args) {
        int[] arr = odczyt("tablica.txt");
        if (arr != null) {
            System.out.println(Arrays.toString(arr));
        }
    }
}

Error:

Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Scanner.java:862) at java.util.Scanner.next(Scanner.java:1485) at java.util.Scanner.nextInt(Scanner.java:2117) at java.util.Scanner.nextInt(Scanner.java:2076) at Operacje_na_plikach.Zad1.odczyt(Zad1.java:27) at Operacje_na_plikach.Zad1.main(Zad1.java:42)


Your code is reading the first number, and then using that value to determine how many more numbers to read.

Your input is 8 3 2 1 4 3 2 , so your program reads the 8 , and then tries to read 8 more numbers.

Since there are only 6 more numbers, when you try to read the 7th you get an error.

链接地址: http://www.djcxy.com/p/96086.html

上一篇: Scanner next()为某些联机编译器抛出NoSuchElementException

下一篇: 从txt文件读取ints java错误