从用户输入“输入玩家年龄”的行时出错

时间:2016-03-09 17:02:27

标签: java

这是我的错误消息:

Exception in thread "main" java.lang.IllegalArgumentException: bound must be positive
    at java.util.Random.nextInt(Random.java:388)
    at playertest.Player.<init>(Player.java:39)
    at playertest.Playertest.main(Playertest.java:35)

我的代码:

import java.util.Random;
public class Player {

private int id;
private String name;
private boolean insured;
private String gender;
private int age=1;

private int luckynumber;

Player(int id)
{
    Random rnd=new Random();
    this.id=id;
    luckynumber=rnd.nextInt(50-101);

}
Player(int id,String name,boolean insured,String gender,int age)
{
    Random rnd=new Random();
    this.id=id;
    this.name=name;
    this.insured=insured;
    this.gender=gender;
    this.age=age;

    luckynumber=rnd.nextInt(50-101);



}
void setid(int Id)
{
    this.id=Id;
}
int getid()
{
    return id;
}
void setname(String name)
{
    this.name=name;
}
String getname()
{
    return name;
}
void setage(int age)
{
    this.age=age;
}
int getage()
{
    return age;
}
int getluckynumber()
{
    return luckynumber;
}
int changeluckynumber()
{
    Random rnd=new Random();
    this.luckynumber=rnd.nextInt(50-101);
    return luckynumber;
}
}

import java.util.Scanner;

public class Playertest {

public static void main(String[] args) {


    Scanner input=new Scanner(System.in);
    System.out.println("Enter id of player");
    int id=input.nextInt();
    System.out.println("Enter name of player");
    String name=input.next();
    System.out.println("Is player insured?");
    boolean insured=input.nextBoolean();
    System.out.println("Enter gender of player");
    String gender=input.next();
    System.out.println("Enter age of player");
    ***int age=input.nextInt();***


    Player ob=new Player(id,name,insured,gender,age);
    ob.setid(id);
    ob.setage(age);
    ob.setname(name);

    System.out.println("ID :"+ob.getid()+" Name :"+ob.getname()+" Age :"+ob.getage()+" Lucky number :"+ob.getluckynumber());
    System.out.println("New lucky number is :"+ob.changeluckynumber());


}

}

1 个答案:

答案 0 :(得分:1)

如错误所述:

  

绑定必须是正面的

你对绑定使用了什么?:

rnd.nextInt(50-101)

-51不是正数。

根据the documentation,这种方法:

  

从此随机数生成器的序列中返回一个伪随机,均匀分布的int值,介于0(包括)和指定值(不包括)之间。

您是否尝试在 50和101之间生成一个随机数?这可能看起来像这样:

rnd.nextInt(51) + 50