简体   繁体   中英

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. 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. 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.

Just use the appropriate constructor of 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 .

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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