写一个类Calculator,有两个属性num1,num2,这两个数据的值,不能在定义的同时初始化,最后实现加减乘
除四种运算
class Calcuter{
private int num1;
private int num2;
public int add(int num1 ,int num2 ){
this.num1 = num1;
this.num2 = num2;
return this.num1 + this.num2;
}
public int sub(int num1 , int num2){
this.num1 = num1;
this.num2 = num2;
return this.num1 - this.num2;
}
public int mul(int num1 , int num2){
this.num1 = num1;
this.num2 = num2;
return this.num1 * this.num2;
}
public int div(int num1 , int num2){
this.num1 = num1;
this.num2 = num2;
return this.num1 / this.num2;
}
}
public class Test{
public static void main(String[] args) {
Calcuter cal = new Calcuter();
System.out.println(cal.add(5,6));
System.out.println(cal.div(5,6));
System.out.println(cal.mul(5,6));
System.out.println(cal.sub(5,6));
}
}
设计一个包含多个构造函数的类,并分别用这些构造函数来进行实例化对象。
class Man{
private int age;
private String name;
private String job;
public Man(int age, String name, String job) {
this.age = age;
this.name = name;
this.job = job;
}
public void show(){
System.out.println("My name is "+this.name+" aged "+this.age+",and my job is "+this.job);
}
@Override
public String toString() {
return "Man{" +
"age=" + age +
", name='" + name + '\'' +
", job='" + job + '\'' +
'}';
}
}
public class Test{
public static void main(String[] args) {
Man LBW = new Man(25,"Lbwnb","LOL");
System.out.println(LBW);
LBW.show();
}
}
实现交换两个变量的值。要求:需要交换实参的值。
import java.util.Scanner;
class Swap {
private int num1;
private int num2;
public int getNum1() {
return num1;
}
public void setNum1(int num1) {
this.num1 = num1;
}
public int getNum2() {
return num2;
}
public void setNum2(int num2) {
this.num2 = num2;
}
public void swap(){
int t = this.num1;
this.num1 = this.num2;
this.num2 = t;
System.out.printf("交换的值为 num1 = %d, num2 = %d", num1, num2);
}
}
public class Test {
public static void main(String[] args) {
Swap change = new Swap();
Scanner sc = new Scanner(System.in);
System.out.println("请输入要交换的两个数:");
change.setNum1( sc.nextInt());
change.setNum2( sc.nextInt());
change.swap();
sc.close();
}
}
class MyValue {
public int val;
}
public class HomeWork {
public static void swap(MyValue myValue1,MyValue myValue2) {
int tmp = myValue1.val;
myValue1.val = myValue2.val;
myValue2.val = tmp;
}
public static void main(String[] args) {
MyValue myValue1 = new MyValue();
myValue1.val = 10;
MyValue myValue2 = new MyValue();
myValue2.val = 20;
System.out.println(myValue1.val+" " +myValue2.val);
swap(myValue1,myValue2);
System.out.println(myValue1.val+" " +myValue2.val);
}