--- title: "00-变量、运算符、输入与输出" created: 2025-12-02 tags: - 项目 aliases: - 变量、运算符、输入与输出 --- # 变量、运算符、输入与输出 类似于C#,Java的所有变量和函数都要定义在class中。 ## 内置数据类型 | | | | | --- | --- | --- | | 类型 | 字节数 | 举例 | | byte | 1 | 123 | | short | 2 | 12345 | | int | 4 | 123456789 | | long | 8 | 1234567891011L | | float | 4 | 1.2F | | double | 8 | 1.2, 1.2D | | boolean | 1 | true, false | | char | 2 | ‘A’ | ## 常量 使用final修饰:(相当于const) ```java final int N = 110; ``` ## 类型转化 显示转化:int x = (int)'A'; 隐式转化:double x = 12, y = 4 \* 3.3; ## 表达式 与C++、Python3类似: ```java int a = 1, b = 2, c = 3; int x = (a + b) * c; x ++; ``` ## 输入 方式1,效率较低,输入规模较小时使用。 ```java Scanner sc = new Scanner(System.in); String str = sc.next(); // 读入下一个字符串 int x = sc.nextInt(); // 读入下一个整数 float y = sc.nextFloat(); // 读入下一个单精度浮点数 double z = sc.nextDouble(); // 读入下一个双精度浮点数 String line = sc.nextLine(); // 读入下一行 ``` 方式2,效率较高,输入规模较大时使用。注意需要抛异常。 ```java package com.yxc; import java.io.BufferedReader; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = br.readLine(); System.out.println(str); } } ``` ## 输出 方式1,效率较低,输出规模较小时使用。 ```java System.out.println(123); // 输出整数 + 换行 System.out.println("Hello World"); // 输出字符串 + 换行 System.out.print(123); // 输出整数 System.out.print("yxc\n"); // 输出字符串 System.out.printf("%04d %.2f\n", 4, 123.456D); // 格式化输出,float与double都用%f输出 ``` 方式2,效率较高,输出规模较大时使用。注意需要抛异常。 ```java package com.yxc; import java.io.BufferedWriter; import java.io.OutputStreamWriter; public class Main { public static void main(String[] args) throws Exception { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); bw.write("Hello World\n"); bw.flush(); // 需要手动刷新缓冲区 } } ``` ## 练习题 [[01-A+B|A+B]] [[03-差|差]] [[02-两点间的距离|两点间的距离]] [[05-钞票|钞票]] [[04-时间转换|时间转换]] --- **项目分区导航**: [[00-java语法|java语法]] ⬅️ | 00-变量、运算符、输入与输出 | ➡️ [[01-A+B|A+B]]