2016-11-26 2 views
0

Хорошо, Моя проблема в том, что 2-й оператор if и 3rd if выдает оператор «< ''> 'не определен.Two Dice 2 Java Issue

Это должно быть два значения int и показать, что они могут делать меньше или больше, не уверен, почему он не работает на моем конце. Вот два кода:

public class TwoDice2 { 
public static void main(String[ ] args) { 

    Die firstDie = new Die(); 
    Die secondDie = new Die(); 

    if (firstDie == secondDie) { 
    System.out.println("First die is " + firstDie.getValue()); 
    System.out.println("Next die is " + secondDie.getValue()); 
    System.out.println("The two dice are the same!"); 
    } 

     if (firstDie > secondDie) { 
      System.out.println("First die is " + firstDie.getValue()); 
      System.out.println("Next die is " + secondDie.getValue()); 
      System.out.println("Die One: " + firstDie + " is greater than Die Two: " + secondDie); 
     } 
      if (firstDie < secondDie) { 
       System.out.println("First die is " + firstDie.getValue()); 
       System.out.println("Next die is " + secondDie.getValue()); 
       System.out.println("Die One: " + firstDie + " is less than Die Two: " + secondDie); 
      } 

} 

}

И:

public class Die { 
private int value; 
private static final int HIGHEST_DIE_VALUE = 6; 
private static final int LOWEST_DIE_VALUE = 1; 

    public Die() { 
     value = ((int)(Math.random() * 100) % HIGHEST_DIE_VALUE + LOWEST_DIE_VALUE); 
} public int getValue() { return value; } } 
+0

Die are not ints. Вы probaby хотите сравнить 'firstDie.getValue()' с тем же для secondDie. Также ваш '==' будет терпеть неудачу, поскольку проверяет ссылочное равенство. И если вы не дадите своему классу Die достойный метод 'equals' и' hashCode', метод equals будет терпеть неудачу. Если вы не сравните * значения *. –

ответ

0

вам просто нужно добавить значение получить после каждого из Dice здесь фиксированный код

public class TwoDice2 { 
public static void main(String[ ] args) { 

Die firstDie = new Die(); 
Die secondDie = new Die(); 

if (firstDie.getValue() == secondDie.getValue()) { 
System.out.println("First die is " + firstDie.getValue()); 
System.out.println("Next die is " + secondDie.getValue()); 
System.out.println("The two dice are the same!"); 
} 

    if (firstDie.getValue() > secondDie.getValue()) { 
     System.out.println("First die is " + firstDie.getValue()); 
     System.out.println("Next die is " + secondDie.getValue()); 
     System.out.println("Die One: " + firstDie.getValue() + " is greater than Die Two: " + secondDie.getValue()); 
    } 
     if (firstDie.getValue() < secondDie.getValue()) { 
      System.out.println("First die is " + firstDie.getValue()); 
      System.out.println("Next die is " + secondDie.getValue()); 
      System.out.println("Die One: " + firstDie.getValue() + " is less than Die Two: " + secondDie.getValue()); 
     } 

} 

вам нужно добавить его после того, как все они, потому что firstdie и второй умирают получить только вы использовали семена для генерации этого не номер фактического количества

1

Die является пользовательский тип (не примитивный тип, как int, long, и т.д ..), поэтому для того, чтобы сообщите JVM, что как можно сравнить два объекта Die (т. е. они равны или не равны), ваш класс Die должен реализовать Comparable, как показано ниже (также в качестве примечания стороны использовать else ifдля проверки те же условия)

Die класс:

public class Die implements Comparable<Die> { 

     private int value; 
     private static final int HIGHEST_DIE_VALUE = 6; 
     private static final int LOWEST_DIE_VALUE = 1; 

     public Die() { 
       value = ((int)(Math.random() * 100)% 
        HIGHEST_DIE_VALUE + LOWEST_DIE_VALUE); 
     } 

     public int getValue() { 
      return value; 
     } 

     @Override 
     public int compareTo(Die o) { 
      if(this.value < o.getValue()) { 
       return -1; 
      } else if(this.value > o.getValue()) { 
       return 1; 
      } 
      return 0; 
     } 

     @Override 
     public boolean equals(Object obj) { 
      Die die = (Die)obj; 
      if (this.getValue() == die.getValue()) { 
      return true; 
      } else { 
      return false; 
      } 
     } 

     @Override 
     public int hashCode() { 
     return value; 
     } 
    } 

Использование:

public static void main(String[] args) { 
     Die firstDie = new Die(); 
     Die secondDie = new Die(); 

     if (firstDie.compareTo(secondDie) == 0) { 
      System.out.println("First die is " + firstDie.getValue()); 
      System.out.println("Next die is " + secondDie.getValue()); 
      System.out.println("The two dice are the same!"); 
     } else if (firstDie.compareTo(secondDie) > 0) { 
      System.out.println("First die is " + firstDie.getValue()); 
      System.out.println("Next die is " + secondDie.getValue()); 
      System.out.println("Die One: " + firstDie + " 
       is greater than Die Two: " + secondDie); 
     } else if (firstDie.compareTo(secondDie) < 0) { 
      System.out.println("First die is " + firstDie.getValue()); 
      System.out.println("Next die is " + secondDie.getValue()); 
      System.out.println("Die One: " + firstDie + " is 
        less than Die Two: " + secondDie); 
     } 
    } 

Кроме того, как показано выше, это лучшая практика, чтобы переопределить equals() & hashcode() всякий раз, когда вы implementComparable.

+0

Может также дать класс a equals и метод hashCode, чтобы результат сравнения соответствовал тесту функционального равенства и hashCode. то есть, если compareTo возвращает 0, то контракт предусматривает, что два класса должны быть равными и иметь один и тот же хэш-код. –

+0

Уверен, обновление этого ... – developer

0

вы можете реализовать сравнимые как ответ на javaguy, либо вы можете использовать firstDie.getValue == secondDie.getValue и firstDie.getValue > secondDie.getValue и так далее, так что вы сравниваете int сек вместо object с. Это будет выглядеть так:

public class TwoDice2 { 
public static void main(String[ ] args) { 

Die firstDie = new Die(); 
Die secondDie = new Die(); 

if (firstDie.getValue() == secondDie.getValue()) { 
System.out.println("First die is " + firstDie.getValue()); 
System.out.println("Next die is " + secondDie.getValue()); 
System.out.println("The two dice are the same!"); 
} 

    if (firstDie.getValue() > secondDie.getValue()) { 
     System.out.println("First die is " + firstDie.getValue()); 
     System.out.println("Next die is " + secondDie.getValue()); 
     System.out.println("Die One: " + firstDie + " is greater than Die Two: " + secondDie); 
    } 
     if (firstDie.getValue() < secondDie.getValue()) { 
      System.out.println("First die is " + firstDie.getValue()); 
      System.out.println("Next die is " + secondDie.getValue()); 
      System.out.println("Die One: " + firstDie + " is less than Die Two: " + secondDie); 
     } 

} 
+0

Спасибо всем за помощь! Было легко разобраться со всей помощью и позаботиться об этом. Меня так беспокоило. –

+0

Ваш прием :) – cat16