操作员的Java Switch语句

时间:2017-07-14 11:37:54

标签: java switch-statement

帮助我们我正在尝试创建一个程序,让您选择+, - ,/,*以及如何使用switch语句使其工作

import java.util.Scanner;

public class practice1{
    public static void main (String[]Args){
        Scanner input = new Scanner(System.in);
        Integer num1, num2;
        char op = '+', '-', '/', '*';

        System.out.println("Select an operator +,-,*,/");
        switch(op){
            case "+":
            System.out.println("Enter two numbers to add");
            System.out.print("Enter first number: "); num1 = input.nextInt();
            System.out.print("Enter second number: "); num2 = input.nextInt();
            System.out.println(num1 + num2);
            break;


        }

    }
}

1 个答案:

答案 0 :(得分:0)

试试这个:

package com.sujit;

import java.util.Scanner;

public class UserInput {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        boolean flag = true;

        do {
        System.out.println("Enter 1st number");
        int num1 = input.nextInt();
        System.out.println("Enter 2nd number");
        int num2 = input.nextInt();

        System.out.println("select one operator :\n 1)+\n2)-\n3)*\n4)/\n5)Exit(Enter E)\n");
        System.out.println("Enter your choice :");

        char choice = input.next().charAt(0);
        String ch = String.valueOf(choice);
        switch (ch) {
        case "+":   
            System.out.println("Addition = "+(num1+num2));
            break;
        case "-":   
            System.out.println("Subtraction = "+(num1-num2));
            break;
        case "*":   
            System.out.println("Multiplication = "+(num1*num2));
            break;
        case "/":   
            if(num2==0){
                System.out.println("Cant devide by 0");
                flag=false;
            }
            else {
                System.out.println("Division = "+(num1/num2));
            }

        break;
        case "E":   
            input.close();
            flag=false;
            break;
        default:
            System.out.println("Wrong choice");
            break;
        }

        }       
        while(flag);
    }

}