簡體   English   中英

從掃描儀向陣列添加數字

[英]Adding numbers to an array from 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,它將每行作為一個索引保存,如下所示:

MAIN [[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();


}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM