Java提供了三种循环结构:
while循环
do...while 循环
for 循环
do{} while();do..while至少运行一次
public class DoWhileDemo1 {
public static void main(String[] args) {
// int i = 10;
// while(){}
// while(i < 5) {
// System.out.println("hello1");
// i++;
// }
// do{}while(); : do..while至少执行一次
// int j = 10;
// do {
// System.out.println("hello2");
// j++;
// }while(j < 5);
// for(循环变量初始化;循环条件;循环变量步长)
// 1.循环变量初始化
// 2.判断是否满足循环条件
// 3.执行循环体
// 4.循环变量增加或减少
// 5.在回到第二步,如此往复
for(int i = 0;i < 5;i++) {
System.out.println("hello");
}
}
}
break 和continue的作用
public class Demo4 {
public static void main(String[] args) {
// break的使用
while(true) {
Scanner scan = new Scanner(System.in);
System.out.println("请输入选项:");
System.out.println("1-------登录");
System.out.println("2-------注册");
System.out.println("3-----退出程序");
int option = scan.nextInt();
if(option < 0 || option > 3) {
System.out.println("无效选项");
}else {
if(option == 1) {
System.out.println("登录成功");
}else if(option == 2) {
System.out.println("注册成功");
}else {
System.out.println("退出成功");
break;
}
}
}
System.out.println("欢迎下次再来!!!!");
}
}
public class HomeWork_OP5 {
public static void main(String[] args) {
// 输出0-9之间的数,但是不包括5
int i = 0;
// while(i < 10) {
// if(i != 5) {
// System.out.print(i);
// }
// i++;
// }
while(i < 10) {
if(i == 5) {
i++;
// 跳过本次循环
continue;
}
System.out.print(i);
i++;
}
}
}
额外知识点
Debug 调试
public class DebugDemo {
public static void main(String[] args) {
// 双击加断点,右键-->Debug as-->F6
int num = 100;
if(num < 50) {
num++;
}
System.out.println(num);
}
}
Scanner的使用问题
public class ScannerProblemDemo {
public static void main(String[] args) {
// 特殊情况:第一次获取的是数字,第二次获取是字符串
Scanner scan = new Scanner(System.in);
System.out.println("请输入一个数字1");
int num1 = scan.nextInt();
System.out.println("请输入一个字符串2");
scan.nextLine();
String str2 = scan.nextLine();
System.out.println(num1+","+str2);
/*
* 在控制台输入的所有数据都会进入内存
* int num1 = scan.nextInt();
* num1会将内存中的数据取走,但内存中还保留了一个enter
* String str2 = scan.nextLine();str2直接就把上次留下的enter取走了
* 所以没有给我们输入字符串的机会
* 解决方式:先用scan.nextLine();把上次留下的enter取走
*/
}
}
随机数
public class RandomDemo {
public static void main(String[] args) {
// 产生随机数
double num1 = Math.random();//[0,1)
// Scanner scan = new Scanner(System.in);
// 随机数类
Random random = new Random();
// random.nextDouble() [0,1)的小数
// random.nextInt(n) [0,n)的整数
double num2 = random.nextDouble();
System.out.println(num2);
}
}
网友评论