写一个简单的函数实现下面的功能:具有三个参数,完成对两个整型数据的加、减、乘、除四种操作,前两个为操作数,第三个参数为字符型的参数。
(1)定义变量; (2)接收用户输入; (3)函数计算; (4)输出结果;
import java.util.Scanner;
public class E20210814 {
public static void main(String[] args) {
int a1, b;
char c;
Scanner input = new Scanner(System.in);
System.out.print("please enter two whole numbers:");
a1 = input.nextInt();
b = input.nextInt();
System.out.print("please enter your computing type:[a-addition s-subtraction m-multiplication d-division]:");
c = input.next().charAt(0);
switch (c) {
case 'a' -> System.out.format("%d+%d=%d", a1, b, a1 + b);
case 's' -> System.out.format("%d-%d=%d", a1, b, a1 - b);
case 'm' -> System.out.format("%d*%d=%d", a1, b, a1 * b);
case 'd' -> {
if (b == 0) {
System.out.println("the divisor is not 0 error!!!");
} else {
System.out.format("%d/%d=%d", a1, b, a1 / b);
}
}
default -> System.out.println("input error please try again!!!");
}
}
}
switch (c) {
case 'a' -> System.out.format("%d+%d=%d", a1, b, a1 + b);
case 's' -> System.out.format("%d-%d=%d", a1, b, a1 - b);
case 'm' -> System.out.format("%d*%d=%d", a1, b, a1 * b);
case 'd' -> {
if (b == 0) {
System.out.println("the divisor is not 0 error!!!");
} else {
System.out.format("%d/%d=%d", a1, b, a1 / b);
}
}
default -> System.out.println("input error please try again!!!");
}
switch-case
语句中case
处的数据类型,因为设定了变量c
为char
类型,所以需要使用 c = input.next().charAt(0) 语句接收用户键盘上的单个字符输入,charAt()
方法用于返回指定索引处的字符,索引范围为从 0 到length() - 1
。switch
结构,给出参考代码。主要特点如下:需要返回值、无需 break
、使用箭头->
、可进行 case 间的合并,以逗号分隔。#include <stdio.h>
int calculate(int operand1, int operand2, char type)
{
char a, s, m, d;
switch (type)
{
case 'a':
printf("%d+%d=%d", operand1, operand2, operand1 + operand2);
break;
case 's':
printf("%d-%d=%d", operand1, operand2, operand1 - operand2);
break;
case 'm':
printf("%d*%d=%d", operand1, operand2, operand1 * operand2);
break;
case 'd':
{
if (operand2 == 0)
{
printf("the divisor is not 0 the error please try again");
break;
}
else
{
printf("%d/%d=%d", operand1, operand2, operand1 / operand2);
break;
}
}
default:
printf("if the type of operation is not specified please re enter!!!");
}
}
int main()
{
int a, b;
char c;
printf("please enter two integers:");
scanf("%d%d", &a, &b);
printf("please enter your computing type:[a-addition s-subtraction m-multiplication d-division]:");
getchar();
scanf("%c", &c);
calculate(a, b, c);
return 0;
}
因为有四种计算类型,所以我们使用
switch-case
语句解决,注意除法计算中除数不为 0 的条件判断,且case
后需为常量,这里使用字符做判断条件,加上单引号‘’
变为字符常量。