一、Scanner类:获取键盘输入
基本语法:Scanner s = new Scanner(System.in);
前提:导包语句,import java.util.Scanner;
import java.util.Scanner;
public class Demo01ScannerSum {
public static void main(String[] args) {
//从键盘接收数据
Scanner sc = new Scanner(System.in);
System.out.println("请输入第一个参数:");
int a = sc.nextInt();
System.out.println("请输入第二个参数:");
int b = sc.nextInt();
int sum = a + b;
System.out.println("两个参数的和是:" + sum);
System.out.println("请输入一个字符串:");
String str = sc.next();
System.out.println("输入的字符串是" + str);
}
}
二、Random类
import java.util.Random;
/*
Random类用来生成随机int数字(有正有负)
导包;
创建;
使用;
int num = r.nextInt();
int num = r.nextInt(数值);控制取值范围,左闭右开区间
*/
public class Demo01Random {
public static void main(String[] args) {
Random r = new Random();
int num = r.nextInt();
System.out.println("随机生成的数字:" + num);
int num2 = r.nextInt(10);//取值范围为0-9
System.out.println(num2);
}
}