Jordan C Jordan C -4 years ago 101
Java Question

User input for creating objects

I'm trying to code something to create a specific object if it matches the values that the user Inputs.

For example:

suppose I have Person class and Car class

public class Person
private int x, y ,z;
private String str;

//Constructors etc
public class Car
private int x,y,z;
private double doub;

//Constructors etc

The user is asked to input 4 different values. The first three fields of Person and Car are the same but if the 4th value is a String or double, the program should create the matching object.

public class Input
public static void main (String args[])
int x,y,z;
?? other; //how do i declare if its either a double or string

Scanner input = new SCanner(;
x = input.nextInt();
// y, z input
other = input.??? //String or double

//Create matching object

How do i go about this?

Answer Source

You can use matches to check if your input is double or a String for example :

Scanner input = new Scanner(;
String other = input.nextLine();
if (other.matches("\\d+\\.\\d+")) {
    //your input is double
    Double d = Double.parseDouble(other);
    System.out.println("double = " + d);

} else {
    //your intput is a Strings
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download