簡體   English   中英

使用Bluej無法打印陣列

[英]Trouble printing an array using Bluej

我正在嘗試打印一個由整數分隔的行的文件,我想在加載到數組中后打印值,以便可以處理和打印最小值,最大值,均值,中位數等。

這是我的以下代碼,但僅打印2000

   String txt = UIFileChooser.open();
    this.data = new int[2000];
    int count = 0;
    try {
        Scanner scan = new Scanner(new File(txt));
        while (scan.hasNextInt() && count<data.length){
            this.data[count] = scan.nextInt();
            count++;
        }
        scan.close();
    }
    catch (IOException e) {UI.println("Error");
    }
     {UI.printf("Count:  %d\n", this.data.length);
    }

每次獲得2000作為輸出的原因是,您僅打印出了數組的整個長度,您可以在this.data = new int[2000];行中將其定義為2000 this.data = new int[2000]; 要打印出數組中值的數量,最簡單的方法就是使用count ,因為它已經保存了該數量。 要打印出數組中的所有值,只需遍歷數組直到最后一個值,然后打印每個值。 代碼示例如下:

String txt = UIFileChooser.open();
this.data = new int[2000];
int count = 0;
try {
    Scanner scan = new Scanner(new File(txt));
    while (scan.hasNextInt() && count < data.length){
        this.data[count] = scan.nextInt();
        count++;
    }
    scan.close();
}
catch (IOException e) {
    UI.println("Error");
}

// this line will print the length of the array,
// which will always be 2000 because of line 2
UI.printf("Count:  %d\n", this.data.length);

// this line will print how many values are in the array
UI.printf("Values in array: %d\n", count);

// now to print out all the values in the array
for (int i = 0; i < count; i++) {
    UI.printf("Value: %d\n", this.data[i]);
}

// you can use the length of the array to loop as well
// but if count < this.data.length, then everything
// after the final value will be all 0s
for (int i = 0; i < this.data.length; i++) {
    UI.printf("Value: %d\n", this.data[i]);
}

暫無
暫無

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

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