【问题标题】:Searching an array for a value but only printing the first instance[update]在数组中搜索一个值但只打印第一个实例[更新]
【发布时间】: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


    【解决方案1】:

    您可以使用break 语句退出for 循环。

    【讨论】:

      【解决方案2】:

      您可以通过遍历所有马匹并即时保存最好的马匹来搜索三匹最好的马匹。之后打印结果。

      有三个变量代表三匹最好的马的数量,三个变量代表三匹最好的马的距离。

      在循环中,您检查当前正在查看的马是否优于第一匹、第二匹或第三匹马。然后你把它插到相应的地方,把其他马下移。

      最后,你会得到三匹最好的马和它们的距离,并且可以一一打印出来。

      下移可以实现麦克这样:

      int horse1, horse2, horse3, d1, d2, d3;
      
      // Do something...
      
      horse3 = horse2;
      d3 = d2;
      horse2 = horseNew;
      d2 = dNew;
      

      在第 1 位和第 3 位插入时,您应该能够弄清楚移位。

      【讨论】:

      • 这让我很困惑,所以你有 6 个变量,然后你如何“转移其他”马?
      【解决方案3】:

      您可以使用以下命令代替从第一名到第三名检查获胜者的 for 循环:因此,如果有获胜者,则执行 while 循环。

        winner = checkAndPrintWinner(arrRan);
      

      然后为了找到获胜者本身,下面的代码会进行排序以查看是否有获胜者,如果有,它会跟踪最后一个值,以便它可以追加或添加到winners 中的新元素大批。随意以不同的方式打印结果。代码可以再优化一点。

      private static boolean checkAndPrintWinner(int [] data) {
        boolean isWinner = false;
        // Do copy and then Ascending sort
        int results[] = Arrays.copyOf(data, data.length);
        Arrays.sort(results);
      
        if (results[results.length-1] >= 15) {
          // We have a winner
          isWinner = true;
          String winners[] = new String[3]; // First three winners 
          winners[0] = ""; winners[1] = ""; winners[2] = "";
          int index = 0;
          int total = results.length;
          int lastValue = results[total-1];
          int fromIndex = 0;
      
          // Start from the back of sorted array where our winners are.
          for (int i = total-1; i >= 0; i--) {
            int nextValue = results[i];
      
            // if values differ, move on to next winner
            if (lastValue != nextValue) {
              fromIndex = 0;
              index++;
            }
            // we got all three winners, so break
            if (index == 3) break;
      
            // Get the next winning index
            fromIndex = getHorseIndexForValue(fromIndex, nextValue, data);
            winners[index] += " Horse " + (fromIndex + 1);
      
            lastValue = nextValue;
            // If winning values are same, next time we want to search from the last found index(fromIndex) + 1.
            fromIndex++;
          }
      
          System.out.println("Winners: " + Arrays.toString(winners));
        }
        return isWinner;
      }
      
      // Get where our horse is based on its score
      private static int getHorseIndexForValue(int from, int value, int [] data) {
        for (int i = from; i < data.length; i++) {
          if (data[i] == value) {
            return i;
          }
        }
        return -1; // should never come here
      }
      

      【讨论】:

        【解决方案4】:

        你的逻辑似乎有很多缺陷。

        • while 循环似乎没有结束
        • 第一个达到 14 的可能不是第一个
        • 达到 15,因此您应该确保没有重复值 出现在第一,第二和第三第一,
        • 设置一次就不能再设置了
        • 一旦找到所有三个,while 循环就会中断。

        使用break语句退出循环

        更新: 让我们假设, horse1 是唯一一个达到或超过 13 的人。在这种情况下, 1. 在任何迭代中,Horse1 = 13,然后 first = null,second=Horse1,third = Horse1 2. Horse1 = 14,第一个 = null,第二个=Horse1,第三个 = horse1 3. Horse1 = 15,第一个 = horse1,第二个 = Horse1,第三个 = Horse1

        在上面的例子中,没有任何变量被重新设置为另一个值,因为没有其他马达到 12 或更高的值

        因此,重复的可能性 如果我做对了请告诉我

        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)+" "; 
             }         
          }
        

        【讨论】:

        • 当找到获胜者时,while 循环结束。在找到获胜者之前,程序不会开始放置马匹,此时我只是想弄清楚为什么程序会在多个位置打印同一匹马
        • 我认为你是对的,这就是它重复的原因。我不知道如何修复它,但至少我知道它为什么坏了。谢谢!
        • 如果它回答了您的问题,请接受。如果你能遵循我之前的指导方针,你也许能够找到正确的实现方式。
        • @DosLurez,您可以采用动态方式,而不是对 12、13 或 14 进行硬编码检查以获得第二和第三名。请参阅我的回答
        猜你喜欢
        • 2018-11-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-14
        • 1970-01-01
        • 2021-01-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多