2019-10-20-23:13:52
目录内容:
1.Scanner类
2.匿名对象
3.Random类
4.对象数组
Scanner类
功能:实现键盘输入数据到程序中
使用步骤:
1.导包:
import 包路径.类名称;
如果需要使用的目标类和当前类位于同一个包下,可以省略导包
只有java.lang包下的内容不需要导包,其他包都需要import语句
2.创建方法:
类名称 对象名 = new 类名称();
3.使用方法:
对象名.成员方法名()
package demoscanner;
import java.util.Scanner;
public class ScannerPra01 {
public static void main(String[] args) {
//2.创建方法
Scanner input = new Scanner(System.in);//System.in表示从键盘进行输入
System.out.print(“请输入内容:”);
//3.获取键盘输入的内容
int sc = input.nextInt();//输入的内容类型是int类型
//4.打印输入的内容
System.out.println(“输入的内容是:”+sc);
}
}
匿名对象的使用:
匿名对象的创建:
new 类名称();
注意事项:匿名对象只能使用唯一的一次,下次再次使用就得重新创建一个新对象
使用建议:如果确定有一个对象只需要使用唯一的一次,就可以用匿名对象
Random类
功能:生成随机数字
导包和创建同Scanner类一样
使用方法:
1.获取一个随机的int数字(范围是int所有范围,有正负两种): int num = sc.nextInt()
2.获取一个随机的int数字(参数代表了范围,左闭右开): int num = sc.nextInt(3)([0,3))
import java.util.Random;
public class RandomPra01 {
public static void main(String[] args) {
//创建
Random input = new Random();
//遍历随机生成的五个0-10的数字
for (int i = 0; i < 5; i++) {
int number = input.nextInt(11);
System.out.println(number);//打印随机生成的数字
}
}
}
对象数组:
数组有一个缺点:一旦创建,则在程序运行中不可改变
package demoobjectarray;
public class ObjectArrayPra01 {
public static void main(String[] args) {
//创建一个长度为3的数组,用来存放person类对象
Person[] array = new Person[3];
//创建三个实例对象
Person one = new Person("迪丽热巴",24);
Person two = new Person("古力娜扎",25);
Person three = new Person("欧阳娜娜",20);
//将实例对象放进数组中
array[0] = one;
array[1] = two;
array[2] = three;
//打印输出内容
System.out.println(array[1].getName()+"="+array[1].getAge());
}
}