2013-12-12 3 views
1

글쎄요,이 작은 일로 저를 죽이고 있습니다. 나는 자바에서 꽤 신참이며 가능한 모든 가능성을 시도해 왔으며 아무 것도 효과가없는 것으로 보인다.아니요 숫자가 아닌 문자를 거부하십시오.

그냥 숫자가 아닌 문자열을 거부하거나 키보드에서 누를 때 문자를 무시하기를 원합니다. '

Please Enter your Student ID: ee 

Exception in thread "main" java.util.InputMismatchException 
    at java.util.Scanner.throwFor(Scanner.java:909) 
    at java.util.Scanner.next(Scanner.java:1530) 
    at java.util.Scanner.nextInt(Scanner.java:2160) 
    at java.util.Scanner.nextInt(Scanner.java:2119) 
    at practice7.main(practice7.java:11) 
Java Result: 1 
BUILD SUCCESSFUL (total time: 4 seconds)*** 
+1

그냥 http://stackoverflow.com/questions/2912817/how-to-use-scanner-to에 대해 살펴 할 수 -accept-only-valid-int-as-input question – birdy

답변

1

사용하여 예외 :

int input = 0; 
Boolean ready = false; 
while(!ready){ 
    try{ 
     System.out.print("Please Enter your Student ID (Numbers Only): "); 
     Scanner in = new Scanner(System.in); 
     input = in.nextInt(); 
     ready=true; 
    }catch(IOException e){ 
     System.out.err("that was not a number"); 
    } 
} 

// now we have input of integer numbers 
doRestOfProgram(); 

당신도

String input = "nothing"; 

while(!input.matches("[0-9]+")) 
{ 
    System.out.print("Please Enter your Student ID (Numbers Only): "); 
    Scanner in = new Scanner(System.in); 
    input = in.nextLine(); 
} 

// now we have input of string numbers 
doRestOfProgram(); 
+0

죄송합니다. 거기서 편집하지 않으 셨습니다. @ryanCarlson – wrossmck

+0

F *** ng H * ll !! 이것은 나를 영원히 바랄 수 있었다! IT가 작동하고, 그것은 너무 죄가 있습니다. 사랑해, 고마워. – eneko

0
// Will throw an exception if String id cannot be parsed into an integer. 
int idNum = Integer.valueOf(id); 
+0

이제 예외를 throw하지만 어떻게 처리해야합니까? ...? – eneko

+0

try {} catch (IOException e) {} 블록 – wrossmck

2

당신은 String를 사용

while (!input.matches("[0-9]+")) 
{ System.out.print("Error, invalid input. Try Again: "); input = sc.nextInt(); } 

사용할 수 있습니다

import java.util.Scanner; 

public class practice7 { 


    public static void main(String[] args) { 


     System.out.println(" Wlecome to the Magellan School student assistant \n\n"); 
     System.out.print("Please Enter your Student ID: "); 
     Scanner sc = new Scanner(System.in); 
     Scanner NS = new Scanner(System.in); 
     int ID = sc.nextInt(); 

//PRETTY SURE IT GOES HERE... 

//rest of program 

나는 여기에 주어진 모든 해답을 시도했다, 그러나 나는 편지를 쓸 때마다 나는이 얻을 s .matches(String regex) 방법. [0-9]+regex이며 here에 대한 설명과 데모를 찾을 수 있습니다.

+0

에서 처리합니다. 그래도 작동했습니다. 많은 감사 친구! – eneko

관련 문제