【问题标题】:Recalling specific lines from an Array Java从数组 Java 中调用特定行
【发布时间】:2011-04-18 23:03:27
【问题描述】:

我正在尝试将文本文件加载到数组中,然后使用数组中的元素。

我的文本文件格式为:

1 0 3 4 1

1 0 3 4 2

.....

2 2 2 2 2

我不知道如何提取特定索引处的不同元素以便我可以使用它们,或者对它们进行数学运算。

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



        }
    }
    }
        }   
    }
        }

我主要关心的是执行一个操作,比如从索引 4 的 c.f 中减去索引 3 的 c.f。

【问题讨论】:

  • 也许这只是一个复制粘贴错误,但 while 循环的结束 } 可能应该在 coords.add(c); 之后。

标签: java arrays indexing


【解决方案1】:

“我主要关心的是执行一个操作,比如从索引 4 的 c.f 中减去索引 3 的 c.f。”

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

int foo = c2.f - c1.f;

【讨论】:

  • 如果有帮助,请考虑投票并接受我的回答(也许接受您之前问题的一些答案);)
【解决方案2】:

Java 数组索引从 0 开始。因此 numstrs[1] 指的是 numstrs 的第二个元素。 请注意,您的代码每行需要 6 个数字,但您的示例数据文件仅显示 5。

另外,您确定要将变量命名为 a、b、c、d、e、f 吗? 也许这更有用:

public int a[6];

【讨论】:

  • 我知道,实际上我跳过了一个数字,它是一个行计数器。我在底部编辑了我的问题。
猜你喜欢
  • 2017-12-05
  • 1970-01-01
  • 1970-01-01
  • 2013-10-29
  • 2011-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多