码迷,mamicode.com
首页 > 其他好文 > 详细

switch case实现两个数的算术运算

时间:2016-07-24 12:04:21      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

方法一:

package com.liaojianya.chapter1;

import java.util.Scanner;

public class SwitchDemo1
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		System.out.println("Enter number a : ");
		double a = input.nextDouble();
		System.out.println("Enter number b : ");
		double b = input.nextDouble();
		Action ac = new Action(a, b);
		ac.command(Action.ADD);
		ac.command(Action.SUBTRACT);
		ac.command(Action.MULTIPLY);
		ac.command(Action.DIVIDE);
		ac.command(Action.MOD);
		input.close();
	}
}

class Action
{
	double a;
	double b;
	public Action(double a, double b)
	{
		this.a = a;
		this.b = b;
	}
	public static final int ADD = 1;
	public static final int SUBTRACT = 2;
	public static final int MULTIPLY = 3;
	public static final int DIVIDE = 4;
	public static final int MOD = 5;

	public void command(int c)
	{
		switch (c)
		{
		case 1:
			System.out.println(a + " + " + b + " = " + (a + b));
			break;

		case 2:
			System.out.println(a + " - " + b + " = " + (a - b));
			break;

		case 3:
			System.out.println(a + " * " + b + " = " + (a * b));
			break;

		case 4:
			System.out.println(a + " / " + b + " = " + (a / b));
			break;

		case 5:
			System.out.println(a + " % " + b + " = " + (a % b));
			break;

		default:
			System.out.println("unknown operation!");
			break;
		}
	}

}

  方法二:

package com.liaojianya.chapter1;

import java.util.Scanner;

/**
 * This program demonstrates the use of switch.
 * @author LIAO JIANYA
 *
 */
public class SwitchDemo
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		
		System.out.println("Enter number a : ");
		double a = input.nextDouble();
		System.out.println("Enter number b : ");
		double b = input.nextDouble();
		System.out.println("Enter  operater :1代表+,2代表-,3代表*,4代表/,5代表% ");
		int c = input.nextInt();
		switch(c)
		{
			case 1:
			System.out.println(a + " + " + b + " = " + (a + b));
			break;

			case 2:
			System.out.println(a + " - " + b + " = " + (a - b));
			break;

			case 3:
			System.out.println(a + " * " + b + " = " + (a * b));
			break;

			case 4:
			System.out.println(a + " / " + b + " = " + (a / b));
			break;

			case 5:
			System.out.println(a + " % " + b + " = " + (a % b));
			break;
			
			default:
				System.out.println("unknown operation!");
				break;
		}
	}

}

  运行结果:

Enter number a : 
12.3
Enter number b : 
32.1
12.3 + 32.1 = 44.400000000000006
12.3 - 32.1 = -19.8
12.3 * 32.1 = 394.83000000000004
12.3 / 32.1 = 0.38317757009345793
12.3 % 32.1 = 12.3

  

switch case实现两个数的算术运算

标签:

原文地址:http://www.cnblogs.com/Andya/p/5700350.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!