is there a way to read values from a file int an array and initialize those value?

HIM :
import java.io.*;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        try {
            File file = new File("C:\\Users\\HIM\\IdeaProjects\\File Tutorial\\src\\quad.txt");
            Scanner scanner = new Scanner(file);

            double a , b, c;
            double[] arr = new double[3];
            for(int i = 0; i < arr.length; i++) {
                while (scanner.hasNextLine()) {
                    arr[i] = scanner.nextInt();
                    System.out.println(arr[i]);
                }
            }
            a = arr[0];
            System.out.println(a);
            b = arr[1];
            System.out.println(b);
            c = arr[2];
            System.out.println(c);

        } catch (Exception e){
            System.out.println("Not Found");
        }
    }
}

i used this code, but from the loop that transferred the values 2, 3, 4, into the array it was read successful but i tried initializing those array values into a,b,c, but it only reads the last value and assign it to a.

Christopher Schneider :

You don't say what your input file looks like, so it's hard to tell you exactly what's wrong, but I suspect the issue is you are using hasNextLine in your loop, but nextInt when you read. This won't behave in the way you expect for input like this, for example:

1 2 3

Notice that there is one line, so hasNextLine will return false because, while there are multiple ints, there is only one line.

What you probably want instead is Scanner#hasNextInt

In addition, this logic is probably not correct:

for(int i = 0; i < arr.length; i++) {
   while (scanner.hasNextLine()) {
      arr[i] = scanner.nextInt();
      System.out.println(arr[i]);
 }

When a Scanner moves to the next token, you cannot go back. So you can only read from it once without creating a new scanner.

What you likely want is the following:

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

This will go through the scanner once and correctly populate your values.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=18577&siteId=1