2017-07-14 41 views
-8

幫助球員選擇+, - ,/,*,我怎麼能使其工作使用switch語句運營商的Java 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; 


     } 

    } 
} 
+2

什麼問題?就像更多的案例一樣。 –

+0

看看switch語句是如何工作的,然後添加額外的例子。簡單!那麼如果你感覺冒險,那麼就用多態性來替換switch語句。 – byxor

+3

問題是這樣的:'char op ='+',' - ','/','*';'。這不是有效的語法。你打算在那條線上做什麼? –

回答

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); 
    } 

}