无限循环,跳转控制语句
一、无限循环的三种格式
//////////////FOR////////////////
for(;;){
System.out.println("Hello World!");
}
///////////////while/////////////
while(true){
System.out.println("Hello World!");
}
///////////////do-while//////////
do{
System.out.println("Hello World!");
}while(true);
其中While(true)是最常用的
二、跳转控制语句
for (int i = 1; i <= 10; i++) {
if(i == 2) {
continue; //终止本次循环,直接进行下一次循环
}else if(i == 4) {
break; //跳出循环体,直接执行循环后的语句
}
System.out.println("小老虎在吃第"+ i +"个包子");
}
continue; //终止本次循环,直接进行下一次循环
break; //跳出循环体,直接执行循环后的语句
三、案例
/////////////////////////////////////////////案例一:逢七过///////////////////////////////////////////
/*
* 游戏规则:从任意数开始报数,当遇到七或七的倍数或者包含7时要说:过
* 代码要求:使用程序在控制台输出1-100之间的数,满足逢七过的规则
*/
for (int i = 1; i <= 100; i++) {
if((i % 7 == 0)||((i / 10) == 7||((i % 10) == 7))){
System.out.println("过");
continue;
}
System.out.println(i);
}
//////////////////////////////////////案例二:计算平方根///////////////////////////////////
/*
* 代码要求:计算平方根的整数位
*/
System.out.println("请输入一个数字来估算范围与判断质数:");
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
int i = 1;
while(true) {
if(i *i == num){
System.out.println("平方根的就是" + i);
break;
}else if(i*i >= num){
System.out.println(num + "平方根的整数范围是" + ( i - 1 ) + "-" + i);
break;
}
i++;
}
/////////////////////////////////////////案例三:求质数////////////////////////////////////
int numsqr = (i - 1); ////////////寻找范围是2-根号下num,这里用到上面的开平方
boolean flag = true; ////////////使用一个变量来记录循环结果
for (int j = 2; j <= numsqr; j++) {
if(num % j == 0){
flag = false;
break;
}
}
if(flag){
System.out.println(num + "是质数");
}else{
System.out.println(num + "不是质数");
}
////////////////////////////////////////案例四:猜随机数//////////////////////////////////////
Random rnd = new Random();
//int rndnum = rnd.nextInt(100); 范围是0-99,包头不包尾,包左不包右
int rndnum = rnd.nextInt(100) + 1;
System.out.println("你有五次机会,猜一个1-100的数:");
int cont = 1;
while(true){
num = scanner.nextInt();
if(num < rndnum){
System.out.println("猜小了哦~");
}else if(num == rndnum){
System.out.println("恭喜你,猜对了!");
break;
}else{
System.out.println("猜大了呢");
}
if(cont == 5){
System.out.println("五次机会已经用完,失败了!");
break;
}
cont++;
}
数组
一、数组的定义
1. 数据类型 [] 数组名 int [] array
2. 数据类型 数组名[] int array[]
二、数组的静态初始化
数据类型[] 数组名 = new 数据类型[]{元素1,元素2,元素3,...};
简写格式: 数据类型[] 数组名 = {元素1,元素2,元素3,...};
int[] array = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
System.out.println(array);
//输出数组的地址值"[I@6f539caf" [表示这是一个数组,I表示类型为int,@为连接符,后面的十六进制为内存地址
三、数组元素的访问
1.获取
格式:数组名[索引] 从0开始
2.写入
数组名[索引] = 值或变量
3.数组的属性
获取长度:数组名.length
四、数组的动态初始化
数据类型[] 数组名 = new 数据类型[数组长度]
规律:
数据类型 | 默认初始化值 |
整数 | 0 |
小数 | 0.0 |
字符串 | '/u0000' |
布尔 | false |
引用数据类型 | null |
五、打乱数组的练习
///////////////////////////////////////////练习:打乱数组中的数据///////////////////////////////////////////////
for (int i1 = 0; i1 < array.length; i1++) {
rndnum = rnd.nextInt(array.length);
int temp = array[i1];
array[i1] = array[rndnum];
array[rndnum] = temp;
}
for(int i1 = 0; i1 < array.length; i1++) {
System.out.println(array[i1]);
}