Home > database >  How do I put user input into an array of strings without a scanner in Java?
How do I put user input into an array of strings without a scanner in Java?

Time:05-11

For an assignment, I have to create an array of names and the number of names and all of the names have to be on the command line. The number of names in theory is infinite. For example, java Electricity 2 Bob Alice

Presently my code looks like this:

int numResidents = Integer.parseInt(args[0]);
        String[] names = new String[numResidents];
        for (int i = 0; i < args.length; i  ) {
            names[i] = StdIn.readString(args[i   1]);
        }

This is giving me an error saying "actual and formal argument lists differ in length", and I don't know what that means. I can't use a scanner despite most of the internet suggesting one because at the time this assignment was due, we did not work with scanners yet. How do I do this without one?

CodePudding user response:

If the names are passed to you as parameters from the command line, then you already have them within your args array, which is the parameter of your main, you don't need to read them (I'm assuming StdIn.readString(...) is supposed to do some reading).

Besides, if the user passes the number of names and the names, then the number is redundant, as you can already deduct its value from the args array (args.length).

Your code should look like this with some precautions from malicious input.

// The number of parameters minus the first one already represents the number of names
// This would avoid:
//  - parsing to int a first parameter which could not be an actual int
//  - a negative value
//  - a different number from the actual number of names passed
int numResidents = args.length - 1;
String[] names = new String[numResidents];

// Your loop should start from 1 to skip the first parameter, not assigning the next parameter (i   1) only to skip the number of residents.
// In fact, This would lead to an ArrayIndexOutOfBoundsException when you're going to iterate the last element (i = args.length - 1) and trying to access 
// a not existing one (args[i   1], i.e. the element after the last one...) 
for (int i = 1; i < args.length; i  ) {
    names[i] = args[i];
}

CodePudding user response:

Maybe change args[i 1] to args[i]

int numResidents = Integer.parseInt(args[0]);
    String[] names = new String[numResidents];
    for (int i = 0; i < args.length; i  ) {
        names[i] = StdIn.readString(args[i]);
    }
  • Related