1

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吗?

4

2 回答 2

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);
于 2011-08-07T10:03:42.440 回答
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"));
于 2011-08-07T10:08:47.870 回答