gpt4 book ai didi

java - 用于创建对象的用户输入

转载 作者:搜寻专家 更新时间:2023-11-01 02:37:32 25 4
gpt4 key购买 nike

如果它与用户输入的值匹配,我正在尝试编写一些代码来创建特定对象。

例如:

假设我有 Person 类和 Car 类

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
}

要求用户输入 4 个不同的值。 Person 和 Car 的前三个字段相同,但如果第 4 个值是 String 或 double,程序应创建匹配对象。

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(System.in);
x = input.nextInt();
// y, z input
other = input.??? //String or double

//Create matching object
}
}

我该怎么做?

最佳答案

您可以使用 matches 来检查您的输入是 double 还是字符串,例如:

Scanner input = new Scanner(System.in);
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
System.out.println(other);
}

关于java - 用于创建对象的用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44094675/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com