java - 从 Scanner 将数字添加到数组

标签 java java.util.scanner

我有一个包含以下内容的文本文件:

10/23/2013  47  34  23  31  03  13  
10/19/2013  33  09  56  54  57  05  
10/16/2013  03  42  26  34  28  27  
10/12/2013  10  58  26  57  08  04  

我能够使用 Scanner 并将日期添加到 ArrayList“DATE”,并将其余数字添加到另一个 ArrayList“NUM”(参见代码)

我正在尝试构建一个 ArrayList>“MAIN”,甚至是一个 HashMap,它将每行作为索引,如下所示:

主[[47,34,23,31,03,13],[33,09,56,54,57,05],[03,42,26,34,28,27],[10, 58,26,57,08,04]]

我无法使用下面的代码获得所需的结果,我需要帮助重组代码以获得所需的结果

谢谢。

   public class Grades {

static String line;
static BufferedReader reader;

static String file = "file/Grades.txt";

static ArrayList<ArrayList<String>> MAIN;
static ArrayList<String> NUM ;

static ArrayList<String> DATE ;
static ArrayList rand;

static int index = 0;

public static void main(String args[]) {

    MAIN = new ArrayList<ArrayList<String>>();
    //lotoNum();



    DATE = new ArrayList<String>();



try {
    Scanner scan = new Scanner(new BufferedReader(new FileReader(file)));

    wwhile(scan.hasNextLine()){
        NUM = new ArrayList<String>();

        String token = scan.nextLine();
        String [] line = token.split("  ");


            DATE.add(line[0]);

            for (int i = 1; i < line.length; i++){
                NUM.add(line[i]);
            }
            MAIN.add(index, NUM);
                index++;


                System.out.println(MAIN);

                //NUM.clear();
                //NUM.trimToSize();


        }


        }

    } catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

}
 }

输出:
[[47, 34, 23, 31, 03, 13]]
[[47, 34, 23, 31, 03, 13], [33, 09, 56, 54, 57, 05]]
[[47, 34, 23, 31, 03, 13], [33, 09, 56, 54, 57, 05], [03, 42, 26, 34, 28, 27]]
[[47, 34, 23, 31, 03, 13], [33, 09, 56, 54, 57, 05], [03, 42, 26, 34, 28, 27], [10, 58, 26, 57, 08, 04]]

最佳答案

试试这个

int index = 0;

while (scan.hasNextLine()){
    String line = scan.nextLine();
    String[] tokens = line.split("  ");

    // you must create a new list everytime or else they will 
    // reference the same object.  That's why you're getting the output.
    // you are.  Also delete the declareation outside of this loop
    // ArrayList<String> NUM;   ----    NUM = new ArrayLis<String>();

    ArrayList<String> NUM = new ArrayLis<String>();

    DATE.add(tokens[0]);

    for (int i = 1; i < tokens.length; i++){
        NUM.add(tokens[i]);
    }

    MAIN.add(index, NUM);
    index++;

    System.out.println(MAIN);

    NUM.clear();


}

关于java - 从 Scanner 将数字添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19826998/

相关文章:

Java if(是或否语句)

java - 使用java的扫描器读取输入

Java,扫描大文件,findWithinHorizo​​n(p, 0) 抛出异常 java.lang.StackOverflowError

java - Scene Builder 2.0 忽略 Controller

java - 为什么 Java 程序需要 "main()"方法?

java - 使用 Active Directory 在 android 中进行单点登录

java - DataNucleus/NeoDatis - 数据库连接似乎关闭,导致持久对象丢失

java - 如何格式化带有前导零的Java字符串?

java - 为 Scanner 类创建一个实例,但不为 java 中的 Math 类创建一个实例?

java - 扫描器如何进行字符串比较?