加载中...

流程控制

  • 用户交互

基本语法如下:
Scanner s = new Scanner(System.in);
通过Scanner的next()和nextLine()方法获取输入的字符串,在读取前,我们需要使用hasNext()和hasNextLine()方法来判断是否还有输入的数据。

next() :
1、一定要读取到有效字符后才会结束输入;
2、对输入有效字符之前遇到的空白,next()会将其自动去掉;
3、只有输入有效字符后,next()才会将字符后输入的空白作为分隔符或者结束符;
4、next()不能得到带有空格的完整字符串。
nextLine():
1、以Enter键为结束符,nextLine()返回的是按回车键之前输入的全部字符;
2、可以获取到空白。

  • if else语句
    if 语句至多有 1 个 else 语句,else 语句在所有 else if 语句之后。

if 语句可以有若干个 else if 语句,它们必须在 else 语句之前(else在最后)。

一旦其中一个 else if 语句检测为true,其他的 else if 以及 else 语句都将跳过执行。
`public class IfDemo03 {
public static void main(String[] args) {
//考试分数大于60分数就是及格,小于60分数就是不及格。
Scanner scanner = new Scanner(System.in);
System.out.println("请输入成绩: ");
int score = scanner.nextInt();

if (score==100){

System.out.println("满分");

}else if (score<100 && score>=90){

System.out.println("A级");

}else if (score<90 && score>=80){

System.out.println("B级");

}else if (score<80 && score>=70){

System.out.println("C级");

}else if (score<70 && score>=60){

System.out.println("D级");

}else if (score<60 && score>=0){

System.out.println("不及格");

}else {undefined

System.out.println("成绩不合法");

}

scanner.close();

}

}

  • switch多选择结构
  1. 支持字符

循环结构

while 循环
do...while循环
for循环
主要用于数组的增强型for循环

while循环

do...while循环


for循环


1.奇数和偶数和

1.for输出1000内的能被5(可改其他)整除的数,每行输出三个(可改其他五个十个)

`package struct;

public class Demo09 {
public static void main(String[] args) {
//练习2:用for循环输出1-1000之间能被5整除的数,并且每行输出3个

    for (int i = 0; i <= 1000; i++) {
        if (i%5 == 0){
            System.out.print(i+"\t");
        }
        if (i%(5*3)==0){
            System.out.println();
        }

    }
}

}
`

  1. 注意拆分的思想,大问题划小问题

    `public class jiu {
    public static void main(String[] args) {
    for (int i=1;i<=9;i++){
    for (int j=1;j<i+1;j++){
    System.out.print(i+""+j+"="+(ji)+"\t" +
    "");
    }
    System.out.println();
    }

    }
    }
    `
    强型for循环

posted @ 2022-04-02 00:27  神乐羊  阅读(49)  评论(0)    收藏  举报