我试图提示用户输入以将整数、 double 或字符串存储在 Comparable ArrayList 中。问题是,我不要求他们让程序知道它是什么。我的解决方案是解析整数或 double 输入。如果它们都返回 false,那么我就知道它是一个字符串。这是我的代码:
int choice2num = 0;
System.out.println("Please enter your values: (Press enter to stop) ");
int integer = 0;
double doubl = 0;
boolean hasInt = true;
boolean hasDouble = true;
do
{
try
{
tempChoice = userIn2.nextLine();
if (hasInt){
try{
integer = Integer.parseInt(tempChoice);
}catch (NumberFormatException e)
{
hasInt = false;
}
}
if (haveInt == false && hasDouble){
try {
doubl = Double.parseDouble(tempChoice);
}catch (NumberFormatException er)
{
hasDouble = false;
}
}
if (hasInt)
{
try{
integer = Integer.parseInt(tempChoice);
}catch (NumberFormatException e )
{
System.out.println("Wrong format, please try again.");
break;
}
list.add(integer);
}
if (hasDouble)
{
try {
doubl = Double.parseDouble(tempChoice);
}catch (NumberFormatException e)
{
System.out.println("Wrong format, please try again.");
break;
}
list.add(doubl);
}
if (!hasDouble && !hasInt)
{
list.add(tempChoice);
}
if (!tempChoice.equals(""))
{
choice2num = Integer.parseInt(tempChoice);
list.add(choice2num);
}
}
catch(NumberFormatException e)
{
System.out.println(e.getMessage());
}
} while (!tempChoice.equals(""));
System.out.println("List: " + list);
secondMenu();
}
这很乱,我知道。当我在程序中运行代码并输入整数 1、2、3、4 和 5 时,它返回:
Wrong format, please try again.
List: [1, 1.0, 1, 2, 2.0, 2, 3, 3.0, 3, 4, 4.0, 4, 5, 5.0, 5]
我这里的错误是什么?
最佳答案
你需要一个 if else
block 。
if (userIn2.hasNextInt()){
// process integer
obj = userIn2.nextInt();
} else if(userIn2.hasNextDouble()) {
// process double
obj = userIn2.nextDouble();
} else {
// process String
obj = userIn2.next();
}
使用此顺序首先获取整数,然后是 double ,最后是字符串。
关于java - 使用手动输入将整数、 double 或字符串存储在 Comparable ArrayList 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47910262/