정수 필드에 정수가 아닌 항목을 입력하는 데 문제가 있습니다. 나는 다른 사람이 내 프로그램을 사용 / 작업하는 경우에만 예방 조치를 취하고 InputMismatchException
있습니다.
숫자가 아닌 문자를 input
변수에 입력 하면 위의 오류가 발생합니다. NullPointerException
문자열 과 관련하여이를 보완 할 수있는 방법이 있습니까?
이 코드는 문제를 일으키는 관련 부분을 포함하기 위해 수정됩니다.
import java.util.Scanner;
class MyWorld {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int input = 0;
System.out.println("What is your age? : ");
input = user_input.nextInt();
System.out.println("You are: " +input+ " years old");
}
}
if 문을 사용하여 user_input인지 확인할 수 있습니다 hasNextInt()
. 입력이 정수이면 설정 input
같다 user_input.nextInt()
. 그렇지 않으면 입력이 유효하지 않다는 메시지를 표시합니다. 이것은 예외를 방지해야합니다.
System.out.println("What is your age? : ");
if(user_input.hasNextInt()) {
input = user_input.nextInt();
}
else {
System.out.println("That is not an integer.");
}
여기에 대한 몇 가지 자세한 정보입니다 hasNextInt()
에서 Javadoc과는 .
참고로 Java의 변수 이름은 lowerMixedCase
규칙을 따라야합니다 . 예를 들어 user_input
는로 변경해야합니다 userInput
.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다