一、Scanner类
创建 Scanner 对象的基本语法:
Scanner s = new Scanner(System.in);
Scanner类是引用数据类型的一种,可以使用该类来完成用户键盘录入,获取到录入的数据。
Scanner使用步骤:
导包:import java.util.Scanner;
创建对象实例:Scanner sc = new Scanner(System.in);
调用方法:
int i = sc.nextInt(); 用来接收控制台录入的数字
String s = sc.next(); 用来接收控制台录入的字符串
例题:
import java.util.Scanner;
public class ScannerDemo01 {
public static void main(String[] args) {
//创建Scanner引用类型的变量
Scanner sc = new Scanner(System.in);
//获取数字
System.out.println("请输入一个数字");
int n = sc.nextInt();
System.out.println("n的值为" + n);
//获取字符串
System.out.println("请输入一个字符串");
String str = sc.next();
System.out.println("str的值为" + str);
}
}
二、Random类
Random也属于引用数据类型。
random() 方法返回随机生成的一个实数,它在[0,1)范围内。
使用方式:
Random使用方式:
import导包:所属包java.util.Random
创建实例格式:Random 变量名 = new Random();
猜数字小游戏
package test6;
import java.util.Random;
import java.util.Scanner;
public class TestRandom {
public static void main(String[] args) {
//使用Scanner和Random完成一个猜数字小游戏,猜1-100之间的数字
Scanner scanner = new Scanner(System.in);
//1.产生一个1-100之间的随机数
Random random = new Random();
//随机100个数字0-99,然后+1 就是1-100
int num = random.nextInt(100)+1;
//定义一个用户用来统计用户猜对用了几次
int count = 0;
//2.不断执行循环,让用户输入要猜的数组并进行大小提示
do{
System.out.println("请输入猜的数字");
int input = scanner.nextInt();
if(input>num){
System.out.println("猜大了");
}else if(input<num){
System.out.println("猜小了");
}else{
System.out.println("恭喜你,猜对了");
break;
}
count++;
}while(true);
//3.结束循环表示用户猜对并提示猜对次数
System.out.println("你猜对了数字"+num+"用了"+count+"次");
}
}
随机点名不重复程序
public static void main(String[] args) {
//使用list集合生成一个随机数组
List<String> list = Arrays.asList("张三","李四","王五");
//把list作为参数重新构建一个新的ArrayList集合
ArrayList<String> names = new ArrayList<>(list);
//使用random生成一个随机
Random random = new Random();
Scanner sc = new Scanner(System.in);
while (true) {
//如果集合没有元素
if (names.size() == 0) {
System.out.println("已抽查完");
break;
}
System.out.println("请输入Y 或者 y");
String input=sc.next();
if (input.equals("Y")||input.equals("y")){
//随机一个集合下标
int index =random.nextInt(names.size());
System.out.println("本次抽到:"+names.get(index));
//该学生已被抽到
names.remove(index);
}else{
System.out.println("本次抽查结束");
break;
}
}
}
ArrayList 类
ArrayList 类是一个可以动态修改的数组,与普通数组的区别就是它是没有固定大小的限制,我们可以添加或删除元素。
ArrayList 继承了 AbstractList ,并实现了 List 接口。
ArrayList定义
ArrayList<Object> array = new ArrayList<Object>();
由此定义了一个存放Object类型的ArrayLIst类,类名为array。
ArrayList的常用方法
add()方法
array.add(Object);
容器类的常用方法通过add()向容器内添加一个对象,参数为添加的对象。这个对象的类型必须为定义时的类型或是其子类型。
size()方法
array.size();
调用这个方法返回值为一个整型,其值为array内包含的对象的个数。
get()方法
array.get(int);
调用这个方法返回一个Object类型的对象,参数为int类型,通过这个参数作为索引访问array内指定的对象
isEmpty()方法
array.isEmpty();
调用此方法返回一个boolean类型的值,判断array是否为空
remove()方法
array.remove(int);调用此方法将int类型的参数作为索引删除array内对应的对象,并将对象作为返回值返回。
这里做了一个简单的记事本程序,用ArrayList类实现,下面是主要的程序代码