정수, 복식 또는 문자열을 Comparable ArrayList에 저장하라는 입력을 사용자에게 요청하려고합니다. 문제는 프로그램에 어떤 것인지 알리라고 요청하지 않는다는 것입니다. 내 솔루션은 정수 또는 복식에 대한 입력을 구문 분석하는 것이 었습니다. 둘 다 false를 반환하면 문자열이라는 것을 압니다. 내 코드는 다음과 같습니다.수동 입력을 사용하여 Comparable ArrayList의 정수, 복식 또는 문자열을 저장합니다.
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]
내 오류가 여기에 무엇입니까?
왜 단순히'hasNextInt()'를 검사하는 대신'nextLine'을 사용하고 예외를 잡을까요? –
두 번째로 확인중인 'haveInt'는 무엇입니까? 어디에도 정의되어 있지 않습니다. –
헤이, 오타. 그것을 고정했지만 여전히 동일한 결과를 얻었습니다. ( – nicholas