第七话-流程控制
作者:互联网
scanner用户交互
代码DEMO
package com.xie.base;
import java.util.Scanner;
public class Demo02 {
public static void main(String[] args) {
//创建扫描器对象,用于接收键盘数据
Scanner scanner = new Scanner(System.in);
int sum = 0;
int count = 0;
while(scanner.hasNextInt()){
int x = scanner.nextInt();
sum = sum + x;
count++;
}
System.out.println(count + "个数的和为" + sum);
System.out.println(count + "个数的平均值为" + sum/count);
//所有IO流的类,都需要关闭,如果不关闭会占用资源。
scanner.close();
}
}
注意:
next():只获取空格前的字符串
nextLine():Enter前包括空格都会获取(用的多)
选择结构
-
if单选择结构
-
if双选择结构
-
if多选择结构
-
嵌套的if结构
代码demo
package com.xie.base; import java.util.Scanner; public class Demo04if { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("请输入分数"); int score = scanner.nextInt(); if(score>=80){ System.out.println("优秀"); }else if(score>=60){ System.out.println("及格"); }else if(score>=0 && score<60){ System.out.println("不及格"); }else{ System.out.println("分数不合法"); } scanner.close(); } }
-
switch多选择结构
package com.xie.base;
public class Demo05switch {
public static void main(String[] args) {
String name = "xie";
//case穿透,第一个匹配上之后,如果没有break,后面的内容都会执行。加上break才能跳出。
switch (name){
case "xie":
System.out.println("xie");
break; //可选
case "zhang":
System.out.println("zhang");
break;
default:
System.out.println("未匹配");
}
}
}
反编译
File-->Project Structure-->Project-->Project compiler output:
以上可以找到IDEA的class文件位置。
复制class文件
粘贴到java文件目录(在IDEA的包内不允许粘贴class)
循环结构
while循环
package com.xie.base;
public class Demo06while {
public static void main(String[] args) {
int i = 0;
int sum = 0;
while(i<100){
i++;
sum+=i;
}
System.out.println(sum);
}
}
do...while循环
相对于while,至少能执行一次。
package com.xie.base;
public class Demo07dowhile {
public static void main(String[] args) {
int i = 0;
do {
System.out.println(i);
}while(i<0);
System.out.println("---");
while (i<0){
System.out.println(i);
}
}
}
for循环
package com.xie.base;
public class Demo08for {
public static void main(String[] args) {
int sum1 = 0;
int sum2 = 0;
for (int i = 0; i < 100; i++) {
if(i%2!=0){
sum1+=i;
}else{
sum2+=i;
}
}
System.out.println(sum1);
System.out.println(sum2);
//九九乘法表
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(i + "*" + j + "=" + (i*j) + "\t");
}
System.out.println();
}
}
}
增强for循环
package com.xie.base;
public class Demo09for2 {
public static void main(String[] args) {
int[] nums = {10,20,30};
for(int num:nums){
System.out.println(num);
}
}
}
break-continue
标签:控制,第七,int,流程,System,xie,println,public,out 来源: https://www.cnblogs.com/xiexieyc/p/16120791.html