Home > Enterprise >  How do I get a Java compiler to execute the right function based on the number of user inputs?
How do I get a Java compiler to execute the right function based on the number of user inputs?

Time:01-30

I am writing a program where the user can input up to two values, so if the user inputs one value, it calls the first constructor and if the user inputs 2 values the second constructor is called, but the issue is when the user inputs one value and press enter, the compiler will be waiting for the second value.

Basically, I want the compiler to execute the function based on the number of inputs. Also, I can't ask the user how many inputs he wants to add before either.

Basically, I'm trying to see if writing java ValuM 5 or java ValuM 5 6 in the command line and get the right function executed.

Someone said it to use the timer Class, to put it in a timeout, but I'm not sure how it works, of if there is an easier way to do this.

import java.util.Scanner;
import java.util.Timer;
public class ValueM {
    public static void main(String[] args) {
        Scanner myObj = new Scanner(System.in);
        int first_Input=myObj.nextInt();
        int Second_Input=myObj.nextInt();
    
        ValueM array_gen=new ValueM(first_Input);
        array_gen=new ValueM(Second_Input,first_Input);
    }
}

CodePudding user response:

What you could do is to require the user to enter both numbers on the same line. That way you could use myObj.nextLine() and check if it contains one or two numbers. (I would rename myObj to scanner or something similar.)

To check if the line contains one or two numbers, you could create a second Scanner with the line as the source: Scanner lineScanner = new Scanner(line);, then use lineScanner.nextInt() to read the first number and lineScanner.hasNextInt() to check if there is a second one.

CodePudding user response:

Your input values look like command line arguments so you don't need to use Scanner. Try this:

public static void main(String[] args) {
    ValueM array_gen;
    if (args.length == 1) {
        array_gen=new ValueM(Integer.parseInt(args[0]));
    } else if (args.length == 2) {
        array_gen=new ValueM(Integer.parseInt(args[1]),Integer.parseInt(args[0]));
    } else {
        // message user about bad input
    }
}
  • Related