Java的两个类库
输入
如何实现键盘输入?我们需要了解到Scanner这个类,其作用于及键盘输入。
类库:java.util
如何使用?分为3步走:
- 导入包(一般idea会帮做)
import java.util.Scanner;
- 创建对象
Scanner scanner = new Scanner(System.in);
- 使用对象
scanner.next(); // 用户输入字符串
scanner.nextInt(); // 用户输入数字
随机数
如果要在我们指定范围内随机生成一个整数,那么我们可以使用Random这个类
类库:java.util
使用方式与输入基本一致,但我们需要注意一下使用其生成随机数时的问题:
- 在指定范围内随机一个数:
nextInt(int bound) -> 在0-(bound-1)
nextInt(10) -> 0-9
- 在1-10之间随机一个数: nextInt(10)+1 -> (0-9)+1 -> 1-10
- 在1-100之间随机一个数:nextInt(100)+1 -> (0-99)+1 -> 1-100
- 在100-999之间随机一个数: nextInt(900)+100 -> (0-899)+100 -> 100-999
例子
输入–
1.
// 包
import java.util.Scanner;
public class Demo03 {
public static void main(String[] args) {
System.out.println("程序开始");
// 得到键盘输入类
Scanner scanner = new Scanner(System.in);
// 等着用户输入一个数字
int a = scanner.nextInt();
String b = scanner.next();
System.out.println(a);
System.out.println(b);
System.out.println("程序结束");
}
}
import java.util.Scanner;
public class Demo03 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入你的第一个数:");
int a = scanner.nextInt();
System.out.println("请输入你的第二个数:");
int b = scanner.nextInt();
System.out.println("两束之和为:" + (a + b));
}
}
3.用户输入两个数,求和
import java.util.Scanner;
public class Demo04 {
public static void main(String[] args) {
// 2. 创建这个对象
Scanner scanner = new Scanner(System.in);
// 输入一个数字,判断奇偶性
System.out.println("请输入一个整数");
int a = scanner.nextInt();
System.out.println(a % 2 == 0 ? "偶数" : "奇数");
}
}
随机数–
import java.util.Random;
public class Demo04 {
public static void main(String[] args) {
// 1.得到一个生成随机数的对象
Random random = new Random();
// 2.使用对象
int i = random.nextInt();
// 3. 生成一定范围的随机数
int i1 = random.nextInt(10);
System.out.println(i1);
}
}