• (Java)程序逻辑控制


    switch语句

    不能做switch参数的类型是Long , boolean , float, double

    输入输出

    输出到工作台

    System.out.println(10);
    System.out.print("不换行");
    System.out.printf("%s","格式化输出");
    
    • 1
    • 2
    • 3
    10
    不换行格式化输出
    
    • 1
    • 2

    使用scanner读取

    在这里插入图片描述

    在这里插入图片描述

    在这里插入图片描述

    结论:在输入不同类型的数据时,先处理字符串类型的,字符串中有空格的使用nextLine;

    System.out.println("请输入你的年龄");
    int age= scan.nextInt();
    System.out.println("年龄: "+age);
    System.out.println("请输入你的工资");
    float money=scan.nextFloat();
    System.out.println("工资: "+money);
    scan.close();
    //Scanner工具,使用完要关闭
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    循环输入

    Scanner scan=new Scanner(System.in);
    while(scan.hasNextInt()){
    System.out.println("请输入你的年龄");
    int age= scan.nextInt();
    System.out.println("年龄: "+age);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    4
    请输入你的年龄
    年龄: 4
    5
    请输入你的年龄
    年龄: 5
    ^D
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    idea上结束循环:ctrl+D
    在cmd命令行窗口结束使用:ctrl+z
    
    • 1
    • 2

    猜数字游戏

    生成随机数

    Random random=new Random();
    int n= random.nextInt(100)+1;//[1,101)
    System.out.println(n);
    //根据当前的时间来生成随机数,时间一直在变所以是生成随机数
    
    • 1
    • 2
    • 3
    • 4

    如果想生成一个固定的数字

    Random random=new Random(132);
    //132是一个固定的数,所以根据132也一直生成一个固定的数
    
    • 1
    • 2

    Math.random
    产生一个[0,1)之间的随机数
    Math.random()(n-m)+m;
    double a=Math.random()
    (3-1)+1,设置一个随机1到3的变量。

    猜数字小游戏
    import java.util.Random;
    import java.util.Scanner;
    public class Test {
        public static void main(String[] args) {
            Random random = new Random();
            int n = random.nextInt(100);
            System.out.println("随机数 "+n);
            Scanner scan = new Scanner(System.in);
            while (true) {
                System.out.println("请输入一个数字:");
                int x = scan.nextInt();
                if (x > n) {
                    System.out.println("猜大了");
                } else if (x < n) {
                    System.out.println("猜小了");
                } else {
                    System.out.println("猜对了");
                    break;
                }
            }
            scan.close();
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
  • 相关阅读:
    Python爬虫——爬取近3个月绵阳市降水量数据源
    前端JavaScript中常见设计模式
    Flutter笔记:聊一聊依赖注入(上)
    DOM系列之 click 延时解决方案
    No.7软件需求规格说明书及UML
    activiti-api-impl
    安卓讲课笔记5.5 Fragment入门
    SpringBoot - WebMvcConfigurer的作用是什么?
    Hadoop3教程(八):MapReduce中的序列化概述
    安装前期开发的环境
  • 原文地址:https://blog.csdn.net/qq_63983125/article/details/126038456