나는 합계하고자하는 숫자의 수를 얻기 위해 메소드를 만들고 있습니다. 일명 2와 3의 숫자를 합치려면 3 개의 숫자를 합치고 싶을 것입니다. 그래서 내가 얼마나 많은 사람들이 함께 모으고 싶은지 물어볼 때, 나는 그들이 소수 자리를 입력했는지 파악하기 위해 try-catch를 사용합니다. 3.5 숫자를 함께 더할 수 없으므로 3 개의 숫자 또는 4를 더할 수 있습니다. 사용자가 십진수를 입력하면 프로그램은 무한 루프를 실행하지만 try 문에있는 내용은 모두 실행합니다. 이 문제를 어떻게 해결할 수 있습니까?루프의 두 번째 illiteration에 try 문을 사용하지 않습니다.
private static int requestMaxInputForFloat(Scanner scanner){
boolean appropriateAnswer = true; // assume appropriate catch not appropriate to loop again
int howManyInputs = 1000000; // hold value to return how many inputs. if this value we will not run.
//request an appropriate number of inputs until appropriate answer = true;
do
{
appropriateAnswer = true; //if looped again reset value to true
try{
System.out.print("How many decimal place numbers would you like to sum? ");
howManyInputs = scanner.nextInt();
}catch(Exception e){
System.out.println("Sorry but you can only request to average a whole number set of data.\nTry Again.");
appropriateAnswer = false;
}//end of try-catch
if (howManyInputs <= 0) //invalid answer
{
System.out.println("Sorry but " + howManyInputs + " is equal to or below 0. Please try again.");
}else{
appropriateAnswer = false;
}
}while(!appropriateAnswer);//end of while loop
return howManyInputs; //return the value
}// end of getMaxInput
'scanner.nextInt()'를 실행 한 후 새 행을 추가하고 다시 실행하십시오. –
Im 여전히 무한 루프가 발생합니다. nextInt() 뒤에 새로운 줄이 있더라도; Try 루프를 실행하고 print()를 인쇄하고 있음을 알았습니다. 하지만 그 것처럼 .nextInt(); 부품. –
'catch' 블록에서'scanner.nextLine()'을 시도하십시오. 문제는'nextInt()'에 에러가 생기면 스캐너의 "포인터"가 여전히 나쁜 문자 (소수점과 같은)를 가리키고 있고 nextInt()를 다시 시도하면 문제가 해결됩니다. 똑같은 나쁜 성격을 다시 검사 해. 스캐너를 건너 뛰려면 무언가를해야합니다. – ajb