一、选择结构
if else
public class HelloWorld {
public static void main(String []args) {
boolean k=true;
if(k){
System.out.println("true");
}else{
System.out.println("false");
}
int u=6;
if(u<5){
System.out.println("u < 5");
}else if(u<10){
System.out.println("5 < u < 10");
}else{
System.out.println(u);
}
}
}
switch case
单变量多值判断。
public class HelloWorld {
public static void main(String []args) {
int u=6;
switch(u){
case 1:
System.out.println("u = 1");
break;
case 2:
System.out.println("u = 2");
break;
case 3:
System.out.println("u = 3");
break;
default:
System.out.println("u = other");
}
}
}
二、循环结构
- break; 结束整个循环。
- continue; 跳过本次循环,进入下一次循环。
while
满足条件后跳出。注意不要搞成死循环了。
do-while 是先执行在判断,实际工作中使用较少。
public class HelloWorld {
public static void main(String []args) {
int k = 0;
int c = 0;
//求1到100的累加
while(k<=100){
c+=k++;
}
System.out.println(c); //5050
}
}
for
是在while的基础上规范了写法,实际开发中比while还常用。
public class Main {
public static void main(String []args) {
int c = 0;
//求1到100的累加
for(int k=0;k<=100;k++){
c+=k;
}
System.out.println(c); //5050
}
}
public class Main {
public static void main(String []args) {
//打印九九乘法表
for(int a=1;a<=9;a++){
for(int b=1;b<=a;b++){
System.out.print(""+a+"*"+b+"="+(a*b)+"\t");
}
System.out.println("");
}
}
}
public class Main {
public static void main(String []args) {
//打印九九乘法表,不显示乘数相等的内容,可以使用标签跳转功能。
tiao:for(int a=1;a<=9;a++){
for(int b=1;b<=a;b++){
if(a==b){
System.out.println("");
continue tiao; //跳转到tiao标签处
}
System.out.print(""+a+"*"+b+"="+(a*b)+"\t");
}
}
}
}
for-each
用于读取数组内容。
public class Main {
public static void main(String []args) {
String[] strs = {"呵呵呵","哈哈哈","嘻嘻嘻"};
for(String str: strs){
System.out.println(str);
}
}
}