2011-08-07 13 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

相關問題