【问题标题】:Get value from txtfile and put it in arrays [closed]从文本文件中获取值并将其放入数组中[关闭]
【发布时间】:2014-01-02 21:29:44
【问题描述】:

我正在尝试读写文件。

我有两个 txt 文件

输入.txt:

   4
   1 1
   2 2
   3 2
   3 3
   2 3

在 output.txt 中,我想从 inputx.txt 中获取价值,就像

    4 //is first value
int[] x = {1,2,3,3,2}
int[] y = {1,2,2,3,3}

如何解析?

【问题讨论】:

  • 要求代码的问题必须表明对正在解决的问题的最低理解。包括尝试的解决方案、它们为什么不起作用以及预期的结果。另见:Stack Overflow question checklist

标签: java arrays io


【解决方案1】:

这里是一个示例代码,它不是最好的方法,只是给你一个提示。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Test {

    public static void main(String[] args) throws FileNotFoundException{
        String filename = "text.txt";
        Scanner sc = new Scanner(new File(filename));
        String s;
        int i = 0;
        int firstVal = 0;
        ArrayList<Integer>x=new ArrayList<Integer>();
        ArrayList<Integer>y=new ArrayList<Integer>();
        while(sc.hasNext()){
            s=sc.next();
            if( s.trim().isEmpty() )
                continue;
            if( i<1 ){
                firstVal = Integer.valueOf(s).intValue();
            }else{
                if(i%2 > 0 ){
                    x.add(Integer.valueOf(s));
                }else{
                    y.add(Integer.valueOf(s));
                }
            }
            i++;
        }
        for(int xv: x){
            System.out.println(xv);
        }
        System.out.println("-----------------");
        for(int yv: y){
            System.out.println(yv);
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多