Scanner类
Scanner类是引用数据类型的一种,我们可以使用该类来完成用户键盘录入,获取到录入的数据。
Scanner使用步骤:
导包:import java.util.Scanner;
创建对象实例:Scanner sc = new Scanner(System.in);
调用方法:
int i = sc.nextInt(); 用来接收控制台录入的数字
String s = sc.next(); 用来接收控制台录入的字符串
常用的方法:
1.next();--->String
2.nextInt();--->int
3.nextLine();-->String
小结:next()与nextLine的区别:next以空格为分隔符,nextLine是以回车为分隔符
public class ScannerDemo {
public static void main(String[] args) {
test1(); test2(); }
public static void test2() { // 定义一个Scanner对象 Scanner sc = new Scanner(System.in);
System.out.println("请输入数:"); String str1 = sc.nextLine(); String str2 = sc.nextLine(); String str3 = sc.nextLine();
System.out.println("str1==" + str1); System.out.println("str2==" + str2); System.out.println("str3==" + str3); }
public static void test1() { // 定义一个Scanner对象 Scanner sc = new Scanner(System.in);
System.out.println("请输入数:"); String str1 = sc.next(); String str2 = sc.next(); String str3 = sc.next();
System.out.println("str1==" + str1); System.out.println("str2==" + str2); System.out.println("str3==" + str3); }
public static void test() { Scanner sc = new Scanner(System.in); System.out.println("请输入一个int类型的数:");
// 1.用int类型接收 int input = sc.nextInt();// 接收的是int类型 System.out.println("输入第一个String类型的数:"); // 2.用String类型接收 String inputStr = sc.next();// 以String类型 System.out.println("请输入一个float类型的数:"); float fInput = sc.nextFloat(); System.out.println("第一个数:" + input + ",第二个数:" + inputStr + ",第三个数是:" + fInput);
} } |
随机数类Random
这个Random类,它可以产生多种数据类型的随机数,
产生[0,maxValue)范围的随机整数,包含0,不包含maxValue;
方法简介
public int nextInt(int maxValue) 产生[0,maxValue)范围的随机整数,包含0,不包含maxValue;
public double nextDouble() 产生[0,1)范围的随机小数,包含0.0,不包含1.0