Question

I would like to use a Java Scanner to get a command from the user in the form of Command arg arg The args are separated by spaces.

I would like to write the command and args to a String[] called command.

I have now started and this is what I have:

public static void main(String[] args){
    Boot.boot();
    
    Scanner scanner = new Scanner(System.in);
    String[] command = scanner.nextLine().trim().split(" ");
    String[] commandListOutput = Boot.command.commands.get(command[0]);
    Object[][] argsArray = new String[1][command.length - 1];
    Class<?>[] argsArrayClasses = new Class<?>[]{Object[].class};
    
    for(int i = 0; i > argsArray.length - 1; i++){
        if(i != 0){
            argsArray[0][i] = command[i];
        }
    }
    
    
    
    invokeMethod(commandListOutput[commandListOutput.length - 1], "command", argsArrayClasses, argsArray[0]);
    scanner.close();
}
Was it helpful?

Solution

You can do something like

Scanner scanner = new Scanner(System.in);
String[] command = scanner.nextLine().trim().split(" ");

assuming you are reading command from standard input.

OTHER TIPS

From the automation point of view, you should probably avoid this approach and create a CLI solution instead (avoiding manual interactions throughout the process), for that I recommend Apache CLI: http://commons.apache.org/proper/commons-cli/

Even if you are doing this for academic purposes, you should probably leverage its argument parsing approach to help you with your own program.

You may try it this way:

public static void main(String arguments[]) {
    Scanner scanner = new Scanner(System.in);
    try {
        scanner.useDelimiter("\n");
        System.out.println("Gimmi your args separated by spaces:");
        String[] args = scanner.next().trim().split(" ");
        System.out.println(Arrays.toString(args));
    } finally {
        scanner.close();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top