JAVA语法
(内容参考www.acwing.com学习平台)
1. 基本语法
1.1 内置数据类型
变量 | 字节数 | 举例 |
---|---|---|
byte | 1 | 123(-128~127) |
short | 2 | 12345(-255~254) |
int | 4 | 123456789(-2e31~2e31-1) |
long | 8 | 1234123123L |
float | 4 | 1.2F |
double | 8 | 1.2 1.2D |
Boolean | 1 | true;false |
char | 2 | ‘A’ |
1.2 常量
使用final修饰;
final int N = 123;
1.3 类型转换
- 显式转换(从高精度转换为低精度):
int s = (int)1.33333
- 隐式转换(从低精度转换为高精度):
double y = 4 * 1.1 ;
1.4 表达式
int a = 1, b = 2, c = 3;
int d = (a + b) * c;
d ++;
1.5 输入
方式一:效率较低,输入规模小的时候使用。
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(); //读如下一行
方式二:效率较高,输入规模大时使用,注意需要抛异常。
package com.jyk;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
System.out.println(str);
}
}
1.6 输出
方式一:效率较低,输入规模小的时候使用。
System.out.println("hello world"); //输出字符串,换行
System.out.println(123); //输出整数,换行
System.out.print(3.14159); //输出单精度浮点数
System.out.printf("%.3f %04d", 3.14159, 3); //格式化输出,float与double都用%f输出
方式二:效率较高,输入规模大时使用,注意需要抛异常。
package com.jyk;
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");
bw.flush(); //需要手动刷新缓冲区
}
}
1.7 判断语句
与C++、Python一样
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int year = sc.nextInt();
if (year % 100 == 0) {
if (year % 400 == 0)
System.out.printf("%d是闰年\n", year);
else
System.out.printf("%d不是闰年\n", year);
} else {
if (year % 4 == 0)
System.out.printf("%d是闰年\n", year);