簡體   English   中英

並行數組:當輸入文件未知時如何初始化數組的長度

[英]Parallel arrays: how to initialize the length of the arrays when the input file is unknown

這是我第一次在這里發帖,並且是Java的新手。 我本周有作業,雖然開始工作有些麻煩,但我想我知道該怎么做。 好吧,老師希望我們使用並行數組並編寫一個程序來創建條形圖。 因此,如果他給我們提供了一個包含以下內容的輸入文件:

4 
Sidney
Washington
London
New York
4 
8
10
3

它將打印出:

   Sidney ****
Wasington *********
   London **********
 New York ***`

因此,我開始編寫程序。 但是我不知道如何初始化數組的長度。 他將為我們提供文件第一行中的多少個元素(因此,使用長度上方的示例為4),但是我們不知道該數字是多少,我們必須編寫一個程序來讀取該數字。 這就是我所擁有的

import java.util.*;
public class BarChart
{
    public static void main(String args[])
    {
    Scanner scan = new Scanner(System.in);
    File file = input;
    // Read in the input file
    int N=input.readInt();

    // Create an array to hold dataLabels, and another to hold dataValues.
    String[] dataLabels = new String[N];
    int[] dataValues= new int[N];`

這是int N的部分,我不知道如何編寫才能使它掃描他的輸入文件的第一行並使用該編號。

只需使用適當的Scanner構造函數即可:

scan = new Scanner(new File("put the path and filename here"), "UTF-8");
int N = scan.nextInt();

另外,我將變量N命名為更具描述性的名稱,例如arrayLength

當然,不要偷懶:使用符合字符集規范的字符集! 當然,請為文件使用適當的字符集代碼。

警告:由於這是一項作業,因此您會被問到如何以及為什么使用此構造函數-准備回答它! 不指定字符集是一個常見錯誤,並且在野外也發現了很多地方...

暫無
暫無

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

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