在java上如何在一行中获取多个数据类型?

csbfibhn  于 2021-06-26  发布在  Java
关注(0)|答案(2)|浏览(388)

我是新的编码,现在我在学习java。我试着写一些像计算器的东西。我写它与开关盒,但后来我意识到,我必须采取在一行所有的输入。例如,在这段代码中,我有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;
    }
qf9go6mv

qf9go6mv1#

您可以尝试以下方法:

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...
}

注意:此处未验证输入。

bvn4nwqk

bvn4nwqk2#

试试下面的方法

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(" ");

在这里 numbers 以及 operator 分隔符 "space" . 现在,你可以打电话给他们 sum array .

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

然后,你可以做你所做的比。

相关问题