java取随机数进行石头剪刀布实例

2023-05-16

实例:用户在界面输入石头剪刀布与系统随机生成随机数(即剪刀石头布)进行比较。

代码:

import java.util.Random;
import java.util.Scanner;
public class Compare {
	public static void main(String[] args){
		while(true){//用于进行未知次数的循环,需要break来跳出
		Scanner in=new Scanner(System.in); 
		System.out.println("请输入您要出的数,石头:0,剪刀:1,布:2");
		int user=in.nextInt();
		Random a=new Random();
		int number=a.nextInt(3);
		switch(user){
		case 0:
		System.out.println("您输入的是石头");
			switch(number){
			case 0:
				System.out.println("系统输入为石头,双方平局"); 
				break;
			case 1:
				System.out.println("系统输入为剪刀,您赢");
				break;
			case 2:
				System.out.println("系统输入为布,系统赢");
				break;											
			}
		break;
		case 1:
			System.out.println("您输入的是剪刀");
			switch(number){
			case 0:
				System.out.println("系统输入为石头,系统赢"); 
				break;
			case 1:
				System.out.println("系统输入为剪刀,双方平局");
				break;
			case 2:
				System.out.println("系统输入为布,您赢");
				break;	
			}
		break;
		case 2:
			System.out.println("您输入的是布");
			switch(number){
			case 0:
				System.out.println("系统输入为石头,您赢"); 
				break;
			case 1:
				System.out.println("系统输入为剪刀,系统赢");
				break;
			case 2:
				System.out.println("系统输入为布,双方平局");
				break;	
			}
		break;
	}
}
}	
}

知识点:

一、nextInt()      next()      nextLine()

nextInt(): it only reads the int value, nextInt() places the cursor in the same line after reading the input.

next(): read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same lineafter reading the input.

nextLine():  reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.

nextInt():

      在读取输入后将光标放在同一行中。 

next():

  • 1、一定要读取到有效字符后才可以结束输入。
  • 2、对输入有效字符之前遇到的空白,next() 方法会自动将其去掉。
  • 3、只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符。
  • next() 不能得到带有空格的字符串。

nextLine():

  • 1、以Enter为结束符,也就是说 nextLine()方法返回的是输入回车之前的所有字符。
  • 2、可以获得空白。

二、Random类

Random类中的常用方法

random类详细介绍https://www.jb51.net/article/83028.htm

a、public boolean nextBoolean()

该方法的作用是生成一个随机的boolean值,生成true和false的值几率相等,也就是都是50%的几率。

b、public double nextDouble()

该方法的作用是生成一个随机的double值,数值介于[0,1.0)之间。

c、public int nextInt()

该方法的作用是生成一个随机的int值,该值介于int的区间,也就是-231到231-1之间。

如果需要生成指定区间的int值,则需要进行一定的数学变换,具体可以参看下面的使用示例中的代码。

d、public int nextInt(int n)

该方法的作用是生成一个随机的int值,该值介于[0,n)的区间,也就是0到n之间的随机int值,包含0而不包含n。

如果想生成指定区间的int值,也需要进行一定的数学变换,具体可以参看下面的使用示例中的代码。

e、public void setSeed(long seed)

该方法的作用是重新设置Random对象中的种子数。设置完种子数以后的Random对象和相同种子数使用new关键字创建出的Random对象相同。

3、Scanner类

参考API中介绍:http://www.runoob.com/manual/jdk1.6/

以下代码使用户能够从 System.in 中读取一个数:

     Scanner in = new Scanner(System.in);
     int user = in.nextInt();

4、while(true)

while(true)退出死循环:https://blog.csdn.net/jdsjlzx/article/details/6652778

 

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

java取随机数进行石头剪刀布实例 的相关文章

随机推荐