开发者

Recalling specific lines from an Array Java

I'm trying to load a text file into an array, then work with the elements in the array.

My text file is in the format:

1 0 3 4 1

1 0 3 4 2

.....

2 2 2 2 2

I cant figure out how to extract the different elements at specific indexes so that I can use them, or do math against them.

 import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

        public class Coord {
            public int a,b,c,d,e,f;


        public static void main(String[] args) throws IOException {
            PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("/Users/evanlivingston/3a.txt", true)));
            Scanner sc = new Scanner(new File("/Users/evanlivingston/1.txt"));
            List<Coord> coords = new ArrayList<Coord>();{


                // for each line in the file
                while(sc.hasNextLine()) {
                    String[] numstrs = sc.nextLine().split("\\s+"); 

                    Coord c = new Coord();

                    c.a = Integer.parseInt(numstrs[1]);
                    c.b = Integer.parseInt(numstrs[2]);
                    c.c = Integer.parseInt(numstrs[3]);
                    c.d = Integer.parseInt(numstrs[4]);
                    c.e = Integer.parseInt(numstrs[5]);
                    c.f = Integer.parseInt(numstrs[6]);

                    coords.add(c);



    /开发者_运维百科/ now you have all coords in memory

    for( int i=0; i<coords.size(); i++ ) {
        // j=i+1 to calculate the distance between two points only once, 
        // not one way and back; also skip calculating distance between 
        // the same point
        for( int j=i+1; j<coords.size(); j++ ) { 
            Coord c1 = coords.get(i);
            Coord c2 = coords.get(j);
            System.out.println(c2);



        }
    }
    }
        }   
    }
        }

My main concern is performing an operation like subtracting c.f of index 3 from c.f of index 4.


"My main concern is performing an operation like subtracting c.f of index 3 from c.f of index 4."

Coord c1 = coords.get(3);
Coord c2 = coords.get(4);

int foo = c2.f - c1.f;


Java array indices start at 0. So numstrs[1] refers to the 2nd element of numstrs. Note that your code wants 6 numbers per line but your sample datafile only shows 5.

Also, are you sure you want to name your variables a,b,c,d,e,f? Maybe this be more useful:

public int a[6];
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜