流程控制
Scanner对象
next()和nextLine()方法
顺序结构
选择结构
单选择结构
双选择结构
多选择结构
嵌套
switch多选择结构
break:防止case穿透
了解IDEA反编码
package struct;
import java.util.Scanner;
public class SwitchSelect {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入");
String score = scanner.next();
switch (score){
case "a":
System.out.println("a");
break;
case "b":
System.out.println("b");
break;
case "c":
System.out.println("c");
break;
default:
System.out.println("错误");
}
scanner.close();
}
}
循环结构
while循环
public class WhileCycle {
public static void main(String[] args) {
//计算1-100的和
int i = 0;
int total = 0;
while(i<100){
i++;
total += i;
}
System.out.println("总和是:"+total);
}
}
do-while循环
public class DoWhileCycle {
public static void main(String[] args) {
//计算1-100的和
int i = 0;
int total = 0;
do {
i++;
total += i;
}while (i<100);
System.out.println("总和是:"+ total);
}
}
for循环
public class ForCycle {
//计算1-100的和
public static void main(String[] args) {
int total = 0;
for(int i=0; i <= 100; i++){
total += i;
}
System.out.println("和是:"+ total);
}
}
//test1
public class CycleTest01 {
public static void main(String[] args) {
//0-100奇数的和
int sum1 = 0;
for(int i = 1; i <= 100; i+=2){
sum1 += i;
}
System.out.println("奇数的和为:"+sum1);
//0-100偶数的和
int sum2 = 0;
for(int a = 2; a <= 100; a+=2){
sum2 += a;
}
System.out.println("偶数的和为:"+sum2);
//方法二
int oddSum = 0;
int evenSum = 0;
for (int i = 0; i <= 100; i++) {
if(i % 2 == 0){
evenSum += i;
}else {
oddSum += i;
}
}
System.out.println("奇数和为"+ oddSum +"偶数和为"+ evenSum);
}
}
//test2 1-1000之间能被5整除的数,每行输出3个
public class CycleTest02 {
//1-1000之间能被5整除的数,每行输出3个
public static void main(String[] args) {
for (int i = 1; i <= 1000; i++) {
if(i%5 == 0){
System.out.print(i + "\t");
}
if (i%15 == 0){
System.out.println();
}
}
}
}
//test3 九九乘法表
public class CycleTest03 {
public static void main(String[] args) {
//九九乘法表
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循环
break、continue
public class GotoLable {
public static void main(String[] args) {
//101-150的质数
int count = 1;
//了解,尽量不使用
outer:for (int i = 101; i <= 150; i++) {
for(int j = 2; j<i/2; j++)
if(i % j == 0){
continue outer;
}
System.out.print(i+"\t");
}
}
}
practice
public class CycleTest04 {
public static void main(String[] args) {
//打印三角形
for (int i = 1; i <= 5; i++) {
for (int j = 5; j >= i; j--) {
System.out.print(" ");
}
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
for (int j = 1; j < i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}