类和对象代码练习

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]);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值