基本结构
1.顺序结构
Java最基本的结构,除非特别指明,否则程序就按照顺序一句一句,一块一块的去执行
2.选择结构
if…else
import java.util.Scanner;
public class Demo3_if {
public static void main(String[] args) {
int i;
Scanner scanner=new Scanner(System.in);
System.out.println("请输入一个整数:");
if(scanner.hasNextInt()){
i=scanner.nextInt();
System.out.println("你输入的整数是:"+i);
}else{
System.out.println("输入了非整数");
}
}
}
switch
变量支持:int/short/byte/char/String(JDK7之后开始支持)
源文件:
import java.util.Scanner;
public class Demo5_switch {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
String str=scanner.nextLine();
//switch里的变量支持:
// byte,char,short,int
// String(JDK7开始,通过查看反编译文件,可以看到实际还是比较数值型,因为先计算量字符串的hashcode)
switch(str){
case "yousi":
System.out.println("幼斯");
break;
case "sanfen":
System.out.println("三分");
break;
default:
System.out.println(str);
}
}
}
反编译文件.class
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package scanner;
import java.util.Scanner;
public class Demo5_switch {
public Demo5_switch() {
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
byte var4 = -1;
switch(str.hashCode()) {
case -909655121:
if (str.equals("sanfen")) {
var4 = 1;
}
break;
case 115168949:
if (str.equals("yousi")) {
var4 = 0;
}
}
switch(var4) {
case 0:
System.out.println("幼斯");
break;
case 1:
System.out.println("三分");
break;
default:
System.out.println(str);
}
}
}
3.循环结构
1. while和do…while
while和do…while的区别:
while:先判断再执行;
do…while:先执行再判断,至少执行一次
package scanner;
/**
* 使用while和do-while
* @author zhaomin
* @date 2022/2/23 23:29
*/
public class Demo6_while {
public static void main(String[] args) {
//while:先判断再执行
//计算1+2+....+100
int i=0;
int sum=0;
while(i<=100){
sum+=i;
i++;
}
System.out.println(sum);//5050
//do...while循环体至少执行一次
int b=1;
int result=0;
do{
result+=b;
b++;
}while(b<=100);
System.out.println(result);//5050
}
}
2.for循环
(1)普通for循环
/*九九乘法表*/
public class Demo7_for {
public static void main(String[] args) {
for(int i=1;i<=9;i++){
for(int j=1;j<=i;j++){
System.out.print(j+"*"+i+"="+(j*i)+'\t');
}
System.out.println();
}
}
}
(2)增强for循环:循环数组和集合
int[] arr={1,2,3};
for(int num:arr){
System.out.println(num);
}
(3)跳出循环
a.break 跳出整个循环
for(int i=0;i<10;i++){
if(i==5){
break;
}
System.out.print(i+' ');
}
b.continue 跳出本次循环
for(int i=0;i<10;i++){
if(i==5){
continue;
}
System.out.print(" "+i);
}
c.goto: 跳到循环标记的标签处(不常用)
/*打印质数*/
outer:for(int i=100;i<110;i++){
for(int j=2;j<i/2;j++){
if(i%j==0){
continue outer;
}
}
System.out.print(i+" ");
}
(4)打印三角形
for(int i=1;i<=5;i++){
for(int j=5;j>i;j--){
System.out.print(" ");
}
for(int j=1;j<=i;j++){
System.out.print("*");
}
for(int j=1;j<i;j++){
System.out.print("*");
}
System.out.println();
}