我是Java课程的新手,我正在努力学习一门课程。该计划应该模拟乌龟和野兔之间的比赛。每个都有基于随机生成的数字的各种动作(在赛车板上移动的方式)。我在生成随机数时遇到问题。以下是我的错误消息。任何人都可以帮我修复错误信息问题吗?此外,如果您在我的代码中看到任何需要修复或其他任何内容的其他内容,我们将非常感谢您的帮助。谢谢,这里是带有以下错误消息的代码。附:我使用蓝色J来编写和编译我的代码:
import java.util.Random;
class Race
{
int [] race = new int[70];
int tortoise;
int hare;
Random randomGenerator = new Random();
public boolean again = true;
public void StartRace()
{
tortoise = 1;
hare = 1;
System.out.println("AND THEY'RE OFF!!!!");
while (tortoise < 70 && hare < 70)
{
MoveHare();
MoveTortoise();
DisplayCurrentLocation();
String request;
} //end while
if
(tortoise > hare)
{
System.out.println("\n TORTOISE WINS!!");
}
else if
(hare > tortoise)
{
System.out.println("\n HARE WINS!!!");
}
else if
(hare == tortoise)
{
System.out.println("TIE!!!");
}
}
public void MoveTortoise()
{
int n = randomGenerator.next(1, 10);
//fast plod
if ( n <= 5)
tortoise += 3;
//slip
else if (n == 9 || n == 10)
tortoise -= 6;
//slow plod
else if (n == 6 || n == 7 || n == 8)
++tortoise;
// protect from going past start
if (tortoise < 1)
tortoise = 1;
// to make sure game ends
else if (tortoise > 70)
tortoise = 70;
}// end tortoise
public void MoveHare()
{
// randomize move
int percent = randomGenerator.Next(1, 10);
// determine moves by graph
//big hop
if (percent == 1 || percent == 2)
hare += 9;
//big slip
else if (percent == 6)
hare -= 12;
// small hop
else if (percent == 3 || percent == 5)
++hare;
// )small slip
else if (percent == 7 || percent == 8)
hare -= 2;
else if (percent == 9 || percent == 10)
hare += 0;
//ensure hare doesn't go past start
if (hare < 1)
hare = 1;
// ensure hare doesnt go past end
else if (hare > 70)
hare = 70;
} // end movehare
public void DisplayCurrentLocation()
{
//this is the location of each on the array
for (int count = 1; count <= 70; count++)
// same spot
if (count ==tortoise && count ==hare)
{
System.out.println("OUCH");
}
else if (count == hare)
{
System.out.println("H");
}
else if (count == tortoise)
{
System.out.println("T");
}
else
System.out.println();
}
public class RaceTest
{
public static void main ( String[] args)
{
Race Application = new Race();
string request;
do
{
Application.StartRace();
System.out.println ("");
System.out.println("Do you want to Play again y/n");
request = Console.ReadKey();
if (request == "Y" || request == "y")
{
again = true;
}
else
{
again = false;
}
}
while (again == true);
System.out.println("Thank you for Playing");
}
}
}
错误消息:类java.util.random中的下一个方法不能应用于给定的类型; required:int,found:int,int;原因:实际和正式的参数列表长度不同
感谢所有帮助。
答案 0 :(得分:1)
有几个问题。
首先,方法next(int)
受到保护,这意味着它不打算由客户端(Random
类的用户)调用。所以你应该使用方法nextInt()
。
其次,要生成任意范围内的随机整数,方法nextInt(int bound)
是最接近它的,它返回0到bound-1
之间的整数(包括 1 ),所以要使用相同的效果
int n = randomGenerator.nextInt(10) + 1;
这将生成0到9之间的随机数,然后加1以使范围为1..10。
1 正式地,它返回[0..bound)
范围内的整数