1

i'm working on my project in JAVA and i have .txt file that contain data like this :

3.4413 44.5444 22.793
33.3321 222.1333 44.7785
23.3001 31.1333 4.7785
77.9999 8.0001 -1.3213 3.2311

so how can i read the .txt file and convert it to :

double[0][0] = {3.4413,44.5444,22.793}
double[0][1] = {33.3321 222.1333 44.7785}
double[1][0] = {23.3001 31.1333 4.7785}
double[1][1] = {77.9999 8.0001 -1.3213 3.2311}

Idham Choudry
  • 559
  • 8
  • 27

1 Answers1

0

If you are sure that you'll be getting only 3 entities in every line then you can do something like this:

public static void main (String[] args) 
{
    double[][] arr = new double[10][3];
    int ptr = 0;
    Scanner in = new Scanner(System.in);

    while(in.hasNext()) {
        arr[ptr][0] = in.nextDouble();
        arr[ptr][1] = in.hasNext() ? in.nextDouble() : 0d;
        arr[ptr++][2] = in.hasNext() ? in.nextDouble() : 0d;
    }
}

Please note that here I have used Scanner and am taking input from System.in. You can replace it to take input from your file.

Considering the above input this will result in the following output:

arr[0][0] -> 3.4413
arr[0][1] -> 44.5444
arr[0][2] -> 22.793

For the first row and so on.

user2004685
  • 8,721
  • 4
  • 29
  • 49