如何从Java中声明的类中获取基元的类型?
我不确定我的标题是否准确地描述了我想说的话——但以下是我想做的: 我有这个班级号码:如何从Java中声明的类中获取基元的类型?,java,Java,我不确定我的标题是否准确地描述了我想说的话——但以下是我想做的: 我有这个班级号码: public class Numbers{ private int Integers; private float Floaters; public Numbers(String xUserInput){ if (xUserInput.matches("[0-9]+")) { System.out.println("Integer");
public class Numbers{
private int Integers;
private float Floaters;
public Numbers(String xUserInput){
if (xUserInput.matches("[0-9]+")) {
System.out.println("Integer");
try{
this.setIntegers(Integer.parseInt(xUserInput));
} catch (NumberFormatException e) {
System.out.println(xUserInput + " is not of Integer type!");
}
} else if (xUserInput.matches("[0-9]*[.]{1}[0-9]+")) {
System.out.println("Float");
try{
this.setFloaters(Float.parseFloat(xUserInput));
} catch (NumberFormatException e) {
System.out.println(xUserInput + " is not of Float type!");
}
} else {
System.out.println("Invalid Input!");
}
}
public int getIntegers() {
return this.Integers;
}
public void setIntegers(int integers) {
this.Integers = integers;
}
public float getFloaters() {
return this.Floaters;
}
public void setFloaters(float floaters) {
this.Floaters = floaters;
}
现在,在main中,我将所有用户输入添加到ArrayList中,但是我想打印数组两次,一次打印所有整数,然后打印所有浮点数
如何获得基元类型?请告诉我哪里出了问题
PS:我试过了
for(Numbers n : numberList) {
System.out.println(n.getClass().getSimpleName());
}
。。。但我得到的只是“数字”。您总是在循环中显示类名。我想你想要的是:
// first loop
for(Numbers n : numberList) {
System.out.println(n.getIntegers());
}
// second loop
for(Numbers n : numberList) {
System.out.println(n.getFloaters());
}
“原始类型”是什么意思?您希望返回的确切字符串是什么而不是“数字”?@Jj感谢您的回复。我想得到“int”或“float”,这取决于该条目保存的内容。如果您否决了投票,请-花时间写一条简短的评论,这样我可以从中学习一些东西。这将打印值,但不会键入。其他类型将显示为0。这并不是我想要的。因此,如果我理解正确,数字可以是int或float,而您只想显示该值?类型不是值本身,即int或float。因此,添加一个新字段,作为String Type=“not set”;设置整数时将其设置为type=“int”,或设置浮点并使用getter(如getType())将该字段初始化时将其设置为type=“float”。我理解解决方法,但它没有回答我的问题。