2012-02-23 2 views
3

사용자가 옵션이 정의되지 않은 것을 입력하면 내 swtich 문을 반복하도록 코드를 업데이트하려고합니다. 나는 다양한 검색 용어에서 돌아 왔고 가까이 왔지만 여전히 운이 없다는 수많은 페이지를 샅샅이 뒤졌습니다. 여기 내 코드는 찌르기를 원하는 사람이 있어야합니다.Java "switching case statement on"invalid input "

java.util.Scanner; 
//import java.lang.Character.*; 
//Thought this was needed to grab single char but its not 
public class caseloop { 
//main Method 
public static void main(String[] args) 
{ 
    Scanner input=new Scanner(System.in); //make so you can give input 
    boolean go = true; // for starting main outer loop 
    boolean run=true; // start inner loop 
    while (go==true) 
    { 
    while (run==true) 
    { 
     //Output 
     System.out.println("Enter option \n 1-Do this \n 2-Do this thing \n 3-Do this other thing"); 
     int option= input.nextInt(); //grab option number 

     switch(option) 
     { 
     /* 
      * This needs to loop and prompt user again if anything other than 1,2, or 3 is entered. 
      */ 
     case 1: 
      System.out.println("Option1"); 
      break; 
     case 2: 
      System.out.println("Option2"); 
      break; 
     case 3: 
      System.out.println("Option3"); 
      break; 
     /*case 4: 
      System.out.println("Option1"); 
      System.out.println("Option2"); 
      System.out.println("Option3"); 

      break; 
     * 
     * 
     * Case 4 was for debug 
     * 
     */ 
     default: 
      System.err.println("Invalid option selected"); 
      /* 
      * On input that is not defined with in the switch-case it will revert to "default" 
      * this fault staement needs to tell ther usere their option is not vaild and then 
      * prompt them to try it again to enter an option. I can not get it to reprompt. 
      * I have tried a while and an if loop both sorta worked but did not actually loop 
      * back to display again. I have been instucted that I am to not use a try catch statment 
      * unless of course that is the only viable option in whichcase I will use it anyways. 
      */ 

      //stupid default statement and its redundent built in "break;" 

     } 
     run=false; 
     } 


    /* 
    * Outer Loop to prompt user if they want to run the entire program again with new entries. 
    */ 
    if (run == false) 
    { 
    System.out.println("Would you like to run again? Y/N"); 
    char again = input.next().charAt(0); 
    again = Character.toUpperCase(again); //force all leters inputed to upper case, lower would work too if i change if conditions 
    if (again == 'Y') 
    { 
     run = true; 
    } 
    else if (again == 'N') 
    { 
     System.out.println("Goodbye."); 
     go=false; 
    } 
    else 
    { 
     System.err.println("Invalid entry. Try again."); 
    } 
    } 
    } 
} 
    //System.err.println("An error occured please try again"); 

} 

위의 사항에 대한 도움을 주시면 감사하겠습니다.

+0

여기에 내가 최종 프로그램의 다른 while 루프 내부의 두 가지 방법을 사용하여 끝났다. 모두 도움을 주셔서 감사합니다. : D –

답변

1

아주 이상한 방법으로 실행 변수를 사용하고 있습니다. 루프가 끝날 때 실행을 false으로 설정 했으므로 루프가 반복되지 않습니다. 올바른 옵션 집합을 run=false으로 설정하기 위해 주위를 변경하는 경우 잘못된 옵션을 입력하면 루프가 한 번 더 실행됩니다.

에서, switch 문의 끝에 run=false 제거 "실행 = false"를 부분은 바로 이곳에없는 System.out.println("OptionX");

+0

빠른 응답에 대해 많은 감사드립니다. 온라인 커뮤니티는 큰 도움이됩니다. –

2

후 추가, 그것은 (유효 여부) 어떤 대답을 실행합니다.

"run = false;" 유효한 각 case 문 안쪽에, 같은 : 그런데

case 1: 
     System.out.println("Option1"); 
     run=false; 
     break; 

"동안 (실행 == true)가"

+0

원래 구현은 while (run) 투표를 할 수 있고 2 개의 답변을받을 수 있다면 가능합니다. –

1

문제는 그 실행 한 후입니다 "(실행) 동안"당신이 쓸 수, 중복 명령문은 기본적으로 부울 실행을 거짓으로 설정하므로 루프에서 빠져 나옵니다. 우리가 필요로하는 것은 이것을 건너 뛸 수있는 방법입니다 : -

run = false; 

대신 루프 상태로 바로 가십시오. 한 가지 해결책은 기본적으로 'continue'문을 추가하는 것입니다. -

switch(option) 
    { 
    /* 
     * This needs to loop and prompt user again if anything other than 1,2, or 3 is entered. 
     */ 
    case 1: 
     System.out.println("Option1"); 
     break; 
    case 2: 
     System.out.println("Option2"); 
     break; 
    case 3: 
     System.out.println("Option3"); 
     break; 
    /*case 4: 
     System.out.println("Option1"); 
     System.out.println("Option2"); 
     System.out.println("Option3"); 

     break; 
    * 
    * 
    * Case 4 was for debug 
    * 
    */ 
    default: 
     System.err.println("Invalid option selected"); 
     continue; //this causes control to go back to loop condition 

    } 
+0

최소한의 코드 변경이 있기 때문에 좋은 옵션이지만이 같은 소규모 구현에서는 계속 작업이 훌륭합니다. 그러나 2 개의 while 루프가있는 큰 환경에서 궁극적으로 else로 끝나는 else if로 끝나는 여러 개의 if 루프로 스위치로 연결됩니다. 내부 루프의 상단으로 돌아가는 동안 while 루프는 모든 입력을 다시 묻습니다. 스위치 케이스 –

1

루프에 레이블을 추가 할 수 있습니다. 이렇게하면 올바른 옵션을 얻었을 때 루프가 종료됩니다. 모든 제안을 사용하여 추가 시험시

loop: switch(option) 
    { 
/* 
    * This needs to loop and prompt user again if anything other than 1,2, or 3 is entered. 
    */ 
case 1: 
    System.out.println("Option1"); 
    break loop; 
case 2: 
    System.out.println("Option2"); 
    break loop; 
case 3: 
    System.out.println("Option3"); 
    break loop; 
/*case 4: 
    System.out.println("Option1"); 
    System.out.println("Option2"); 
    System.out.println("Option3"); 

    break; 
* 
* 
* Case 4 was for debug 
* 
*/ 
default: 
    System.err.println("Invalid option selected"); 
    continue; //this causes control to go back to loop condition 

}