20192316 2020-2021-1 《数据结构与面向对象程序设计》实验二报告
20192316 2020-2021-1 《数据结构与面向对象程序设计》实验二报告
课程:《程序设计与数据结构》
班级: 1923
姓名: 贝世之
学号:20192316
实验教师:王志强
实验日期:2020年10月8日
必修/选修: 必修
1.实验内容
- 编写简单的计算器,完成加减乘除模运算。
- 要求从键盘输入两个数,使用判定语句选择一种操作,计算结果后输出,然后使用判定和循环语句选择继续计算还是退出。
- 编写测试代码,测试验证。(https://www.cnblogs.com/rocedu/p/4472842.html)
2. 实验过程及结果
2.1编写简单的计算器
采用主函数负责提示和输入,子函数负责计算的方法(代码已注释)
import java.util.Scanner;
public class task2 { //主函数用于提示和输入
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("If you want to compute the operations of a and b");
char d; //定义d作为跳出循环的依据
do{
System.out.print("Please enter the of a = ");
double a = scan.nextDouble(); //输入要计算的数的值
System.out.print("Please enter the of b = ");
double b = scan.nextDouble();
System.out.print("If you want to calculate addition, enter 1.\n" +
"If you want to calculate subtraction, enter 2.\n" +
"If you want to calculate multiplication, enter 3.\n" +
"If you want to calculate division method, enter 4.\n" +
"If you want to calculate module, enter 5.\n");
int c = scan.nextInt(); //选择运算符
if((b==0&&c==4)||(b==0&&c==5)||( c!=1 && c!=2 && c!=3 && c!=4 && c!=5 )){
System.out.println("Error!"); //如果除法和模运算中除数为0或运算符不是加减乘除模,则报错
}
double resule = calculate(a,b,c); //子函数运算
System.out.println("resule = "+resule);
do {
System.out.println("Do you want to keep counting? y/n");
d = scan.next().charAt(0);
}while(d != 'y' && d != 'n'); //是否继续运算,y继续,n退出
}while(d == 'y');
}
public static double calculate(double a, double b, int c) { //子函数主要负责计算
if(c==1){
return a+b;
}
else if(c==2){
return a-b;
}
else if(c==3){
return a*b;
}
else if(c==4){
return a/b;
}
else if(c==5){
return a%b;
}
else {
return 0.0;
}
}
}
2.2运行结果
2.3测试代码
public class task2Test { //单元测试
public static void main(String[] args) {
double resule = task2.calculate(8,5,1); //给a,b赋值代入测试,c为运算符号
if(resule == 13){
System.out.println("pass1."); //加法测试通过
}
else{
System.out.println("fault1."); //加法测试失败
}
resule = task2.calculate(8,5,2);
if(resule == 3){
System.out.println("pass2."); //减法测试通过
}
else{
System.out.println("fault2.");
}
resule = task2.calculate(8,5,3);
if(resule == 40){
System.out.println("pass3."); //乘法测试通过
}
else{
System.out.println("fault3.");
}
resule = task2.calculate(10,5,4);
if(resule == 2){
System.out.println("pass4."); //除法测试通过
}
else{
System.out.println("fault4.");
}
resule = task2.calculate(8,5,5);
if(resule == 3){
System.out.println("pass5."); //模测试通过
}
else{
System.out.println("fault5.");
}
}
}
2.4测试结果
2.5上传码云
3. 实验过程中遇到的问题和解决过程
- 问题1:无法输入字符
- 问题1解决方案:先定义字符型变量ch,
再用此方式输入字符
ch = scan.next().charAt(0);
- 问题2:在编程环境中语句过长,过行时结构混乱
- 问题2解决方案:在变成环境的帮助下,明白要先用“”将本行内容引住,在句尾添加+,下一行再用“”引住剩余内容,以此类推。
其他(感悟、思考等)
感悟:
- 之前用c语言编写过简单的计算器,思路上与java差别不大,但是代码内容差别还是很大的。
- 刚看完单元测试就上机操作,操作过程中仍然遇到较多卡顿,还应多多实践。
思考:有编程环境的生活比命令行舒坦多了,但还是很苦o(╥﹏╥)o,科技为懒人带来福利。
参考资料
https://blog.csdn.net/weixin_43922093/article/details/100811374