java控制流
if语句:这个没什么好讲的
if else if,else,在编写代码的时候有些可以使用三元运算符进行代码的简化
int temp = 32;
if (temp > 30) {
System.out.println("It's a hot day");
}
else if (temp > 20 && temp <= 30){
System.out.println("Beautiful day");
}
else
System.out.println("Cold day");
在这段代码中,可以简化的,在else if的条件中简写为 temp > 20即可,以及这个部分的条件判断可以不必带上大括号{},
switch-case语句
我觉得学过C的应该理解这些比较通顺,举个例子:
String role = "admin";
switch (role) {
case "admin":
System.out.println("You're an admin!");
break;
case "moderator":
System.out.println("You're a moderator");
break;
default:
System.out.println("You're a guest");
}
for循环:
for (int i = 5; i > 0; i--)
System.out.println("Hello World " + i);
while循环:
int i = 5;
while (i > 0) {
System.out.println("Hello World " + i);
i--;
}
for循环和while循环相比,在执行相同流程的时候,for更加简便,for循环适合已知循环几次,
do-while循环:
至少执行一次
while和do-while日常使用相比,用while的比较多
do {
System.out.print("Input: ");
input = scanner.next().toLowerCase();
System.out.println(input);
}while (!input.equals("quit"));
for-each
String[] fruits = {"Apple", "Mango", "Orange"};
for (String fruit : fruits)
System.out.println(fruit);