Java
变量、运算符、表达式、输入输出
变量类型
类型 | 字节数 | 举例 |
---|---|---|
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’ |
ASCII: ‘a’= 97 ‘A’ = 65 ‘0’ = 48
final = C/C++中的const
- final int N = 10;
类型强制转换
- 显示转换:
int x = (int) 'A';
- 隐式转换:
double x = 12,y = 4 * 3.3
- 隐式转换是小类型转大类型,而显式转换可以大转小
运算符同C语言
C/Java中的除是向0取整,而python是向下取整
浮点数相等判断?
if (Math.abs(x - y) < 1e-8)
常用tips:double精度问题,在涉及double的精度问题中,常用将其加上一个eps来保证结果的正确性——https://www.acwing.com/activity/content/problem/content/7533/
输入输出
小范围输入1e5
import java.util.Scanner;
public class Main {
public static void main (String[] args) throws Exception {
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();//读入下一行
}
}
输入单个字符:
char ch = sc.next().charAt(0)
大范围输入:注意抛异常
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);
}
}
BufferedReader只能读一行字符串,如果想读一行中空格分开的多个整数
String[] str = br.readLine().split(" "); int x = Integer.parseInt(str[0]); int y = Integer.parseInt(str[1]);
小范围输出
public class Main {
public static void main(String[] args) throws Exception {
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输出
}
}
System.out.printf()
- int:%d
- float:%f:默认保留6位
- double:%f:默认保留6位
- char:%c
- String:%s
println
public class Main { public static void main(String[] args) { int a = 1; int b = a ++ ; System.out.println(a + " " + b); int c = ++ a; System.out.println(a + " " + c); } }
output:
2 1
3 3
如何输出%? 在输出的时候写%%即可
大范围输出
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(); // 需要手动刷新缓冲区 warning
}
}