2017-10-05 2 views
-1

누군가 왜 while 루프가 whatNight를 두 번 묻는 지 설명 할 수 있습니까? 어떻게 유효하지 않은 사용자 입력을 다시 메시지 표시하는 경우 'R'또는 'C'어떻게 잘못된 사용자 입력을 reprompt하고 값을 복원합니까?

for(int x = 1; x <= inputInt; x++) { 
    char whatNight = JOptionPane.showInputDialog("Enter c or r for what type of night").charAt(0); 
    boolean pleasework = whatNight == 'c' || whatNight == 'C'; 
    boolean imbeggingu = whatNight == 'r' || whatNight == 'R'; 
    boolean doesNotWork = whatNight != 'c' && whatNight != 'C' && whatNight != 'r' && whatNight != 'R'; 

    //why does the while loop ask twice even if u enter c or r? 
    while(pleasework || imbeggingu || doesNotWork) { 

     if(doesNotWork) 
      JOptionPane.showMessageDialog(null, "INvalid letter"); 
      whatNight = JOptionPane.showInputDialog("Enter c or r for what type of night").charAt(0); 
     //reprompt not storing in whatNight variable :/ 

      if(pleasework) 
      JOptionPane.showMessageDialog(null, "You entered c for carnight"); 

      else if(imbeggingu) 
      JOptionPane.showMessageDialog(null, "You entered r for regular night"); 
      break; 
    } 

답변

0

귀하의 질문에 대답하기 위해 나는 첫 번째 단계의 예

System.out.println(pleasework); 
로 값을 디버깅을 추천 할 것 이외의 사용자 입력 뭔가

당신의 개념 논리가 꽤 떨어져서 문제를 어떻게 처리 할 것인지 다시 생각해야합니다. 예를 들어 입력이 C 또는 R이 아닌 경우 새 입력을 요청하지만 이에 따라 부울을 설정하지 마십시오.

이렇게하면됩니다.

for(int x = 1; x <= inputInt; x++) { 
    char whatNight = JOptionPane.showInputDialog("Enter c or r for what type of night").charAt(0); 
    whatNight = checkInput(whatNight); 
    boolean nightC = whatNight == 'c' || whatNight == 'C'; 
    boolean nightR = whatNight == 'r' || whatNight == 'R'; 

    if(nightC) { 
     JOptionPane.showMessageDialog(null, "You entered c for carnight"); 
    } else if(nightR) { 
     JOptionPane.showMessageDialog(null, "You entered r for regular night"); 
    } 
} 

--------------------------------------------------------------------- 

private char checkInput(char input) { 
    if(input == 'c' || input == 'C' || input == 'r' || input == 'R') { 
     return input; 
    } 
    char whatNight = JOptionPane.showInputDialog("You entered a wrong letter, enter either c or r for what type of night it was").charAt(0); 
    return checkInput(whatNight); 
} 

내가 알고있는 것을 알지 못하면 설명하겠습니다.

관련 문제