逻辑控制(Java)

【本节目标】

1. Java中程序的逻辑控制语句
2. Java中的输入输出方式
3. 完成猜数字游戏


1.顺序结构


顺序结构比较简单,按照代码书写的顺序一行一行执行。 

System.out.println("aaa");
System.out.println("bbb");
System.out.println("ccc");

/ 运行结果
aaa
bbb
ccc

如果调整代码的书写顺序, 则执行顺序也发生变化

System.out.println("aaa");
System.out.println("ccc");
System.out.println("bbb");

/ 运行结果
aaa
ccc
bbb

2. 分支结构(选择语句)


2.1 if 语句

1. 语法格式1 

if(布尔表达式){
  /语句
} 

如果布尔表达式结果为true,执行if中的语句,否则不执行。

比如:小明,如果这次考试考到90分或以上,给你奖励一个鸡腿。

int score = 92;
if(score >= 90){
  System.out.println("吃个大鸡腿!!!");
} 

2. 语法格式2

if(布尔表达式){
  / 语句1
}else{
  / 语句2
}

 如果布尔表达式结果为true,则执行if中语句,否则执行else中语句。

比如:小明,如果这次考到90分以上,给你奖励一个大鸡腿,否则奖你一个大嘴巴子。

int score = 92;
if(score >= 90){
  System.out.println("吃个大鸡腿!!!");
}else{
  System.out.println("挨大嘴巴子!!!");
}

3. 语法格式3

if(布尔表达式1){
  / 语句1
}else if(布尔表达式2){
  / 语句2
}else{
  / 语句3
}

表达式1成立,执行语句1,否则表达式2成立,执行语句2,否则执行语句3

比如:考虑到学生自尊,不公开分数排名,因此:

  • 分数在 [90, 100] 之间的,为优秀
  • 分数在 [80, 90) 之前的,为良好
  • 分数在 [70, 80) 之间的,为中等
  • 分数在 [60, 70) 之间的,为及格
  • 分数在 [ 0, 60) 之间的,为不及格
  • 错误数据

按照上述办法通知学生成绩。

public class Test {
    public static void main(String[] args) {
        int score=80;
        if(score >= 90){
            System.out.println("优秀");
        }else if(score >= 80 && score < 90){
            System.out.println("良好");
        }else if(score >= 70 && score < 80){
            System.out.println("中等");
        }else if(score >= 60 && score < 70){
            System.out.println("及格");
        }else if(score >= 0 && score < 60){
            System.out.println("不及格");
        }else{
            System.out.println("错误数据");
        }
    }
}

 练习:

1. 判断一个数字是奇数还是偶数

public class Test {
    public static void main(String[] args) {
        int num = 10;
        if (num % 2 == 0)
        {
        System.out.println("num 是偶数");
        }
        else
        {
            System.out.println("num 是奇数");
        }
    }
}

2. 判断一个数字是正数,负数,还是零

public class Test {
    public static void main(String[] args) {
        int num = 10;
        if (num > 0) {
           System.out.println("正数");
        } else if (num < 0) {
          System.out.println("负数");
        } else {
          System.out.println("0");
        }
    }
}

3. 判断一个年份是否为闰年

public class Test {
    public static void main(String[] args) {
        int year = 2000;
        if (year % 100 == 0) {
            // 判定世纪闰年
            if (year % 400 == 0) {
                System.out.println("是闰年");
            } else {
                System.out.println("不是闰年");
            }
        } else {
            // 普通闰年
            if (year % 4 == 0) {
                System.out.println("是闰年");
            } else {
                System.out.println("不是闰年");
            }
        }
    }
}
import java.util.Scanner;
public class Test {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int year = scanner.nextInt();
        if (year % 100 == 0) {
            // 判定世纪闰年
            if (year % 400 == 0) {
                System.out.println("是闰年");
            } else {
                System.out.println("不是闰年");
            }
        } else {
            // 普通闰年
            if (year % 4 == 0) {
                System.out.println("是闰年");
            } else {
                System.out.println("不是闰年");
            }
        }
    }
}







上面这个代码和c语言中scanf一样,都要从键盘中输入


import java.util.Scanner;//导包

Scanner scanner = new Scanner(System.in);
        int year = scanner.nextInt();

【注意事项】

1.代码风格

/ 风格1-----> 推荐
int x = 10;
if (x == 10) {
  / 语句1
} else {
  / 语句2
}









/ 风格2
int x = 10;
if (x == 10)
{
  / 语句1
}
else
{
  / 语句2
}

 虽然两种方式都是合法的, 但是 Java 中更推荐使用风格1, { 放在 if / else 同一行. 代码跟紧凑。

2.分号问题

int x = 20;
if (x == 10);
{
  System.out.println("hehe");
}


/ 运行结果
hehe

 此处多写了一个 分号, 导致分号成为了 if 语句的语句体, 而 { } 中的代码已经成为了和一个 if 无关   的代码块.

3.悬垂 else 问题

int x = 10;
int y = 10;
if (x == 10)
if (y == 10)
System.out.println("aaa");
else
System.out.println("bbb");



这里和c语言一样,else一定跟最近的if去匹配


2.2 switch 语句


基本语法

switch(表达式){
case 常量值1:{
语句1;
[break;]
}
case 常量值2:{
语句2;
[break;]
}
...
default:{
内容都不满足时执行语句;
[break;]
}
}

 执行流程:

1. 先计算表达式的值
2. 和case依次比较,一旦有响应的匹配就执行该项下的语句,直到遇到break时结束
3. 当表达式的值没有与所列项匹配时,执行default

代码示例: 根据 day 的值输出星期 

public class Test {
    public static void main(String[] args) {
        int day = 1;
        switch(day) {
            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;
        }
    }
}

【注意事项】

1.多个case后的常量值不可以重复
2.switch的括号内只能是以下类型的表达式:

       1.基本类型:byte、char、short、int,注意不能是long类型,float,                                                  double,boolean

       2.引用类型:String常量串、枚举类型

public class Test {
    public static void main(String[] args) {
        double num = 1.0;
        switch(num) {
            case 1.0:
                System.out.println("hehe");
                break;
            case 2.0:
                System.out.println("haha");
                break;
        }
    }
}

3.break 不要遗漏, 否则会失去 "多分支选择" 的效果

int day = 1;
switch(day) {
  case 1:
    System.out.println("星期一");
    // break;
  case 2:
    System.out.println("星期二");
    break;
}


/ 运行结果
星期一
星期二

 4.switch 不能表达复杂的条件

/ 例如: 如果 num 的值在 10 到 20 之间, 就打印 hehe
/ 这样的代码使用 if 很容易表达, 但是使用 switch 就无法表示.


if (num > 10 && num < 20) {
System.out.println("hehe");
}

5.switch 虽然支持嵌套, 但是很丑,一般不推荐~

public class Test {
    public static void main(String[] args) {
        int x = 1;
        int y = 1;
        switch(x) {
            case 1:
                switch(y) {
                    case 1:
                        System.out.println("hehe");
                        break;
                }
                    break;
                    case 2:
                        System.out.println("haha");
                        break;
                }
    }
}

代码的美观程度也是一个重要的标准. 毕竟这是看脸的世界.

综上, 我们发现, switch 的使用局限性是比较大的。


3. 循环结构


3.1 while 循环

基本语法格式: 

while(循环条件(布尔表达式)){
循环语句;
}

 循环条件为 true, 则执行循环语句; 否则结束循环.

代码示例1: 打印 1 - 10 的数字

public class Test {
    public static void main(String[] args) {
        int num = 1;
        while (num <= 10) {
            System.out.println(num);
        }
    }
}
如果是上面这个代码的话会死循环,应该像下面这么写









public class Test {
    public static void main(String[] args) {
        int num = 1;
        while (num <= 10) {
            System.out.println(num);
            num++;
        }
    }
}

代码示例2: 计算 1 - 100 的和

public class Test {
    public static void main(String[] args) {
        int n = 1;
        int result = 0;
        while (n <= 100) {
            result += n;
            n++;
        }
        System.out.println(result);
    }
}




 执行结果
5050

代码示例3: 计算 5 的阶乘

public class Test {
    public static void main(String[] args) {
        int n = 1;
        int result = 1;
        while (n <= 5) {
            result *= n;
            n++;
        }
        System.out.println(result);
    }
}



执行结果
120

代码示例4: 计算 1! + 2! + 3! + 4! + 5!

public class Test {
    public static void main(String[] args) {
        int i = 1;
        int sum = 0;
         // 外层循环负责求阶乘的和
        while (i <= 5) {
            int n= 1;
            int ret = 1;
           // 里层循环负责完成求阶乘的细节.
            while (n <= i) {
                ret *= n;
                n++;
            }
            sum += ret;
            i++;
        }
        System.out.println("sum = " + sum);
    }
}





另一种写法:
public class Test {
    public static void main(String[] args) {
        int n=1;
        int ret=1;
        int sum=0;
        while(n<=5) {
            ret *=n;
            n++;
            sum+=ret;
        }
        System.out.println(sum);
    }
}

执行结果
153

这里我们发现, 当一个代码中带有多重循环的时候, 代码的复杂程度就大大提高了. 而比较复杂的代码就更容易出错.后面我们会采用更简单的办法来解决这个问题.

注意事项:

1. 和 if 类似, while 下面的语句可以不写 { } , 但是不写的时候只能支持一条语句. 建议还是加上 { }
2. 和 if 类似, while 后面的 { 建议和 while 写在同一行.
3. 和 if 类似, while 后面不要多写 分号, 否则可能导致循环不能正确执行.

int num = 1;
while (num <= 10); {
  System.out.println(num);
  num++;
}


 执行结果
[无任何输出, 程序死循环]

此时 ; 为 while 的语句体(这是一个空语句), 实际的 { } 部分和循环无关. 此时循环条件 num <= 10 恒成立, 导致代码死循环了.

3.1.1 break

break 的功能是让循环提前结束.

代码示例: 找到 100 - 200 中第一个 3 的倍数 

public class Test {
    public static void main(String[] args) {
        int num = 100;
        while (num <= 200) {
            if (num % 3 == 0) {
                System.out.println("找到了 3 的倍数, 为:" + num);
                break;
            }
            num++;
        }
    }
}



执行结果
找到了 3 的倍数, 为:102







调试看回放2.33.29

执行到 break 就会让循环结束.

3..1.2 continue

continue 的功能是跳过这次循环, 立即进入下次循环.

代码示例: 找到 100 - 200 中所有 3 的倍数 

public class Test {
    public static void main(String[] args) {
        int num = 100;
        while (num <= 200) {
            if (num % 3 != 0) {
                num++; / 这里的 ++ 不要忘记! 否则会死循环.
                continue;
            }
            System.out.println("找到了 3 的倍数, 为:" + num);
            num++;
        }
    }
}





找到了 3 的倍数, 为:102
找到了 3 的倍数, 为:105
找到了 3 的倍数, 为:108
找到了 3 的倍数, 为:111
找到了 3 的倍数, 为:114
找到了 3 的倍数, 为:117
找到了 3 的倍数, 为:120
找到了 3 的倍数, 为:123
找到了 3 的倍数, 为:126
找到了 3 的倍数, 为:129
找到了 3 的倍数, 为:132
找到了 3 的倍数, 为:135
找到了 3 的倍数, 为:138
找到了 3 的倍数, 为:141
找到了 3 的倍数, 为:144
找到了 3 的倍数, 为:147
找到了 3 的倍数, 为:150
找到了 3 的倍数, 为:153
找到了 3 的倍数, 为:156
找到了 3 的倍数, 为:159
找到了 3 的倍数, 为:162
找到了 3 的倍数, 为:165
找到了 3 的倍数, 为:168
找到了 3 的倍数, 为:171
找到了 3 的倍数, 为:174
找到了 3 的倍数, 为:177
找到了 3 的倍数, 为:180
找到了 3 的倍数, 为:183
找到了 3 的倍数, 为:186
找到了 3 的倍数, 为:189
找到了 3 的倍数, 为:192
找到了 3 的倍数, 为:195
找到了 3 的倍数, 为:198

执行到 continue 语句的时候, 就会立刻进入下次循环(判定循环条件), 从而不会执行到下方的打印语句.

找到1-100之间,既能被3整除,也能被5整除的所有数据



public class Test {
    public static void main(String[] args) {
     int i=1;
     while(i<=100) {
         if(i%15 !=0) {
             i++;
             continue;
         }
         System.out.println(i);
         i++;
     }

    }
}


3.2 for 循环

【基本语法】 

for(表达式①;布尔表达式②;表达式③){
表达式④;
}
  • 表达式1: 用于初始化循环变量初始值设置,在循环最开始时执行,且只执行一次
  • 表达式2: 循环条件,满则循环继续,否则循环结束
  • 表达式3: 循环变量更新方式

【执行过程】 

①②③④--->②③④--->②③④--->②③④--->②③④--->②③④--->...--->②为false,循环结束。

【代码示例】 

1. 打印 1 - 10 的数字

public class Test {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            System.out.println(i);
        }
    }
}

2. 计算 1 - 100 的和

public class Test {
    public static void main(String[] args) {
        int sum = 0;
        for (int i = 1; i <= 100; i++) {
            sum += i;
        }
        System.out.println("sum = " + sum);
    }
}



执行结果
5050

3. 计算 5 的阶乘

public class Test {
    public static void main(String[] args) {
        int result = 1;
        for (int i = 1; i <= 5; i++) {
            result *= i;
        }
        System.out.println("result = " + result);
    }
}



执行结果
120

4. 计算 1! + 2! + 3! + 4! + 5!

public class Test {
    public static void main(String[] args) {
        int sum = 0;
        for (int i = 1; i <= 5; i++) {
            int tmp = 1;
            for (int j = 1; j <= i; j++) {
                tmp *= j;
            }
            sum += tmp;
        }
        System.out.println("sum = " + sum);
    }
}





执行结果
153

【注意事项】 (和while循环类似)

1. 和 if 类似, for 下面的语句可以不写 { } , 但是不写的时候只能支持一条语句. 建议还是加上 { }
2. 和 if 类似, for 后面的 { 建议和 while 写在同一行.
3. 和 if 类似, for 后面不要多写 分号, 否则可能导致循环不能正确执行.
4. 和while循环一样,结束单趟循环用continue,结束整个循环用break

3.3.do while 循环(选学(基本不怎么使用))

do{
循环语句;
}while(循环条件);

 先执行循环语句, 再判定循环条件,循环条件成立则继续执行,否则循环结束。

例如:打印 1 - 10

public class Test {
    public static void main(String[] args) {
        int num = 1;
        do {
            System.out.println(num);
            num++;
        } while (num <= 10);


    }
}

【注意事项】

1. do while 循环最后的分号不要忘记
2. 一般 do while 很少用到, 更推荐使用 for 和 while. 


4. 输入输出


4.1 输出到控制台

基本语法

三种输出方式:

System.out.println(msg);       / 输出一个字符串, 且换行

System.out.print(msg);        / 输出一个字符串, 不换行
System.out.printf(format, msg); / 格式化输出

1.println 输出的内容自带 \n, print 不带 \n
2.printf 的格式化输出方式和 C 语言的 printf 是基本一致的.

格式化字符串

 这个表格没必要记住, 用到的时候根据需要查一下就行了.

4.2 从键盘输入

使用 Scanner 读取字符串/整数/浮点数 

import java.util.Scanner;  // 需要导入 util 包


其中System.in指从就按盘获取



scanner.nextLine():输入一个字符串
scanner.nextInt():输入一个整形
scanner.nextFloat():输入一个浮点数




...scanner.nextLine()  包含空格(比如输入gao bo,他打印gao bo)
...scanner.next()   不包含空格(比如输入gao bo,他打印gao)







String name = sc.nextLine()==String name = scanner.nextLine()



Scanner sc = new Scanner(System.in);

System.out.println("请输入你的姓名:");
String name = scanner.nextLine();//输入一个字符串
System.out.println(name);

System.out.println("请输入你的年龄:");
int age = scanner.nextInt();
System.out.println(age);

System.out.println("请输入你的工资:");
float salary = scanner.nextFloat();
System.out.println(salary);
sc.close() //这个是调用关闭的方法








如果先输年龄再输姓名,我们发现,输完年龄之后,不等你输入姓名就已经执行完了,为什么呢?因为当你输完年龄之后有个回车,他把回车当姓名输进去了,这里处理这种情况只能在年龄之后多加scanner.nextLine().
如下:

System.out.println("请输入你的年龄:");
int age = scanner.nextInt();
System.out.println(age);

scanner.nextLine();

System.out.println("请输入你的姓名:");
String name = scanner.nextLine();
System.out.println(name);

System.out.println("请输入你的工资:");
float salary = scanner.nextFloat();
System.out.println(salary);










// 执行结果
请输入你的姓名:
张三
请输入你的年龄:
18
请输入你的工资:
1000
你的信息如下:
姓名: 张三
年龄:18
工资:1000.0

 使用 Scanner 循环读取 N 个数字,并求取其平均值

sc.hasNextInt():判断当前的标记或者实判断接下来的输入是否为int



Scanner sc = new Scanner(System.in);
int sum = 0;
int num = 0;
while (sc.hasNextInt()) {
  int tmp = sc.nextInt();
  sum += tmp;
  num++;
}
System.out.println("sum = " + sum);
System.out.println("avg = " + sum / num);
sc.close();



// 执行结果
10
40.0
50.5
^Z
sum = 150.5
avg = 30.1








读一个整形:
import java.util.Scanner;
public class Test {
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        while(scanner.hasNextInt()) {
            int a=scanner.nextInt();
            System.out.println(a);
        }
    }
}







读一个字符串:
import java.util.Scanner;
public class Test {
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        while(scanner.hasNextLine()) {
            String a=scanner.nextLine();
            System.out.println(a);
        }
    }
}

注意事项: 当循环输入多个数据的时候, 使用 ctrl + z 来结束输入 (Windows 上使用 ctrl + z, Linux / Mac 上使用 ctrl+ d).

在后续oj题当中,遇到IO类型的算法题,有各种循环输入的要求,后序给大家介绍。


5. 猜数字游戏


游戏规则:

系统自动生成一个随机整数(1-100), 然后由用户输入一个猜测的数字. 如果输入的数字比该随机数小, 提示 "低了", 如果输入的数字比该随机数大, 提示 "高了" , 如果输入的数字和随机数相等, 则提示 "猜对了" . 

代码如下:

1.首先,我们要让电脑随机生成一个数字,他需要一个工具Random,
它的使用:
Random random = new Random();
int randNum = random.nextInt(100);/他会生成0-100之间的随机数,但是不包含100
2.接下来要猜这个数字








import java.util.Random;
import java.util.Scanner;
public class Test {
    public static void main(String[] args) {
        Random random = new Random();
        int randNum = random.nextInt(100);//[0-100)+1     [0-101)
       // System.out.println("生成的随机数字:" + randNum);/这个是生成的随机数

        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("请输入你要猜的数字:");
            int num = scanner.nextInt();
            if (num > randNum) {
                System.out.println("猜大了!");
            } else if (num == randNum) {
                System.out.println("猜对了!");
                break;
            } else {
                System.out.println("猜小了!");
            }
        }
    }
}













那能不能生成固定的随机数呢?看代码

public class Test {
    public static void main(String[] args) {
       /这里给了123之后,他每次根据123生成随机数
        Random random = new Random(123);
        int randNum = random.nextInt(100);//[0-100)+1     [0-101)
       // System.out.println("生成的随机数字:" + randNum);/这个是生成的随机数

        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("请输入你要猜的数字:");
            int num = scanner.nextInt();
            if (num > randNum) {
                System.out.println("猜大了!");
            } else if (num == randNum) {
                System.out.println("猜对了!");
                break;
            } else {
                System.out.println("猜小了!");
            }
        }
    }
}


6. 练习


1. 输出 1000 - 2000 之间所有的闰年
2. 求出0~999之间的所有“水仙花数”并输出。(“水仙花数”是指一个三位数,其各位数字的立方和确好等于该数本身,如: 153=1^3+5^3+3^3 ,则153是一个“水仙花数”。)

public class Test {
    public static void main(String[] args) {
        /怎么知道他又几位数呢?比如153,因为他是十进制的数字,每次给他除10,一直除到0
            /153 = 1^3 + 5^3 + 3^3
            for (int i = 0; i < 999999; i++) {
                /1.第一步,看他有多少位数
                int count = 0;//计算当前i 有几位数
                int tmp = i;
                while (tmp != 0) {
                    count++;
                    tmp = tmp / 10;//让新的i除以10
                    /这里用tmp代替了i,因为i最后肯定为0,但是下面还要用,所以要代替
                }
                //count的值是多少已经计算完成   i还是没有变的
                /2.接下来计算i[tmp]的每一位
                tmp = i;
                int sum = 0;
                while (tmp != 0) {
                    sum += Math.pow(tmp%10,count);//假如:Math.pow(2,3),就是2的3次方
                    tmp /= 10;
                }
                if(sum == i) {
                    System.out.println(i);
                }
            }
        }
    }













执行结果:
0
1
2
3
4
5
6
7
8
9
153
370
371
407
1634
8208
9474
54748
92727
93084
548834


3. 写一个函数返回参数二进制中 1 的个数,比如: 15 0000 1111 4 个 1

public class Test {
    public static void main(String[] args) {
        int n = 7;
        int count = 0;
        while (n != 0) {
            count++;
            n = n & (n - 1);
        }
        System.out.println(count);
    }
}


4. 获取一个数二进制序列中所有的偶数位和奇数位,分别输出二进制序列。

奇数偶数自己定


public class Test {
    public static void main(String[] args) {
        int n = 7;
        for (int i = 31; i >= 0; i -= 2) {
            System.out.print(((n >>> i) & 1) + " ");
        }
        System.out.println();
        for (int i = 30; i >= 0; i -= 2) {
            System.out.print(((n >>> i) & 1) + " ");
        }
    }
}






printf(换行)
println(不换行)





执行结果:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1


5. 完成猜数字游戏


7.作业


1.作业标题(1664)

数字9 出现的次数

作业内容

编写程序数一下 1到 100 的所有整数中出现多少个数字9

import java.util.Scanner;

/1-100之间包含多少个9

public class Test {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();//100
        int count = 0;
        for (int i = 1; i <= n; i++) {
            if(i / 10 == 9) {//十位上的9
                count++;
            } if(i % 10 == 9) {//个位上的9
                count++;
            }
        }
        System.out.println(count);
    }
}

执行结果:20










/1-100之间多少个数字包含9

public class Test {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();//100
        int count = 0;
        for (int i = 1; i <= n; i++) {
            if(i / 10 == 9) {
                count++;
            }else if(i % 10 == 9) {//选择,选择了if就没有选择else if
                count++;
            }
        }
        System.out.println(count);
    }
}

执行结果:19

2.作业标题(1659)

判定素数

作业内容

给定一个数字,判定一个数字是否是素数

/判断素数
1.
public class Test {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();

        for (int k = 1; k <= n ; k++) {
            int i = 2;
            for (; i < k; i++) {
                if(k % i == 0) {
                    //System.out.println(i+"不是素数!");
                    break;
                }
            }
            if(i == k) {
                System.out.println(k+"是素数");
            }
        }
    }
    }


            //这段代码只判断一个数字是不是素数
            int i = 2;
            for (; i < k; i++) {
                if(k % i == 0) {
                    //System.out.println(i+"不是素数!");
                    break;
                }
            }
            if(i == k) {
                System.out.println(k+"是素数");
            }










2.优化
public class Test {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();

        for (int k = 1; k <= n ; k++) {
            int i = 2;
            for (; i <= k/2; i++) {
                if(k % i == 0) {
                    //System.out.println(i+"不是素数!");
                    break;
                }
            }
            if(i > k/2) {
                System.out.println(k+"是素数");
            }
        }
    }
    }













3.优化

public class Test {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();

        for (int k = 1; k <= n; k++) {
            int i = 2;
            for (; i <= Math.sqrt(k); i++) {//Math.sqrt(k)就是给k开根号
                if (k % i == 0) {
                    //System.out.println(i+"不是素数!");
                    break;
                }
            }
            if (i > Math.sqrt(k)) {
                System.out.println(k + "是素数");
            }
        }
    }
}

 3.作业标题(1666)

求2个整数的最大公约数

作业内容

给定两个数,求这两个数的最大公约数

例如:

输入:20 40

输出:20

求两个数的最大公约数(辗转相除法)

 比如24 18,先让24除18,商1余6,再让18除6,商3余0,此时6就是最大公约数



public class Test {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int a = scanner.nextInt();
        int b = scanner.nextInt();
        int c = a % b;
        while (c != 0) {
            a = b;  //让b等于原来的a,c等于原来的b
            b = c;
            c = a % b;
        }
        System.out.println(b);
    }
}

 4.作业标题(1667)

计算分数的值

作业内容

计算1/1-1/2+1/3-1/4+1/5 …… + 1/99 - 1/100 的值 。

public class Test {
    public static void main(String[] args) {
        double sum = 0;
        int flg = 1;
        for (int i = 1; i <= 100; i++) {
            sum = sum + 1.0 / i * flg;
            flg = -flg;
        }
        System.out.println(sum);
    }
}

 5.作业标题(2088)

打印 X 图形

作业内容

描述

KiKi学习了循环,BoBo老师给他出了一系列打印图案的练习,该任务是打印用“*”组成的X形图案。

输入描述:

多组输入,一个整数(2~20),表示输出的行数,也表示组成“X”的反斜线和正斜线的长度。

输出描述:

针对每行输入,输出用“*”组成的X形图案。

示例1

输入:

5

复制输出:

*   *
 * * 
  *  
 * * 
*   *

复制

示例2

输入:

6

复制输出:

*    *
 *  * 
  **  
  **  
 *  * 
*    *
public class Test {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextInt()) { / 注意 while 处理多个 case
            int a = in.nextInt();
            for (int i = 0; i < a; i++) {

                for (int j = 0; j < a; j++) {
                    if (i == j || (i + j) == a - 1) {
                        System.out.print("*");
                    } else {
                        System.out.print(" ");
                    }
                }
                System.out.println();
            }
        }
    }
}

 6.作业标题(1676)

模拟登陆

作业内容

编写代码模拟三次密码输入的场景。 最多能输入三次密码,密码正确,提示“登录成功”,密码错误, 可以重新输 入,最多输入三次。三次均错,则提示退出程序

import java.util.Scanner;
public class Test {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int count = 3;
        while (count != 0) {
            System.out.println("请输入你的密码,你还有 " + count + " 次机会!");
            String password = in.nextLine();
            if (password.equals("1234")) {
                System.out.println("登录成功!");
                break;
            } else {
                System.out.println("密码错误!");
                count--;
            }
        }
    }
}

 7.作业标题(1674)

输出乘法口诀表

作业内容

输出n*n的乘法口诀表,n由用户输入。

非n*n乘法口诀
public class Test {
    public static void main(String[] args) {
      int i=0;
      for(i=0;i<=9;i++) {
          int j=0;
          for(j=0;j<=i;j++) {
              System.out.printf("%d*%d=%2d ",i,j,i*j);
          }
          System.out.println();
      }
    }
}














public class Test {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= i; j++) {
                //System.out.print(i+"*"+j +" = "+i*j+" ");
                System.out.print("\t" + j + "*" + i + " = " + j * i + " ");
            }
            System.out.println();
        }
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值