编写一个类Calculator,有两个属性num1,num2,这两个数据的值,不能在定义的同时初始化,最后实现加减乘除四种运算.
public class HomeWork {
public static void main(String[] args) {
Scanner scan0 = new Scanner(System.in);
Scanner scan1 = new Scanner(System.in);
while(true) {
int x = scan0.nextInt();
int y = scan1.nextInt();
Calculator calculator = new Calculator(x, y);
System.out.println(x + " + " + y + "= " + calculator.add());
System.out.println(x + " - " + y + "= " + calculator.sub());
System.out.println(x + " * " + y + "= " + calculator.mul());
System.out.println(x + " / " + y + "= " + calculator.dev());
}
}
}
class Calculator {
private int num1;
private int num2;
public int add() {
return this.num1 +this.num2;
}
public int sub() {
return this.num1 -this.num2;
}
public int mul() {
return this.num1 *this.num2;
}
public double dev() {
double ret = (double)this.num1 / this.num2;
return ret;
}
public Calculator(int num1, int num2) {
this.num1 = num1;
this.num2 = num2;
}
}
实现交换两个变量的值。要求:需要交换实参的值
public class HomeWork0 {
public static void main(String[] args) {
System.out.println("第一种");
int[] arr = {10,20};
System.out.println("交换前"+Arrays.toString(arr));
swap(arr);
System.out.println("交换后"+Arrays.toString(arr));
System.out.println();
System.out.println("第二种");
MyValue myValue1 = new MyValue();
myValue1.val = 1;
MyValue myValue2 = new MyValue();
myValue2.val = 2;
System.out.println("交换前: "+myValue1.val+" "+myValue2.val);
swap(myValue1,myValue2);
System.out.println("交换后: "+myValue1.val+" "+myValue2.val);
}
public static void swap(MyValue myValue1,MyValue myValue2) {
int tmp = myValue1.val;
myValue1.val = myValue2.val;
myValue2.val = tmp;
}
public static void swap(int[] arr) {
int tmp = arr[0];
arr[0] = arr[1];
arr[1] = tmp;
}
}
class MyValue {
public int val;
}
以上就是动力节点java培训机构的小编针对“编程基础分享,Java类与对象练习题”的内容进行的回答,希望对大家有所帮助,如有疑问,请在线咨询,有专业老师随时为你服务。
你适合学Java吗?4大专业测评方法
代码逻辑 吸收能力 技术学习能力 综合素质
先测评确定适合在学习