类和对象代码练习

1.编写一个类Calculator,有两个属性num1,num2,这两个数据的值,不能在定义的同时初始化,最后实现加减乘 除四种运算.
2.设计一个包含多个构造函数的类,并分别用这些构造函数来进行实例化对象。
3.实现交换两个变量的值。要求:需要交换实参的值
代码:
1.

import java.util.Scanner; class Calculator{ 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 int add(int num1,int num2){ return num1+num2; } public int difference(int num1,int num2){ return num1-num2; } public int product(int num1,int num2){ return num1*num2; } public double quotient(int num1,int num2){ return num1*1.0/num2; } }public class HomeWork{ public static void main(String[] args) { System.out.println("请输入两个整数: "); Calculator calculator = new Calculator(); Scanner scanner = new Scanner(System.in); calculator.setNum1(scanner.nextInt()) ; calculator.setNum2(scanner.nextInt()); System.out.println(calculator.add(calculator.getNum1(), calculator.getNum2())); System.out.println(calculator.difference(calculator.getNum1(), calculator.getNum2())); System.out.println(calculator.product(calculator.getNum1(), calculator.getNum2())); System.out.println(calculator.quotient(calculator.getNum1(), calculator.getNum2())); } }

【类和对象代码练习】2.
class Person{ private int age; private String name; public Person(){} public Person(int age, String name){ this.age = age; this.name = name; }public void show(){ System.out.println("age: " + age + " name: " + name); }public int getAge() { return age; }public void setAge(int age) { this.age = age; }public String getName() { return name; }public void setName(String name) { this.name = name; } }public class HomeWork{ public static void main(String[] args) { Person person = new Person(); person.setAge(17); person.setName("ys"); person.show(); Person person1 = new Person(18, "ysa"); person1.show(); } }


3.
public class HomeWork{ public static void swap(int[]arr){ int tmp = arr[0]; arr[0] = arr[1]; arr[1] = tmp; } public static void main(String[] args) { int[] array = {12,23}; System.out.println("array[0]= " + array[0] + "arr[1]= " + array[1]); swap(array); System.out.println("array[0]= " + array[0] + "arr[1]= " + array[1]); } }


    推荐阅读