如何阅读和获取Scaner的Enter键

时间:2016-09-27 16:05:12

标签: java

我正在学习Java,此时我尝试使用简单的任务来熟悉Java synthax。

今天我写了一个简单的计算器,其中一个任务目标是当用户按下回车键时完成程序。所以这是我的问题,我的代码解决方案与其他键一起工作,例如'y'

带有'y'键的

代码(正常工作):

import java.util.Scanner;

public class SimpleCalculator {

public static void main(String[] args) {

    System.out.println("Program 'Simple Calculator'");
    boolean log = true; 
    Scanner in = new Scanner(System.in);

    while (log == true) {

        double result = 0;
        double a, b = 0;
        System.out.println("Enter the first number");
        a = in.nextDouble();
        char sign;
        String temp;
        boolean log2 = true;

        while (log2 == true) {
            System.out.println("Enter the algebraic operation sign ('+' ,'-' ,'*' or '/' )");
            temp = in.next();
            sign = temp.charAt(0);

            if (sign == '+' || sign == '-' || sign == '*' || sign == '/') {
                log2 = false;
                switch (sign) {
                case '+':
                    System.out.println("Enter the 2nd number ");
                    b = in.nextDouble();
                    result = a + b;
                    break;
                case '-':
                    System.out.println("Enter the 2nd number ");
                    b = in.nextDouble();
                    result = a - b;
                    break;
                case '*':
                    System.out.println("Enter the 2nd number ");
                    b = in.nextDouble();
                    result = a * b;
                    break;
                case '/':
                    while (b == 0) {
                        System.out.println("Enter the 2nd number ");
                        b = in.nextDouble();
                        if (b != 0)
                            result = a / b;
                        else
                            System.out.println("Division by 0 is undefined for real nubers, enter 2nd number again");
                    }
                    break;

                }

            } else {
                System.out.println("wrong operation sign, enter it once again");
            }
            if (log2 == false)
                System.out.println("Result: " + result);

        }
        System.out.println("Press y for exit the program(or any other to use it once again)"); 

        temp = in.next();
        if (temp.equals("y")) {
            System.out.println("y Key pressed.");
            log = false;
        }

    }
    in.close();
    System.out.println("End of work");

}

}

当按下Enter键时,我尝试了最后一个if的两个变体来结束工作

temp = in.next();
if (temp.equals("")) {
System.out.println("Enter Key pressed.");
log = false;}

和第二个

temp =in.next();
        sign = temp.charAt(0);
        if (sign == 13 )    //carriage return character code
            log = false; 

但是在输入密钥的情况下两者都不好。如果有人告诉我为什么这两个变量如果与输入键无法正常工作以及使用结束键结束程序的最佳方式,那将是很好的。

谢谢你:)

0 个答案:

没有答案