【发布时间】:2015-06-13 04:23:01
【问题描述】:
我正在制作一个赛马程序,将打印第 2 名和第 3 名的马匹。我必须在一个数组中设置 10 匹马,然后将 1-3 的随机数添加到它们的位置。获胜者是第一匹达到 15 或以上的马。
我的问题是我的程序没有正确打印第二和第三名的马。
[更新] 我删除了许多条件并添加了字符串变量来存储信息。它运行更流畅,但现在我不知道为什么程序会不断打印重复等。
这是代码,我更新了打印获胜者的 for 循环:
import java.util.*;
public class HorseRace{
public static void main(String[ ] arg){
Scanner reader = new Scanner(System.in);
int range = 3;
int win = 15;
final int SIZE = 5;
Random ran = new Random( );
boolean winner = false;
boolean second = false;
int[ ] arrRan = new int[SIZE];
System.out.print("Off to the races! Press enter to make the horses run.");
String readString = reader.nextLine();
while(winner!=true){//loop forever until winner
//begin program
System.out.print(readString);
if(readString.equals("")){//when enter is pressed
for(int i = 0; i<arrRan.length; i++){//loop that adds position when enter is pressed
arrRan[i] = arrRan[i] + (ran.nextInt(3) + 1); //add to the array in random numbers
System.out.println("Horse " + (i+1) + ": " + arrRan[i]);//print the contents of the array
}
}//end if
if(reader.hasNextLine()){
readString = reader.nextLine();
System.out.println("Please press enter.");
}
for(int i = 0; i<arrRan.length; i++){
if(arrRan[i]>=15){//if a winner is found
first = first + "Horse " + (i+1)+" ";
winner = true;
}
//if winner is found then look for a 2nd place
//if there is no position 14 then search for 13, if no 13 then 12. The lowest 2nd place will be in position 12.
if(arrRan[i]==14){
second = second + "Horse " + (i+1)+" ";
secondPl = true;
}
if(arrRan[i]!=14&&arrRan[i]==13){
second = second + "Horse " + (i+1)+" ";
secondPl = true;
}
if(arrRan[i]!=13&&arrRan[i]==12){
second = second + "Horse " + (i+1)+" ";
secondPl = true;
}
if(arrRan[i]==13){
third = third + "Horse " + (i+1)+" ";
}
}
if(winner==true){
System.out.println(first);
System.out.println(second);
System.out.println(third);
}
}//end while
}//close main
}//close class
【问题讨论】:
标签: java arrays loops conditional-statements