java上机实验
我们使用的教材是《java简明教程(第三版)》- 皮德常
复数的运算
这是我们java上机实验课的第三次上机作业,本次要求我们练习第四章第2题。
同样的道理,我们先仔细观察一波题目,死死盯着它,让它不好意思。然后我们就有了思路,同样的使用方法,一眼看出法,不需要过多的解释。
分析
别想了,分析是不可能分析的,这辈子都不可能分析。
说到分析,这题题目虽然短,但回想一下以前数学题目,是不是题目越短越难?呵,这题却很可爱。
- 首先,我们看到一个关键词类,也就是
class
,因此我们需要定义一个类叫做complex
。 - 其次,我们又看见一个关键词俩个实例变量,所以,类里面需要定义俩个
int
变量。一个叫realPart
,另一个叫imagPart
。 - 最后,我们看到有三个小问,所以大概率需要三个方法(
method
),然后就开始动手了。
暴力破解
import java.util.Scanner;
class complex{
int realPart,imagPart;
complex(int r, int i){
this.realPart = r;
this.imagPart = i;
}
void add(complex other){
int addRealPart, addImagPart;
addRealPart = this.realPart + other.realPart;
addImagPart = this.imagPart + other.imagPart;
System.out.println("addResult: " + addRealPart + " + " + addImagPart + "j");
}
void sub(complex other){
int subRealPart, subImagPart;
subRealPart = this.realPart - other.realPart;
subImagPart = this.imagPart - other.imagPart;
System.out.println("subResult: " + subRealPart + " + " + subImagPart + "j");
}
}
public class chapter4_2 {
public static void main(String[] arg){
Scanner S = new Scanner(System.in);
System.out.println("Please input realPart and imagPart.");
complex a = new complex(S.nextInt(),S.nextInt());
System.out.println("Please input another realPart and imagPart.");
complex b = new complex(S.nextInt(),S.nextInt());
S.close();
a.add(b);
a.sub(b);
}
}
结果显示:
Please input realPart and imagPart.
65 85
Please input another realPart and imagPart.
100 50
addResult: 165 + 135j
subResult: -35 + 35j
求解圆面积
此次上机有俩道作业,这一道是第四章第3题
分析
- 一个类
- 一个变量
- 键盘输入
- 构造函数
- 计算面积和周长,大概率需要俩方法(
method
) - 数据输入不为负数
暴力破解
import java.util.Scanner;
class circle{
double radius;
circle(double _radius){
this.radius = _radius;
}
void circum(){
double result;
result = 2 * Math.PI * this.radius;// 使用Math.PI来调用π值
System.out.printf("The circum is: %.2f\n",result);
}
void area(){
double result;
result = Math.PI * this.radius * this.radius;// 使用Math.PI来调用π值
System.out.printf("The area is: %.2f\n",result);
}
}
public class chapter4_3 {
public static void main(String[] arg){
Scanner S = new Scanner(System.in); // 启动输入程序。
System.out.printf("Please input a radius: ");
double radius = S.nextDouble();
S.close(); // 务必记住需要close()。
if(radius < 0) { // 判断非负
System.out.println("The radius is invalid.");
return;
}
circle c = new circle(radius);
c.circum();
c.area();
}
}
结果显示:
Please input a radius: 3
The circum is: 18.85
The area is: 28.27
Please input a radius: -9
The radius is invalid.
叨叨几句... NOTHING