带循环的Java字符输入?

时间:2015-05-25 08:29:25

标签: java loops exception-handling

伙计们我想写一个程序,找到具有异常处理的Nominator和Denominator并计算他们的结果。我还添加了一个简单界面,您是否要继续按'y'。或'n'。字符属于小写字母。

我希望该接口仅发生在两件事上。当程序捕获错误的输入时。并且在计算结果时。

问题是,当用户按下'n'时,它不会退出。或者当用户输入任何字符时,例如'aadswe'接口不再出现。我陷入了这个问题。

public class Main {
        public static void main(String[] args) {
            int numeator;
            int denominator;
            double result;
            Scanner s = new Scanner(System.in);
            char m = 'y';
            do {
                try {
                System.out.print("Enter Numenator:");
                numeator = s.nextInt();

                System.out.print("Enter Denominator:");
                denominator = s.nextInt();

                result = numeator / denominator;

                System.out.println("Answer: " + result);
            } catch (InputMismatchException e) {
                System.out.println("error=> must enter integer values");
            } catch (ArithmeticException e) {
                System.out.println("error=> falseairthmtic");
            }
            System.out.println("Would you continue prees 'y' or quit press 'n'");
            m = s.next().charAt(0);
        }
        while (m == 'y');
    }
}

1 个答案:

答案 0 :(得分:2)

使用以下代码 -

public static void main(String[] args) {
            int numeator;
            int denominator;
            double result;
            Scanner s = new Scanner(System.in);
            char m = 'y';
            do {
                try {
                System.out.print("Enter Numenator:");
                numeator = s.nextInt();

                System.out.print("Enter Denominator:");
                denominator = s.nextInt();

                result = numeator / denominator;

                System.out.println("Answer: " + result);
            } catch (InputMismatchException e) {
                System.out.println("error=> must enter integer values");
            } catch (ArithmeticException e) {
                System.out.println("error=> falseairthmtic");
            }
            System.out.println("Would you continue prees 'y' or quit press 'n'");
            m = s.next().charAt(0);
            while(m!='y'&& m!='n'){
                System.out.println("you can press only 'y'or'n' "+ m+ " is not allowed!!") ;
                m = s.next().charAt(0);
            }
        }
        while (m == 'y');
            System.out.println("Has been quit");
    }