文章目录
- 1.条件
- 1.条件语句思路:
- 2.代码
- 3.原理
- 2.循环
- 1.条件语句思路:
- 2.代码
- 3.原理
1.条件
1.条件语句思路:
在Java中,我们可以使用条件分支语句来进行选择,
当程序走到条件语句时,根据条件来判断该走哪条路。
2.代码
import java.util.Scanner;
public class tiaoJian {
public static void main(String[] args) {
System.out.print("please input your money:");
Scanner sc=new Scanner(System.in);
double money= sc.nextDouble();//获取钱数
double price1=1000;//物品1价格
double price2=500;//物品2价格
if(money>(price1+price2)) {
System.out.println("You can buy one and two.");
}
else if(money>price1){
System.out.println("You can buy one or two.");
}
else if(money>price2){
System.out.println("You can buy two.");
}
else{
System.out.println("You can't buy anyone.");
}
System.out.print("please input the number:");
int n=sc.nextInt();
switch (n){
case 1:
System.out.println("星期一");
break;
case 2:
System.out.println("星期二");
break;
case 3:
System.out.println("星期三");
break;
case 4:
System.out.println("星期四");
break;
case 5:
System.out.println("星期五");
break;
case 6:
System.out.println("星期六");
break;
case 7:
System.out.println("星期七");
break;
default:
System.out.println("输入不正确");
break;
}
System.out.print("please input the number:");
int m= sc.nextInt();
switch (m) {
case 1, 2, 3 -> System.out.println("第一季度");
case 4, 5, 6 -> System.out.println("第二季度");
case 7, 8, 9 -> System.out.println("第三季度");
case 10, 11, 12 -> System.out.println("第四季度");
default -> System.out.println("输入不正确");
}
}
}
3.原理
if(条件1){
语句1
}
else if(条件2){
语句2
}
else{
语句3
}
满足哪个条件时进入哪个循环语句,如果都不满足则进入else语句。
switch (n){
case x:
语句1
break;
case y:
语句2
break;
default
语句3
break;
}
switch语句称为开关语句,最前面输入n;如果n和某个case后面的值相等,则执行那个case后面的语句,如果都不相等,则执行default后面的语句。
在每个case后面都要加一个break来结束开关,如果没有则直接执行下一个case。
2.循环
1.条件语句思路:
在Java中,我们可以使用循环语句来进行对某一段代码的循环,
如果我们出现重复代码,我们可以使用循环
2.代码
public class XunHuan {
public static void main(String[] args) {
System.out.println("--------while--------");
int i=0;
int s=0;
while(i<=10){
s=s+i;
i++;
System.out.print(s+" ");
}
System.out.println("\n"+s);
System.out.println("---------for---------");
int n=0;
for(int m=0;m<=10;m++)
{
n+=m;
System.out.print(n+" ");
}
System.out.println("\n"+n);
System.out.println("------do···while-----");
int x=0;
int y=0;
do{
x=x+y;
y++;
System.out.print(x+" ");
}while (y<=10);
System.out.println("\n"+x);
}
}
3.原理
while(条件){
循环体
}
使用while循环时,当条件满足时进入循环体,如果条件不满足则跳出循环。
在while中是先判断语句,然后进入循环体,当循环次数不确定时可以使用while循环语句。
for(语句1;语句2;语句3){
循环体
}
在for循环中,先赋值语句1,再看是否满足语句2,如果满足,就进入循环体,如果不满足,则跳出循环,再对语句3进行自加或自减。
在循环次数明确的情况下可以使用for循环。
do{
循环体
}while(条件)
使用do while循环时,当条件满足时进入循环体,如果条件不满足则跳出循环。
在while中是先执行一次循环体.然后进行语句的判断,当循环次数不确定时可以使用do while循环语句。