Java的变量类分成8个基本类:
- byte 8位数
使用2^8 ,限制为-128 到 127 (2^8-1)
- short 短数字 (16位数) 限制为 -32768 到 32767(2^16-1)
- int Integer的缩减(32位数)java默认正数字
- long 长数字(64位数)使用时用“数字L”来区分
- float (32位数漂浮符号)使用时用“数字f”格式来区分
- double (64位数漂浮符号)java默认漂浮号
- char 字符 (0~65535)16位数UTF
- boolean(真假)- 只能是true 或 false
public class TypeExamples {
public static void main(String[] args) {
System.out.println("Examples of whole number literals");
System.out.println("The min and max of the byte type is " + Byte.MIN_VALUE
+ " and " + Byte.MAX_VALUE);
System.out.println("The min and max of the short type is " + Short.MIN_VALUE
+ " and " + Short.MAX_VALUE);
System.out.println("The min and max of the int type is " + Integer.MIN_VALUE
+ " and " + Integer.MAX_VALUE);
System.out.println("The min and max of the long type is " + Long.MIN_VALUE
+ " and " + Long.MAX_VALUE);
System.out.println("\nExamples of decimal number literals");
System.out.println("The min and max of the float type is " + Float.MIN_VALUE
+ " and " + Float.MAX_VALUE);
System.out.println("The min and max of the double type is " + Double.MIN_VALUE
+ " and " + Double.MAX_VALUE);
System.out.println("\nSometimes Float and Double have different calculations");
System.out.println("Example below is area calculations with float and double");
}
}
备注:和钱有关的数据不建议使用double或者float,因为运算时容易漏数据。Java自带的BigDecimal更合适。
Scanner最常用是和System.in配合读取输入的数据,可以分各种类。比如有
Scanner.next() - 存储的是String,都可以接受
Scanner.nextBoolean() - 接受的只有true和false
Scanner.nextFloat() - 接受和存储的是float
Scanner.nextDouble() - 接受和存储的是double
Scanner.nextInt() - 接受和存储的是int
Scanner.nextByte() - 接受和储存的是byte
可以发现是没有专门储存char的公式,也就意味着像储存char必须使用string后转换。
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
// no char input for scanner
Scanner input = new Scanner(System.in);
System.out.print("Please input your age: ");
int age = input.nextInt();
System.out.println("My age is: " + age);
}
}