1、数据输入
1.1 Scanner类的使用方法
步骤如下:
①导包 import java.util.Scanner;(类上面)
②创建对象 Scanner scanner = new Scanner(System.in); scanner 是一个变量,可以自己任意定义
③接收数据 int i = scanner.nextInt(); i 是一个变量,可以自己任意定义
代码实例:
输入三个人的身高,用程序求出三个人身高中最高的那个人。
public class Demo01 {
public static void main(String[] args) {
//创建对象
Scanner scanner = new Scanner(System.in);
System.out.print("身高a:\t");
//接收数据
int a = scanner.nextInt();
System.out.print("身高b:\t");
//接收数据
int b = scanner.nextInt();
System.out.print("身高c:\t");
//接收数据
int c = scanner.nextInt();
//三目运算
int j = a > b ? (a > c ? a : c) : (b > c ? b : c);
//输出结果
System.out.print("身高最高:\t"+j);
}
}
运行结果:
身高a: 167
身高b: 184
身高c: 173
身高最高: 184
猜数字小游戏:
程序自动生成1-100之间的一个随机数,使用程序猜出这个数字。
需求分析:
1、如果用户猜的数字大于随机数,提示你猜的数字太大了
2、如果用户猜的数字小于随机数,提示你猜的数字太小了
3、如果用户猜的数字等于随机数,提示你猜对了
public class Demo01 {
public static void main(String[] args) {
/**
* 随机数
* */
//首先,定义一个随机数
Random random = new Random();
int number = random.nextInt(100) + 1;
//使用程序,输入数据来猜数字
Scanner scanner = new Scanner(System.in);
boolean b = true;
while (b) {
System.out.println("请输入你要猜的数字:");
int guessNumber = scanner.nextInt();
//进行数字的比较
if (guessNumber > number) {
System.out.println("你猜的数字太大了");
} else if (guessNumber < number) {
System.out.println("你猜的数字太小了");
} else {
System.out.println("你猜对了");
b = false;
}
}
}
}
请输入你要猜的数字:
40
你猜的数字太大了
请输入你要猜的数字:
38
你猜的数字太小了
请输入你要猜的数字:
39
你猜对了
2、什么是Random类
Random类用来生成伪随机数。
例如:
public class Demo01 {
public static void main(String[] args) {
//定义一个随机数
Random r = new Random();
int i = r.nextInt();
System.out.println("随机数为:\t" + i);
}
}
1.1 Random使用步骤
使用方式和之前学习的Scanner使用方式基本相同
1、导包 java.util.Random
例如:import java.util.Random;
2、使用Random random =new Random();声明一个Random对象
3、int number = random.nextInt();
注意事项:
想要生成一个区间[0,100),可以使用
int number = random.nextInt(100);
代码实例:
public class Demo01 {
public static void main(String[] args) {
//定义一个随机数
Random r = new Random();
//100以内随机数
int i = r.nextInt(100);
System.out.println("100以内随机数为:\t" + i);
//100到200之间的随机数
int j = r.nextInt(100) + 100;
System.out.println();
System.out.println("[100,200)以内随机数为:\t" + j);
}
}
运行结果:
100以内随机数为: 19
[100,200)以内随机数为: 163