簡體   English   中英

使用掃描儀將文本文件中的輸入讀取到數組中

[英]Reading input from a text file using scanner into array

我正在嘗試使用掃描儀類從文本文件讀取輸入,並將其傳遞到數組中。 我知道如何使用掃描儀類讀取輸入。 我在這里面臨的唯一問題是我無法傳遞到數組中。

public class ReadItemData {

    public static void main(String[] args) throws Exception {

        Scanner aScanner = new Scanner(new FileReader(
                "src//chapter11//Items.txt"));

            while (aScanner.hasNext()) {
                String code = aScanner.next();
                String sku = aScanner.next();
                double qty = aScanner.nextDouble();

                System.out.println(code + " " + sku + " " + qty);

        }
    }

上面的代碼無需數組概念即可工作。 我想擴展相同的概念,以將上述數據讀入大小為100的數組中。任何建議都將有所幫助。 我的最終目標是按代碼,sku對數組中的輸入進行排序

這就是我使用可比接口進行排序的方式。 如何將這個概念擴展到數組?

我用這樣的東西來排序(沒有數組的概念)

   class Item implements Comparable {
    private int qty;
    private String sku,code;

    public Item(int qty, String sku,String code) {
        this.qty = qty;
        this.sku = sku;
        this.code = code;
    }

    public int getQty() {
        return qty;
    }

    public String getSku() {
        return sku;
    }
    public String getCode() {
            return code;
    }

    public int compareTo(Object o) {
        Item i = (Item) o;
        if (this.getQty() < i.getQty())
        {
            return -1;
        }
        if (this.getQty() > i.getQty())
        {
            return 1;

            }
        return 0;
    }
}

謝謝!!

    String[] array = new String[100];
    int currentIndex = 0;     
    while (aScanner.hasNext()) {
            String code = aScanner.next();
            String sku = aScanner.next();
            double qty = aScanner.nextDouble();

            array[currentIndex] = code;
            array[currentIndex++] = sku;
            array[currentIndex++] = ""+qty;
            currentIndex++;

    }

如評論中所述,您可以使用100行3列的2D數組,如下所示:

Object[][] array = new Object[100][3];
    int i=0,j=0;
    while (aScanner.hasNext()) {
         String code = aScanner.next();
         String sku = aScanner.next();
         double qty = aScanner.nextDouble();
         array[i][j++] = code; // array of row i and columns j 
         array[i][j++] = sku;
         array[i][j]   = qty;
         i++; // increment i since it's for rows
         j=0;//reset j because it's for columns

    } 

暫無
暫無

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

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