• 廖雪峰Java1-3流程控制-1输入输出


    1.输入

    • 导入java.util.Scanner
    • 创建Scanner对象并传入System.in
    • 使用Scanner.nextLine()读取用户输入的字符串
    • Scanner.nextInt()读取用户输入的整数
    import java.util.Scanner;
    public class Hello {
        public static void main(String[] args){
            Scanner scanner = new Scanner(System.in);
            System.out.println("Input your name:");
            String name = scanner.nextLine();
            System.out.println("Input your age:");
            int age = scanner.nextInt();
            System.out.println("hi, "+ name + ", you are "+age);
          }
    }
    

    2.输出

            System.out.println("输出换行");
            System.out.print("输出但不换行");
    

    格式化输出

    用作短信模版,或控制字符格式使数据更易读。

    • System.out.printf()
    • 使用占位符%xxx
    • 常用的占位符
      |%d 整数|%x 十六进制整数|%f 浮点数|%% %字符本身|
      |--------|---------------|---------|-------------|
            double d = 3.1415926;
            System.out.println(d);
            System.out.printf("PI = %.2f
    ", d);//保留2位小数点
            System.out.printf("PI = %7.2f
    ", d);//一共7位
            System.out.printf("%s is %d years old
    ","Bob",12);
            double f = 0.123456;
            System.out.printf("%f
    ", f);
            System.out.printf("%e
    ", f);//科学计数法表示小数
            System.out.printf("%.2f
    ", f);
            System.out.printf("%6.2f
    ", f);
            System.out.printf("%+.2f
    ", f);//打印符号位
            //调整参数顺序
            System.out.printf("%s %s %s 
    ", "A", "B", "C");
            System.out.printf("%2$s %1$s %1$s %3$s
    ", "A", "B", "C");//1$s表示第一个参数
            //System.out.printf("%s %s","hello");//参数可以多,但不能少。少了会报异常java.util.MissingFormatArgumentException
    

    搜索Format String Syntax,即可找到更多参数说明。https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html

    总结

    • 输出换行println()/不换行print()/格式化输出printf()
    • 输入nextLine() extInt() extDouble()...
  • 相关阅读:
    网络请求与远程资源
    JavaScript对象
    微信小程序抓包Charles
    归并排序
    顺序表
    后缀表达式
    中缀表达
    ES6 Promise
    Es 方法
    10.26学习
  • 原文地址:https://www.cnblogs.com/csj2018/p/10251915.html
Copyright © 2020-2023  润新知