스캐너를 통해 정수 입력을 더 쉽게 보장하는 방법?
-
19-08-2019 - |
문제
내가 쓰고있는 프로그램의 경우, 1과 8 사이의 정수를 사용자에게 요청해야합니다. 나는이 작업을 수행하는 여러 가지 (청정) 방법을 시도했지만 그 중 어느 것도 작동하지 않았으므로 다음과 같습니다.
int x = 0;
while (x < 1 || x > 8)
{
System.out.print("Please enter integer (1-8): ");
try
{
x = Integer.parseInt(inputScanner.next());
}
catch(NumberFormatException e)
{
x = 0;
}
}
어디에 inputScanner
스캐너입니다. 더 나은 방법이 있습니까?
해결책
스캐너는 정규 표현이 맞습니까? "^[1-8] $"먼저 일치하는지 확인하십시오.
다른 팁
NextInt ()를 사용하는 것은 이미 다음 () 메소드를 사용하는 것과 비교하는 것입니다. 그 전에는 hasnextint ()를 사용 하여이 모든 쓸모없는 예외를 방지하지 않아도됩니다.
다음과 같은 결과 :
int x = 0;
do {
System.out.print("Please...");
if(scanner.hasNextInt()) x = scanner.nextInt();
else scanner.next();
} while (x < 1 || x > 8);
그래픽 인터페이스 계산기 (정수와 만 작동)를 수행해야했는데, 문제는 입력이 정수가 아닌 경우 테스트가 예외를 던지지 않았다는 것입니다. 그래서 나는 사용할 수 없었습니다
try { int x = Integer.parseInt(input)} catch (Exception e) {dosomethingelse}
Java 프로그램은 일반적으로 jtextfield에 대한 입력을 문자열로 취급하기 때문에 다음을 사용했습니다.
if (input.matches("[1-9][0-9]*"){ // String.matches() returns boolean
goodforyou
} else {
dosomethingelse
}
// this checks if the input's (type String) character sequence matches
// the given parameter. The [1-9] means that the first char is a Digit
// between 1 and 9 (because the input should be an Integer can't be 0)
// the * after [0-9] means that after the first char there can be 0 - infinity
// characters between digits 0-9
도움이 되었기를 바랍니다 :)
아파치 커먼즈는 당신의 친구입니다. 보다 숫자 우틸 (numberutils.toints.toint) (문자열, int)
String input;
int number;
while (inputScanner.hasNextLine())
{
input = inputScanner.nextLine();
if (input.equals("quit")) { System.exit(0); }
else
{
//If you don't want to put your code in here, make an event handler
//that gets called from this spot with the input passed in
try
{
number = Integer.parseInt(input);
if ((number < 1) || (number > 8))
{ System.out.print("Please choose 1-8: "); }
else { /* Do stuff */ }
}
catch (NumberFormatException e) { number = 0; }
}
}
나는 항상 전체 문자열을 끌어 당기므로 사용자가 Enter 버튼을 누르도록 확인할 수 있습니다. 만 사용하는 경우 inputScanner.nextInt()
당신은 두 개를 넣을 수 있습니다 int
S는 라인에 있고 하나는 하나를 잡아 당기고 다른 하나를 당길 것입니다.
예제 코드 :
int x;
Scanner in = new Scanner(System.in);
System.out.println("Enter integer value: ");
x = in.nextInt();
정수를 저장하는 데 배열을 사용할 수도 있습니다.
당신은 다음과 같은 것을 시도 할 수 있습니다 :
Scanner cin = new Scanner(System.in);
int s = 0;
boolean v = false;
while(!v){
System.out.print("Input an integer >= 1: ");
try {
s = cin.nextInt();
if(s >= 1) v = true;
else System.out.println("Please input an integer value >= 1.");
}
catch(InputMismatchException e) {
System.out.println("Caught: InputMismatchException -- Please input an integer value >= 1. ");
cin.next();
}
}