主函数: double d=Math.random(); //打印[0,1)中的随机数 int h=(int)(6*Math.random+1); //打印[1,6]中的随机整数2.使用Math
主函数: double r=4; double area=Math.PI*Math.pow(r,2); System.out.println(area); //输出PI*r*r的值3.while循环(先判断后执行)
主函数:
int i=1;
int sum=0;
while(i<=100){
sum=sum+i;
i++;
} //输出1+2+3+4+.....100的和
4.do-while循环(先执行后判断)
主函数:
int i=1;
int sum=0;
do
{sum+=i;
i++;
}while(i<=100) //输出5050
5.continue语句while实现的问题都可用for循环实现,注意for( : : ) //是死循环,相当于while(true)
public class Test{
public static void main(String[] args) {
int count = 0;//定义计数器
for (int i = 100; i < 150; i++) {
//如果是3的倍数,则跳过本次循环,继续进行下一次循环
if (i % 3 == 0){
continue;
}
//否则(不是3的倍数),输出该数
System.out.print(i + "、");
count++;//没输出一个数,计数器加1
//根据计数器判断每行是否已经输出了5个数
if (count % 5 == 0) {
System.out.println();
}
}
}
}
6.带标签的continuecontinue的主要作用是跳过本次循环进行下一次循环
主函数:
outer:for(int i=101;i<150;i++){
for(int j=2;j
省去不必要的步骤
7.递归结构(自己调用自己)
public class Text059 {
public static void main(String[] args) {
System.out.printf("%d阶乘的结果:%s%n",5,factorial(5));
}
static long factorial(int n) {
if(n==1) {
return 1;
}else {
return n*factorial(n-1);
}
}
} //求5的阶乘
程序简单但占用大量系统堆栈,内存耗用多,速度比循环慢很多
8.循环求阶乘
public class Text05902 {
public static void main(String[] args) {
factorialLoop(5);
}
static long factorialLoop(int a) {
long result=1;
while(a>1) {
result*=a*(a-1);
a-=2;
}
System.out.println(result);
return result;
}
}
用递归实现的 都能用循环实现,尽量避免使用递归
9.构造函数
class Point{
double x,y;
public Point(double _x,double _y) {
x=_x;
y=_y;
}
public double getDistance(Point p) {
return Math.sqrt((x-p.x)*(x-p.x)+(y-p.y)*(y-p.y));
}
}
public class Text065 {
public static void main(String[] args) {
Point p=new Point(3.0,4.0);
Point ori=new Point(0.0,0.0);
System.out.println(p.getDistance(ori));
}
}
构造方法,求两点间距离
10.构造函数重载
public class User {
int id; // id
String name; // 账户名
String pwd; // 密码
public User() {
}
public User(int id, String name) {
super();
this.id = id;
this.name = name;
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
public static void main(String[] args) {
User u1 = new User();
User u2 = new User(101, "王哥");
User u3 = new User(100, "王哥", "123456");
}
}
11.package的使用
package cn.sxt;
public class Test {
public static void main(String[] args) {
System.out.println("helloworld");
}
}
在src目录上单击右键,选择new->package
12.导入类import
import java.sql.Date;
import java.util.*;//导入该包下所有的类。会降低编译速度,但不会降低运行速度。
public class Test{
public static void main(String[] args) {
//这里指的是java.sql.Date
Date now;
//java.util.Date因为和java.sql.Date类同名,需要完整路径
java.util.Date now2 = new java.util.Date();
System.out.println(now2);
//java.util包的非同名类不需要完整路径
Scanner input = new Scanner(System.in);
}
}
用导入类import可以调用不同文件里的类,简化程序,条理清晰



