繁体   English   中英

如何在 java 上单行获取多种数据类型?

[英]How to take multiple data types in single line on java?

我是编码新手,现在我正在学习 Java。 我试着写一些类似计算器的东西。 我用 switch case 编写了它,但后来我意识到我必须将所有输入都放在一行中。 例如,在这段代码中,我采用了 3 个输入,但在 3 个不同的行中。 但我必须在单行中输入 2 个输入和 1 个字符。 第一个数字第二个字符,然后是第三个数字。 你能帮助我吗?

 Public static void main(String[] args) {
    int opr1,opr2,answer;
    char opr;
    Scanner sc =new Scanner(System.in);
    System.out.println("Enter first number");
    opr1=sc.nextInt();
    System.out.println("Enter operation for");
    opr=sc.next().charAt(0);
    System.out.println("Enter second number");
    opr2=sc.nextInt();

    switch (opr){
        case '+':
            answer=opr1+opr2;
            System.out.println("The answer is: " +answer);
        break;
        case '-':
            answer=opr1-opr2;
            System.out.println("The answer is: " +answer);
        break;
        case '*':
            answer=opr1*opr2;
            System.out.println("The answer is: " +answer);
        break;
        case '/':
            if(opr2>0) {
                answer = opr1 / opr2;
                System.out.println("The answer is: " + answer);
            }
            else {
                System.out.println("You can't divide to zero");
            }
        break;
        default:
            System.out.println("Unknown command");
        break;
    }

你可以尝试这样的事情:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Please enter number, operation and number. For example: 2+2");
    String value = scanner.next();

    Character operation = null;
    StringBuilder a = new StringBuilder();
    StringBuilder b = new StringBuilder();

    for (int i = 0; i < value.length(); i++) {
        Character c = value.charAt(i);
        // If operation is null, the digits belongs to the first number.
        if (operation == null && Character.isDigit(c)) {
            a.append(c);
        }
        // If operation is not null, the digits belongs to the second number.
        else if (operation != null && Character.isDigit(c)) {
            b.append(c);
        }
        // It's not a digit, therefore it's the operation itself.
        else {
            operation = c;
        }
    }

    Integer aNumber = Integer.valueOf(a.toString());
    Integer bNumber = Integer.valueOf(b.toString());

    // Switch goes here...
}

注意:这里没有验证输入。

尝试以下方式

System.out.print("Enter a number then operator then another number : ");
String input = scanner.nextLine();    // get the entire line after the prompt 
String[] sum = input.split(" ");

这里numbersoperator"space"分隔。 现在,您可以通过sum array调用它们。

int num1 = Integer.parseInt(sum[0]);
String operator = sum[1];   //They are already string value
int num2 = Integer.parseInt(sum[2]);

然后,您可以像以前那样做。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM