01、用户交互Scanner
Scanner scanner = new Scanner(System.in);
System.out.println("使用next方式接收:");
if (scanner.hasNext()) {
String str = scanner.nextLine();
System.out.println("输入的内容:"+str);
}
//用完就关掉
scanner.close();
02、Scanner进阶使用
Scanner scanner = new Scanner(System.in);
int i = 0;
float f = 0.0F;
System.out.println("请输入数字:");
if (scanner.hasNextInt()) {
i = scanner.nextInt();
System.out.println("整数:" + i);
} else if (scanner.hasNextFloat()) {
f = scanner.nextFloat();
System.out.println("浮点数:" + f);
} else {
System.out.println("输入的不是整数或者浮点数~");
}
//用完就关掉
scanner.close();
03、顺序结构
04、if选择结构
05、switch选择结构
switch 语句中的变量类型可以是: byte、short、int 或者 char。从 Java SE 7 开始,switch 支持字符串 String 类型了,同时 case 标签必须为字符串常量或字面量。
case 穿透
String grade = "A";
switch (grade) {
case "A": {
System.out.println("优秀");
return;
}
case "B": {
System.out.println("良好");
return;
}
case "C": {
System.out.println("及格");
return;
}
case "D": {
System.out.println("不及格");
return;
}
default: {
System.out.println("未知等级");
}
}
06、while循环详解
07、do while循环
1、
while(条件){
//语句块
}
2、
do{
//语句块
}while(条件)
08、for循环详解
死循环
for (; ;) {
System.out.println("死循环中");
}
09、打印九九乘法表
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + "*" + i + "=" + (i * j) + "\t");
}
System.out.println();
}
输出
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
10、增强for循环
11、break/continue/goto
goto
//打印101-150的所有的质数
//质数是指在大于1的自然数中,除了1和它本身以外不再有其他因数的自然数
//不推荐使用!
outer:
for (int i = 101; i <= 150; i++) {
for (int j = 2; j < i / 2; j++) {
if (i % j == 0) {
continue outer;
}
}
System.out.print(i + " ");
}
输出
101 103 107 109 113 127 131 137 139 149
12、打印三角形及debug
//打印三角形(5行)
for (int i = 1; i <= 5; i++) {
for (int j = 5; j > i; j--) {
System.out.print(" ");
}
for (int k = 1; k <= i; k++) {
System.out.print("*");
}
for (int n = 1; n < i; n++) {
System.out.print("*");
}
System.out.println();
}
输出
*
***
*****
*******
*********