2011-08-07 3 views
1

사용자가 Y/N을 대답으로 입력하지 않은 경우 오류를 반환하고 Do you want to try again (Y/N)? 질문을 다시 어떻게 제기합니까?Y/N을 입력 할 때 오류를 반환하십시오.

import java.io.*; 

public class Num10 { 
    public static void main(String[] args){ 
     String in=""; 
     int start=0, end=0, step=0; 

     BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); 

     do{ 
      try{ 
       System.out.print("Input START value = "); 
       in=input.readLine(); 
       start=Integer.parseInt(in); 
       System.out.print("Input END value = "); 
       in=input.readLine(); 
       end=Integer.parseInt(in); 
       System.out.print("Input STEP value = "); 
       in=input.readLine(); 
       step=Integer.parseInt(in); 
      }catch(IOException e){ 
       System.out.println("Error!"); 
      } 

      if(start>=end){ 
       System.out.println("The starting number should be lesser than the ending number"); 
       System.exit(0); 
      }else 
      if(step<=0){ 
       System.out.println("The step number should always be greater than zero."); 
       System.exit(0); 
      } 

      for(start=start;start<=end;start=start+step){ 
       System.out.println(start); 
      } 

      try{ 
       System.out.print("\nDo you want to try again (Y/N)?"); 
       in=input.readLine(); 
      }catch(IOException e){ 
       System.out.println("Error!"); 
      } 
     }while(in.equalsIgnoreCase("Y")); 

    } 
} 

if-else을 사용해야합니까? 이 같은

+0

은 무엇 정확하게 예상대로 작동하지 않습니다 같은 입력했는지 확인? 코드를보고 이미 함수를 구현 했습니까? – home

+0

@home 예 코드가 작동하지만 'y/n'질문에 대해 y/n을 입력하지 않았을 때 오류를 표시하고 종료하는 방법은 무엇입니까? 그냥 프로그램을 종료합니다. – Zhianc

답변

1

먼저 +1. 그건 묻는 질문자의 90 % 이상입니다. 최종 try/catch 블록에서, 사용자가 'Y'또는 'N'

 try{ 
      while (!in.equalsIgnoreCase("y") && !in.equalsIgnoreCase("n")) { 
        System.out.print("\nDo you want to try again (Y/N)?"); 
        in=input.readLine(); 
      } 
     }catch(IOException e){ 
      System.out.println("Error!"); 
     } 
    }while(in.equalsIgnoreCase("Y")); 
+0

잘 작동합니다. 감사합니다! – Zhianc

1

어떻게 좀 : 완전히 컴파일 가능한 프로그램을 공급하기위한

BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); 
boolean w4f = true; 

do { 
    String in = input.readLine(); 

    if ("Y".equalsIgnoreCase(in)) { 
     w4f = false; 

     // do something 

    } else if ("N".equalsIgnoreCase(in)) { 
     w4f = false; 

     // do something 

    } else { 

     // Your error message here 
     System.out.println("blahblah"); 
    } 

} while(w4f); 
+0

은 ""Y ". equalsIgnoreCase (in)'에 대해 'w4f = true'가되어서는 안됩니까? – Zhianc

+0

@jc david : 네. 나는 단지 그것이 일반적으로 어떻게 작동 할 수 있는지를 설명하기를 원했다. 당신이 대답을 받아 들였을 때, 요점을 얻은 것 같아요, 그렇죠? – home

+0

여기서 break/continue를 사용할 수 있습니다. – atamanroman

관련 문제