注:本文非标准教程,仅是总结个人学习过程,可能存在纰漏,如有错误之处欢迎留言告知,非常感谢
刚开始学java,给自己留点笔记。
所用编辑器是Eclipse。
面向过程的解法
package test;
import java.util.*;
public class Rectangle {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("请输入长方形的长和宽");
int a=in.nextInt();
int b=in.nextInt();
System.out.println("面积是:"+(a*b));
System.out.println("周长是:"+(2*(a+b)));
}
}
笼统的过程开发,就像用C做一样,学习java应该减少使用这种做法。
面向对象的解法1
package test;
import java.io.*;
import java.util.*;
public class Rectangle {
public int longth,width;
public int getArea(int l,int w) {
long=l;
width=w;
System.out.println("面积:"+LongSK*Width);
return l*w;
}
public int getRrimeter(int l,int w) {
longth=l;
width=w;
System.out.println("周长:"+2*(longth+width));
return 2*(l+w);
}
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("请输入长方形的长和宽");
int l=in.nextInt();
int w=in.nextInt();
int A=new Rectangle().getArea(l, w);
A=new Rectangle().getPerimeter(l, w);
}
}
去请教了老师,然后老师说这个解法不是很好(哭)
原因是longth和width可以在方法里使用,方法不需要设置参数来代替longth和width,所以这个解法不好。
面向对象的解法2
package test;
import java.util.*;
public class Rectangle {
int longth,width;
public int getArea() {
//System.out.println("面积:"+longth*width);
return longth*width;
}
public int getPerimeter() {
//System.out.println("周长:"+2*(longth+width));
return 2*(longth+width);
}
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int B,C;
Rectangle A=new Rectangle();
System.out.println("请输入长方形的长和宽");
A.longth=in.nextInt();
A.width=in.nextInt();
B= A.getArea();
C=A.getPerimeter();
System.out.println("面积:"+B);
System.out.println("周长:"+C);
}
}
这个就不在方法里带参数。。
总结:
1、int A=new Rectangle().SetArea(l, w); 用main函数里的变量来调用类里的方法。
2、学习到了对于属性在方法里的使用。
(方法相当于主类里的函数;属性是主类里的定义的变量。)
3、import java.util.*;
是导入包,相当于C++里的 using namespace std;