2015-03-27 4 views
0

В настоящее время я работаю над проектом java, и я должен сделать программу, которая генерирует число от 1000 до 2000, а затем дает вам возможность ввести количество игроков, все имена и догадки в двух разных массивах, затем создайте два метода: один, чтобы найти самое близкое предположение к фактическим числам, а другое - сообщить или найти победителя, совпадающего с их предположением и распечатать его. Im возникли проблемы с моим вторым способом, им рисует пустую на логической части прямо сейчас это мой код и вывод:Java Guessing Game Project (начинающий)

public static void reportWinner (int answer, int winner, int [] array, String [] array1) 
{ 
    ArrayList tempList = new ArrayList(); 
    ArrayList tempList1 = new ArrayList(); 
    int counter = 0; 
    int temp = 0; 
    for(int index = 0; index < array.length; index++) 
    { 
     temp = answer - array[index]; 
     temp = Math.abs(temp); 
     if(temp == winner) 
     { 
      counter++; 
      tempList.add(array1[index]); 
      tempList1.add(array[index]); 
     } 
    } 
    for(int index = 0; index < tempList.size(); index++) 
    { 
     if(tempList.size() == 1); 
     { 
      System.out.println("The winner is " + tempList.get(0) + ", with a guess of " + tempList1.get(0) + " which is " 
          + winner + " away from the actual number of jelly beans."); 
      if(tempList.size() > 1) 
      { 
       System.out.println("The winners are: "); 
       System.out.println(tempList.get(index) + ", with a guess of " + tempList1.get(index) + " which is " 
            + winner + " away from the actual number of jelly beans."); 
      } 
     } 
     if(tempList.size() == 1 && winner == 0) 
     { 
      System.out.println("The winner is " + tempList.get(0) + ", with a guess of " + tempList1.get(0) + " which is " 
          + "the exact number of jelly beans in the jar."); 
      if(tempList.size() > 1) 
      { 
       System.out.println("The winners are: "); 
       System.out.println(tempList.get(index) + ", with a guess of " + tempList1.get(index) + " which is " 
            + "the exact number of jelly beans in the jar."); 
      } 
     } 
    } 
    } 

Это выход он производит, когда есть больше чем один победитель.

There were 1532 jelly beans in the jar. 
The winner is Stan, with a guess of 1200 which is 332 away from the actual number of jelly beans. 
The winners are: 
Stan, with a guess of 1200 which is 332 away from the actual number of jelly beans. 
The winner is Stan, with a guess of 1200 which is 332 away from the actual number of jelly beans. 
The winners are: 
greg, with a guess of 1200 which is 332 away from the actual number of jelly beans. 
The winner is Stan, with a guess of 1200 which is 332 away from the actual number of jelly beans. 
The winners are: 
Jim, with a guess of 1200 which is 332 away from the actual number of jelly beans. 

Это то, что он должен выглядеть

There were 1500 jelly beans in the jar. 

The winners are: 

Mike with a guess of 1475, which is 25 away from the actual number of jelly beans. 
Tony with a guess of 1525, which is 25 away from the actual number of jelly beans. 

Im, имеющих проблемы с частью метода я знаю, что это много, но если вам нужно, чтобы увидеть остальную часть кода, дайте мне знать, что любая помощь будет оценил, спасибо. (Мне кажется, мне нужен способ аннулирования первой распечатки, если счетчик проходит один, но я не уверен, как это сделать)

+0

Удалить эту точку с запятой с конца этого line: 'if (tempList.size() == 1);'. – rgettman

+0

удалил его и теперь нет выхода –

+0

Никогда, никогда не используйте необработанные типы! Просто сидение. –

ответ

0

Это то, что вам нужно. Примечание: рекомендуется использовать значащие имена переменных, а не array или tempList, чтобы сделать код более читаемым.

public static void reportWinner (int answer, int winner, int [] array, String [] array1) 
{ 
    ArrayList tempList = new ArrayList(); 
    ArrayList tempList1 = new ArrayList(); 
    int temp = 0; 
    for(int index = 0; index < array.length; index++) 
    { 
     temp = answer - array[index]; 
     temp = Math.abs(temp); 
     if(temp == winner) 
     { 
      tempList.add(array1[index]); 
      tempList1.add(array[index]); 
     } 
    } 
    if(tempList.size() > 1) { 
     System.out.println("The winners are: "); 
    } else if(tempList.size() == 1) { 
     System.out.println("The winner is: "); 
    } 
    for(int index = 0; index < tempList.size(); index++) 
    { 
     String suffix = ""; 
     if(winner == 0) { 
      suffix = "the exact number of jelly beans in the jar." 
     } else { 
      suffix = winner + " away from the actual number of jelly beans." 
     } 
     System.out.println(tempList.get(index) + ", with a guess of " + tempList1.get(index) + " which is " + suffix); 
    } 
} 
2

Попробуйте это. Я внес много изменений в ваш код, потому что я этого не понимал. После изменения:

  • Нет сырых типов
  • только один цикл, чтобы найти победителю
  • только один массив с игроком, и их количество
  • Другой цикл для вывода

Здесь представляет собой код

import java.util.ArrayList; 
import java.util.List; 

public class GuesNumber { 

    public static void main(String[] args) { 
     // The number we want to guess 
     final int theNumber = 1500; 
     // A random set of players and their numbers 
     List<Player> players = new ArrayList<>(); 
     for (int i = 0; i < 100; i++) { 
      players.add(new Player("Player " + i, (int) (Math.round((Math.random() * 1000)) + 1000))); 
     } 
     // Call of your function (with less arguments) 
     reportWinner(theNumber, players); 
    } 

    public static void reportWinner(int theNumber, List<Player> players) { 
     // Here we store the minimal diff between THE number 
     // and the number of the potential winner 
     Integer minDiff = null; 
     // Here we store the winners 
     ArrayList<Player> winners = new ArrayList<>(); 
     // Find the winners 
     for (Player player : players) { 
      int diff = Math.abs(player.number - theNumber); 
      // We have a potential winner the player is the first 
      // we check or his number is less or equal then 
      // the minimal diff 
      if (minDiff == null || minDiff <= diff) { 
       // We have to clear all potential winners, 
       // if the number of the player is smaller then 
       // the minimal diff 
       if (minDiff != null && minDiff > diff) { 
        winners.clear(); 
       } 
       // Add a potential winner 
       winners.add(player);      
       minDiff = diff; 
      }; 
     } 
     // Let's do the output 
     System.out.println("There were " + theNumber + " jelly beans in the jar\n"); 
     System.out.println("The winner " + (winners.size() == 1 ? "is" : "are") + ":\n"); 
     for (Player player : winners) { 
      System.out.print(player.name + " with a gues of " + player.number + ", wich is " + minDiff + " away from the actual number of jelly beans. "); 
     } 
     System.out.println(""); 
    } 

    public static class Player { 

     String name; 
     int number; 

     public Player(String name, int number) { 
      this.name = name; 
      this.number = number; 
     } 
    } 

} 
+0

Всегда полезно объяснить, где и что было, и что вы изменили. – Tom

+0

@Tom - Вы правы. Но я думаю, что метод в вопросе имеет очень индивидуальный стиль. Поэтому я изменил весь метод. – drkunibar

+0

Это не так, но OP должен знать, какова была его ошибка и какие улучшения в вашей программе. Например, гораздо лучший способ повторить список «победителей», отсутствие сырых типов и т. Д. – Tom