我正在制作一个赛马程序,该程序将打印第一名、第二名和第三名的马匹。我必须将 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
最佳答案
您可以使用 break
语句退出 for
循环。
关于java - 在数组中搜索值但仅打印第一个实例[更新],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29510779/