一程序执行顺序
程序中最经典的三种执行顺序:
1.1分支结构:
1.1.1if分支
if格式:
案例
类型一:
if(条件表达式){
代码;
}
public class if_demo {
public static void main(String[] arg)
{
int age = 19;
if(age>=18)
{
System.out.println("可以上网吧");
}
}
}
类型二:
double money = 13.0;
if(money<10) {
System.out.println("钱发不出去");
}
else{
System.out.println("支付金额"+money);
}
类型三:
Scanner SC = new Scanner(System.in);
double score =SC.nextDouble();
if (score >= 90){
System.out.println("评级:A");
}
else if(score >= 80 ) {
System.out.println("评级:B");
} else if (score >= 70) {
System.out.println("评级:C");
} else if (score >= 0) {
System.out.println("评级:D");
} else {
System.out.println("输入错误!");
}
1.1.2 switch
switc格式:
switch案例:
package d2.branch;
import java.util.Scanner;
public class switch_demo {
public static void main(String[] args) {
Scanner Sc=new Scanner(System.in);
String week = Sc.next();
switch (week) {
case "周一":
System.out.println("学习第一天");
break;
case "周二":
System.out.println("学习第二天");
break;
case "周三":
System.out.println("学习第三天");
break;
case "周四":
System.out.println("学习第四天");
break;
case "周五":
System.out.println("学习第五天");
break;
case "周六":
System.out.println("放假第1天");
break;
case "周日":
System.out.println("放假第2天");
break;
default:
System.out.println("输入错误");
}
}
}
if与switch区别:
switch穿透性:
1.2循环结构
for循环格式:
在执行的时候先进性判断然后在执行,在执行的时候循环次数确定。
for(初始值;条件表达式;步进语句){
循环体1;
}
for例子:
一百以内奇数偶数求和,并打印出相应数字:
package d2.loop;
public class fordemo {
public static void main(String[] args) {
String even="偶数:0";
String odd = "奇数:1";
int evenadd=0;
int oddadd=1;
for(int i=2;i<=100;i++){
if(i%2==0)
{
even=even + "+" + i;
evenadd+=i;
}
else {
odd=odd + "+" + i;
oddadd=oddadd+i;
}
}
System.out.println(even + "="+evenadd);
System.out.println(odd+"="+oddadd);
}
}
while循环
循环格式:
循环例子:
for与while区别
do while循环:
循环格式:
特点:先执行在判断。
死循环:
关键字:
Random随机数:
导包代码 import java.util.Random;
作用:生成随机数。
注意是生成括号里面是n则生成(0~n-1)的数据
package d2.loop;
import java.util.Random;
public class randomdemo {
public static void main(String[] args) {
Random random = new Random();
for(int i=0;i<10;i++)
{
int c= random.nextInt(5);
System.out.println(c);
}
}
}
或者限制范围,注意不包含20;