• JavaSE | 初识Java(四) | 输入输出


    基本语法
    1. System.out.println(msg); // 输出一个字符串, 带换行
    2. System.out.print(msg); // 输出一个字符串, 不带换行
    3. System.out.printf(format, msg); // 格式化输出
    • println 输出的内容自带 \n, print 不带 \n
    • printf 的格式化输出方式和 C 语言的 printf 是基本一致的

    代码实例

    1. System.out.println("hello world");
    2. int x = 10;
    3. System.out.printf("x = %d\n", x)
    从键盘输入
    使用 Scanner 读取字符串 / 整数 / 浮点数
    1. import java.util.Scanner; // 需要导入 util 包
    2. Scanner sc = new Scanner(System.in);
    3. System.out.println("请输入你的姓名:");
    4. String name = sc.nextLine();
    5. System.out.println("请输入你的年龄:");
    6. int age = sc.nextInt();
    7. System.out.println("请输入你的工资:");
    8. float salary = sc.nextFloat();
    9. System.out.println("你的信息如下:");
    10. System.out.println("姓名: "+name+"\n"+"年龄:"+age+"\n"+"工资:"+salary);
    11. sc.close(); // 注意, 要记得调用关闭方法
    12. // 执行结果
    13. 请输入你的姓名:
    14. 张三
    15. 请输入你的年龄:
    16. 18
    17. 请输入你的工资:
    18. 1000
    19. 你的信息如下:
    20. 姓名: 张三
    21. 年龄:18
    22. 工资:1000.0
    使用 Scanner 循环读取 N 个数字,并求取其平均值
    1. Scanner sc = new Scanner(System.in);
    2. int sum = 0;
    3. int num = 0;
    4. while (sc.hasNextInt()) {
    5. int tmp = sc.nextInt();
    6. sum += tmp;
    7. num++;
    8. }
    9. System.out.println("sum = " + sum);
    10. System.out.println("avg = " + sum / num);
    11. sc.close();
    12. // 执行结果
    13. 10
    14. 40.0
    15. 50.5
    16. ^Z
    17. sum = 150.5
    18. avg = 30.1
    注意事项 : 当循环输入多个数据的时候 , 使用 ctrl + z 来结束输入 (Windows 上使用 ctrl + z, Linux / Mac 上使用 ctrl + d).
    在后续 oj 题当中,遇到 IO 类型的算法题,有各种循环输入的要求,后序给大家介绍。
    猜数字游戏
    参考代码:
    1. import java.util.Random;
    2. import java.util.Scanner;
    3. public class Test {
    4. public static void main(String[] args){
    5. Random random = new Random();
    6. Scanner sc = new Scanner(System.in);
    7. int toGuess = random.nextInt(100);
    8. while(true){
    9. System.out.println("please input your namber:");
    10. int num = sc.nextInt();
    11. if(num < toGuess){
    12. System.out.println("lower");
    13. }else if(num>toGuess){
    14. System.out.println("higher");
    15. }else{
    16. System.out.println("Yes");
    17. break;
    18. }
    19. }
    20. sc.close();
    21. }
    22. }

  • 相关阅读:
    Android学习笔记 2.3.7 时钟(AnalogClock和TextClock)的功能与用法 && 2.3.8 计时器(Chronometer)
    面试字节跳动java岗被算法吊打,60天苦修这些笔记,侥幸收获offer
    【Qt 6】读写剪贴板
    K8S之初入师门第一篇熟读手册
    518. 零钱兑换 II-动态规划算法
    幂等设计详解
    CPP 核心编程8-模板
    程序员基础能力系列(3)——chrome快捷键总结
    m基于Lorenz混沌自同步的混沌数字保密通信系统的FPGA实现,verilog编程实现+MATLAB混沌验证程序
    《Redis设计与实现》笔记
  • 原文地址:https://blog.csdn.net/khh1014173041/article/details/133489799