问题是随机参数的取值int b=rnd.nextInt(3);为什么取值3呢?不是很明白数组hand不就是0,1,2吗?还有就是比较语句,为什么是c-49呢?不是很明白 希望明白人给解答一下不胜感激。import java.util.*;
import java.io.*;
public class file6
{
public static void main(String[] args)
{
try
{
Random rnd=new Random();
int i=0;
String[] hand={"剪子","锤子","包袱"};
System.out.println("开始游戏了");
System.out.print("剪子(0),锤(1),包袱(2)中,选择哪一个呢?");
int c=System.in.read();
System.out.println("<结果>");
switch(c)
{
case '0':
System.out.println("玩家:"+hand[0]);
break;
case '1':
System.out.println("玩家:"+hand[1]);
break;
case '2':
System.out.println("玩家:"+hand[2]);
break;
}
int b=rnd.nextInt(3);
System.out.println("计算机:"+hand[b]);
if((c-49)>b)
{
System.out.println("玩家胜利!");
System.out.println("比分:1:0");
}
else if((c-49)<b)
{
System.out.println("计算机胜利!");
System.out.println("比分:0:1");
}
else if((c-49)==b)
{
System.out.println("平手!");
System.out.println("比分:0:0");
}
}
catch(Exception e){}
}
}
import java.io.*;
public class file6
{
public static void main(String[] args)
{
try
{
Random rnd=new Random();
int i=0;
String[] hand={"剪子","锤子","包袱"};
System.out.println("开始游戏了");
System.out.print("剪子(0),锤(1),包袱(2)中,选择哪一个呢?");
int c=System.in.read();
System.out.println("<结果>");
switch(c)
{
case '0':
System.out.println("玩家:"+hand[0]);
break;
case '1':
System.out.println("玩家:"+hand[1]);
break;
case '2':
System.out.println("玩家:"+hand[2]);
break;
}
int b=rnd.nextInt(3);
System.out.println("计算机:"+hand[b]);
if((c-49)>b)
{
System.out.println("玩家胜利!");
System.out.println("比分:1:0");
}
else if((c-49)<b)
{
System.out.println("计算机胜利!");
System.out.println("比分:0:1");
}
else if((c-49)==b)
{
System.out.println("平手!");
System.out.println("比分:0:0");
}
}
catch(Exception e){}
}
}
public int nextInt(int n)
返回一个伪随机数,它是从此随机数生成器的序列中取出的、在 0(包括)和指定值(不包括)之间均匀分布的 int值。nextInt 的常规协定是伪随机地生成并返回指定范围中的一个 int 值。所有 n 个可能 int 值的生成概率(大致)相同。Random 类按如下方式实现 nextInt(int n) 方法:
public int nextInt(int n) {
if (n<=0)
throw new IllegalArgumentException("n must be positive"); if ((n & -n) == n) // i.e., n is a power of 2
return (int)((n * (long)next(31)) >> 31); int bits, val;
do {
bits = next(31);
val = bits % n;
} while(bits - val + (n-1) < 0);
return val;
}
前面的描述中使用了不明确的词“大致”,只是因为 next 方法大致为一个单独选择位的公正来源。如果它是一个随机选择位的最佳来源,那么给出的算法应该从起始范围开始完全一致地选择 int 值。 但此算法稍微有些复杂。它拒绝那些会导致不均匀分布的值(由于 2^31 无法被 n 整除)。某个值被拒绝的概率取决于 n。最坏的情况是 n=2^30+1,拒绝的概率是 1/2,循环终止前的预计迭代次数是 2。 此算法特别对待 n 是 2 次幂的情况:它从基础的伪随机数生成器中返回正确的高位数。在不是特殊处理的情况中,将返回正确的低 位数。众所周知,线性同余伪随机数生成器(比如此类所实现的)在其低位的值序列中有 short periods。因此,如果 n 是 2 次幂(幂值较小),则这种特殊情况会导致对此方法的后续调用会返回其长度大大增加的值序列。 参数:
n - 所返回随机数的范围。必须为正数。
返回:
一个伪随机数,处于 0(包括)和 n(包括)之间均匀分布的 int 值。
抛出:
IllegalArgumentException - n 不是正数。======
注意我标红的地方
nextInt(int n)
返回一个伪随机数,它是从此随机数生成器的序列中取出的、在 0(包括)和指定值(不包括)之间均匀分布的 int值。
不明白请看java API文档...
System.out.println(a); 输出为0
你输入的值是字符的0
c-49 system.in.read();读入的是ASCII码值 所以是 -49;
具体 012 我不知到 ASCII码值是多少了;
基本就是这样