有两种方式可以实现,一种是利用Scanner,另一种是利用BufferedReader

  1. package first; 
  2.  
  3. //import java.util.Scanner; 
  4. import java.io.BufferedReader; 
  5. import java.io.IOException; 
  6. import java.io.InputStreamReader; 
  7.  
  8. public class Operation { 
  9.  
  10.     /** 
  11.      * @param args 
  12.      */ 
  13.     public static Double Operate(double numberA,double numberB,char opera){ 
  14.         double result=0
  15.         switch(opera){ 
  16.             case '+'
  17.                 result=numberA+numberB; 
  18.                 break
  19.             case '-'
  20.                 result=numberA-numberB; 
  21.                 break
  22.             case '*'
  23.                 result=numberA*numberB; 
  24.                 break
  25.             case '/'
  26.                 if(numberB==0){ 
  27.                     System.out.println("除数不能为零"); 
  28.                     System.exit(0); 
  29.                 } 
  30.                 else
  31.                     result=numberA/numberB; 
  32.                     break
  33.                 } 
  34.         } 
  35.         return result; 
  36.     } 
  37.      
  38.      
  39.     public static void main(String[] args) throws IOException { 
  40.         // TODO Auto-generated method stub 
  41.         double numberA = 0d; 
  42.         double numberB = 0d; 
  43.         char[] ch = new char[3]; 
  44.         char opre='0'
  45.         System.out.println("输入参数及运算符:"); 
  46.          
  47. //      Scanner sc = new Scanner(System.in); 
  48. //      sc.useDelimiter("\n"); 
  49. //      if (sc.hasNext()) { 
  50. //          numberA = Double.parseDouble(sc.next()); 
  51. //          numberB = Double.parseDouble(sc.next()); 
  52. //          ch = sc.next().toCharArray(); 
  53. //      } 
  54. //      char opre = ch[0]; 
  55.         BufferedReader bf=new BufferedReader(new InputStreamReader(System.in)); 
  56.         try { 
  57.             System.out.println("输入第一个数"); 
  58.             numberA=Double.parseDouble(bf.readLine()); 
  59.             System.out.println("输入第二个数"); 
  60.             numberB=Double.parseDouble(bf.readLine()); 
  61.             System.out.println("输入运算符"); 
  62.             bf.read(ch); 
  63.             opre=ch[0]; 
  64.         } catch (NumberFormatException e) { 
  65.             // TODO Auto-generated catch block 
  66.             e.printStackTrace(); 
  67.         } catch (IOException e) { 
  68.             // TODO Auto-generated catch block 
  69.             e.printStackTrace(); 
  70.         }finally
  71.             if(bf!=null){ 
  72.                 bf.close(); 
  73.             } 
  74.         } 
  75.                  
  76.          
  77.         double result = Operate(numberA, numberB, opre); 
  78.         System.out.println("输出结果为:" + result); 
  79.     } 
  80.