Java基础:变量、运算符、表达式、IO

Java

变量、运算符、表达式、输入输出

变量类型

类型字节数举例
byte1123
short212345
int4123456789
long81234567891011L
float41.2F
double81.2,1.2D
boolean1true\false
char2‘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
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值