2017-09-26 4 views
0

Java에서 간단한 콘솔 앱을 만들고 있는데 문제가 있습니다. 내 코드 :while 루프 및 switch 문을 사용하는 스캐너

boolean isActive = true; 
Scanner scanner = new Scanner(System.in); 

do { 
try { 
    int option = scanner.nextInt(); 

    switch (option) { 

     case 1: 
      System.out.println("Search By Registration number: " + 
        "\n------------------------------"); 
      System.out.println("Enter registration number!"); 
      String regNumber = scanner.nextLine(); 
      if (regNumber == incorrect) { 
       continue; // return to case 1 and ask enter regnumber one more time 
      } else { 
       // do stuff 
      } 

      break; 

     case 2: 
      System.out.println("Exit the search option: "); 
      isActive = false; 
      break; 

     default: 
      System.out.println("Your selection was wrong. Try one more time!"); 
      break; 

    } 
} catch (InputMismatchException ex) { 
    System.out.println("Your selection was wrong. Try one more time!"); 
} 
scanner.nextLine(); 
} while (isActive); 

오류가 발생한 경우 사례 1로 돌아갈 수 없습니다. 따라서 오류가 발생하면 사용자는 한번 더 등록 번호 입력에 관한 메시지를 받아야합니다.

답변

0

올바른 것이 아닌 동안 입력을 수신하기 위해 regNumber에 대한 입력을 반복 할 수 있습니다.

String regNumber = incorrect; 
// String is a reference type, therefore equality with another String's value 
// must be checked with the equals() method 

while(regNumber.equals(incorrect)){ 

    if (regNumber.equals(correct)) { 
     // Do something if input is correct 
    } 

} 

이것은 정확히 원하는 해결책은 아니지만 동일한 개념을 생각해보고 프로그램에 적용 할 수 있습니다. 문자열 비교에 대한 자세한 내용은 this을 참조하십시오. 희망이 도움이! 당신이 regNumber이에

if (regNumber.equals(incorrect)) { 
     System.out.println("Incorrect!"); 
     continue; 
} else { 
     System.out.println("Correct!"); 
} 

그러나 그렇다하더라도, 제대로 작동하지 않는 프로그램이 문자열 regNumber = scanner.nextLine을 변경()를 확인할 때

1

당신은 등호()를 사용해야합니다 :

String regNumber = scanner.next();