4.12 Java

1.在线IDE的 public class 名字一定要是Main
2.一个Java程序内最多一个public class
3.prublic static void main(String []args)
4.静态()独立于实例对象 可以直接通过访问类来调用

常见程序:

import java.util.Scanner;
public class Main
{
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int x = input.nextInt();
        int y = input.nextInt();
        System.out.printf("x+y=%d",x+y);
    }
}

Java有垃圾回收机制 不用担心内存泄漏的问题

自定义复数类 同时用 @Override对输出的toString()方法进行自定义改写

import java.util.Scanner;
public class Main
{
    private double a,b;
    public Main(){
    }
    public Main(double a){
        this.a = a;
    }
    public Main(double a,double b){
        this.a = a;
        this.b = b;
    }
    public double getA(){
        return a;
    }
    public void setA(double a){
        this.a = a;
    }
    public double getB(){
        return b;
    }
    public void setB(double b){
        this.b = b;
    }
    public Main add(Main cn){
        Main tmp = new Main();
        tmp.setA(this.getA() + cn.getA());
        tmp.setB(this.getB() + cn.getB());
        return tmp;
    }
    public Main minus(Main cn){
        Main tmp = new Main();
        tmp.setA(this.getA() - cn.getA());
        tmp.setB(this.getB() - cn.getB());
        return tmp;
    }
    @Override
    public String toString(){
        if(a == 0.0) return b + "i";
        if(b == 0.0) return a + "";
        if(b < 0.0) return a + "" + b + "i";
        else return a + "+" + b + "i";
    }
    public static void main (String[] args) {
        /* code */
        Scanner input = new Scanner(System.in);
        double x1,x2,y1,y2;
        x1 = input.nextDouble();
        y1 = input.nextDouble();
        x2 = input.nextDouble();
        y2 = input.nextDouble();
        Main a = new Main(x1,y1);
        Main b = new Main(x2,y2);
        System.out.println("("+ a + ")"+" + "+"("+ b + ") = " + (a.add(b)));
    }
}
posted @ 2023-04-12 23:20  N0zoM1z0  阅读(5)  评论(0编辑  收藏  举报