简体   繁体   English

并行数组:当输入文件未知时如何初始化数组的长度

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

This is my first time posting on here and I am new to Java. 这是我第一次在这里发帖,并且是Java的新手。 I have assignment due this week and I'm having some trouble getting it started, though I think I know what to do after I start it. 我本周有作业,虽然开始工作有些麻烦,但我想我知道该怎么做。 Ok so the teacher wants us to use parallel arrays and write a program that will create a bar chart. 好吧,老师希望我们使用并行数组并编写一个程序来创建条形图。 So if he gives us an input file that contains: 因此,如果他给我们提供了一个包含以下内容的输入文件:

4 
Sidney
Washington
London
New York
4 
8
10
3

It will print out: 它将打印出:

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

So I have started to write my program. 因此,我开始编写程序。 But I don't know how to initialize the length of the arrays. 但是我不知道如何初始化数组的长度。 He will be giving us how many elements in the first line of the file (so using the example up above the length would be 4), however we will not know what that number is, we have to write a program that will read that number. 他将为我们提供文件第一行中的多少个元素(因此,使用长度上方的示例为4),但是我们不知道该数字是多少,我们必须编写一个程序来读取该数字。 This is what I have 这就是我所拥有的

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];`

It is the int N part that I don't know how to write in order to get it to scan the first line of his input file and use that number. 这是int N的部分,我不知道如何编写才能使它扫描他的输入文件的第一行并使用该编号。

Just use the appropriate constructor of Scanner : 只需使用适当的Scanner构造函数即可:

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

Also, I'd name the variable N as something more descriptive, like arrayLength . 另外,我将变量N命名为更具描述性的名称,例如arrayLength

Be sure, and don't be lazy: use the one with the charset specification! 当然,不要偷懒:使用符合字符集规范的字符集! And of course use the appropriate character set code for the file. 当然,请为文件使用适当的字符集代码。

Warning: As this is an assignment, you'll get asked how and why you used this constructor - be prepared to answer it! 警告:由于这是一项作业,因此您会被问到如何以及为什么使用此构造函数-准备回答它! Not specifying the character set is a common mistake, and found quite some places out in the wild too... 不指定字符集是一个常见错误,并且在野外也发现了很多地方...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM