Java中含有一下8种基本数据类型
数据类型 | 关键字 | 在内存中占用的字节数 | 取值范围 | 默认值 |
---|---|---|---|---|
布尔型 | boolean | 1个字节(8位) | true,false | false |
字节型 | byte | 1个字节(8位) | -128 ~ 127 | 0 |
字符型 | char | 2个字节(16位) | 0 ~ 216-1 | ‘\u0000’ |
短整型 | short | 2个字节(16位) | -215 ~ 215-1 | 0 |
整型 | int | 4个字节(32位) | -231 ~ 231-1 | 0 |
长整型 | long | 8个字节(64位) | -263 ~ 263-1 | 0 |
单精度浮点型 | float | 4个字节(32位) | 1.4013E-45 ~ 3.4028E+38 | 0.0F |
双精度浮点型 | double | 8个字节(64位) | 4.9E-324 ~ 1.7977E+308 | 0.0D |
其中byte,short,int,long类型都是整数类型,并且都是有符号整型
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a;
byte b;
long c;
short d;
a = in.nextInt();
b = in.nextByte();
c = in.nextLong();
d = in.nextShort();
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
in.close();
}
}
单个字符的输入方法
import java.text.DecimalFormat;//方法一
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char x;
x = in.next().charAt(0);
System.out.println(x);
in.close();
}
}
import java.text.DecimalFormat;//方法二,读入字符串的第一个字符
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s;
s = in.nextLine()
char x = s.charAt(0);
System.out.println(x);
in.close();
}
}
double,float类型如何保留小数点后几位
方法一:实例化DecimalFormat类,这种方法不会四舍五入
import java.text.DecimalFormat;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
DecimalFormat df = new DecimalFormat("#.000");//有几个0就保留几位小数
float a;
double b;
a = in.nextFloat();
b = in.nextDouble();
System.out.println(df.format(a));
System.out.println(df.format(b));
in.close();
}
}
方法二:
import java.math.BigDecimal;
public class Test {
public static void main(String[] args) {
double data = 3.02;
//利用字符串格式化的方式实现四舍五入,保留1位小数
String result1 = String.format("%.1f",data);
//1代表小数点后面的位数, 不足补0。f代表数据是浮点类型。保留2位小数就是“%.2f”。
System.out.println(result1);//输出3.0
//利用BigDecimal来实现四舍五入.保留一位小数
double result2 = new BigDecimal(data).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
//1代表保留1位小数,保留两位小数就是2
//BigDecimal.ROUND_HALF_UP 代表使用四舍五入的方式
System.out.println(result2);//输出3.0
}
}