【问题标题】:convert line from text file into variables JAVA将文本文件中的行转换为变量 JAVA
【发布时间】:2011-04-18 01:44:59
【问题描述】:

我正在尝试从文本文件中提取单行的数字并对它们执行操作并将它们打印到新的文本文件中。

我的文本文件读到类似

10 2 5 2

10 2 5 3

等等……

我喜欢做一些严肃的数学运算,所以我希望能够调用我正在使用的行中的每个数字并将其放入计算中。

似乎最好使用数组,但是要将数字放入数组中,我必须使用字符串标记器吗?

【问题讨论】:

  • java.util.StringTokenizer 已替换为 String.split(String)。它更易于使用,并使您的代码更加简洁。

标签: java arrays text


【解决方案1】:
Scanner sc = new Scanner(new File("mynums.txt"));
while(sc.hasNextLine()) {
    String[] numstrs = sc.nextLine().split("\\s+"); // split by white space
    int[] nums = new int[numstrs.length];
    for(int i = 0; i < nums.length; i++) nums[i] = Integer.parseInt(numstrs[i]);

    // now you can manipulate the numbers in nums[]

}

显然您不必使用int[] nums。你可以这样做

int x = Integer.parseInt(numstrs[0]);
int m = Integer.parseInt(numstrs[1]);
int b = Integer.parseInt(numstrs[2]);
int y = m*x + b; // or something? :-)

或者,如果你提前知道结构都是整数,你可以这样做:

List<Integer> ints = new ArrayList<Integer>();
Scanner sc = new Scanner(new File("mynums.txt"));
while(sc.hasNextInt()) {
    ints.add(sc.nextInt());
}

它创建了不太理想的 Integer 对象,但这些天并不昂贵。你可以随时将其转换为int[],然后将它们吞入其中。

【讨论】:

  • int y = m*x + b; 对我来说听起来像是一些严肃的数学,就像 OP 想要的那样 :)
猜你喜欢
  • 1970-01-01
  • 2013-11-26
  • 1970-01-01
  • 1970-01-01
  • 2012-03-17
  • 2014-05-31
  • 2015-02-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多