2014-01-21 3 views
2

Я взял несколько классов программирования Java в колледже, но прошло несколько лет, поэтому я довольно ржавый. Я решил попросить моего брата о программировании. Он попросил меня написать программу, чтобы опробовать его по эффективности элементарного типа в играх покемонов. Код работает по большей части, но по какой-то причине иногда появляется диалоговое окно Option. У меня есть заголовок, но остальное - серая коробка. Наиболее сложная для меня часть заключается в том, что у меня есть println() прямо перед ней, и она печатает правильную фразу, когда панель пуста.JOptionPane showOptionDialog отображается пустым случайно

Вот мой код вывод:

import javax.swing.JOptionPane; 
public class Quiz { 


public static void main(String[] args) { 
    try{ 
     /*creates the matrix of the different types 
     *and their effectiveness to each other. 0 
     *represents "Not very effective", 1 is "Neutral" 
     *2 is "Super effective", 3 is "No Damage" 
     */ 

     int[][] myTypeArray = 
      {{1, 1, 1, 1, 1, 0, 1, 3, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1}, 
       {2, 1, 0, 0, 1, 2, 0, 3, 2, 1, 1, 1, 1, 0, 2, 1, 2, 0}, 
       {1, 2, 1, 1, 1, 0, 2, 1, 0, 1, 1, 2, 0, 1, 1, 1, 1, 1}, 
       {1, 1, 1, 0, 0, 0, 1, 0, 3, 1, 1, 2, 1, 1, 1, 1, 1, 2}, 
       {1, 1, 3, 2, 1, 2, 0, 1, 2, 2, 1, 0, 2, 1, 1, 1, 1, 1}, 
       {1, 0, 2, 1, 0, 1, 2, 1, 0, 2, 1, 1, 1, 1, 2, 1, 1, 1}, 
       {1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 2, 1, 2, 1, 1, 2, 0}, 
       {3, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 0, 1}, 
       {1, 1, 1, 1, 1, 2, 1, 1, 0, 0, 0, 1, 0, 1, 2, 1, 1, 2}, 
       {1, 1, 1, 1, 1, 0, 2, 1, 2, 0, 0, 2, 1, 1, 2, 0, 1, 1}, 
       {1, 1, 1, 1, 2, 2, 1, 1, 1, 2, 0, 0, 1, 1 ,1, 0, 1, 1}, 
       {1, 1, 0, 0, 2, 2, 0, 1, 0, 0, 2, 0, 1, 1, 1, 0, 1, 1}, 
       {1, 1, 2, 1, 3, 1, 1, 1, 1, 1, 2, 0, 0, 1, 1, 0, 1, 1}, 
       {1, 2, 1, 2, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 3, 1}, 
       {1, 1, 2, 1, 2, 1, 1, 1, 0, 0, 0, 2, 1, 1, 0, 2, 1, 1}, 
       {1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 2, 1, 3}, 
       {1, 0, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 0, 0}, 
       {1, 2, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 2, 2, 1}}; 

     //Names for the types 
     String[] myTypeNamesArray = {"Normal", "Fighting", "Flying", "Poison", "Ground", 
       "Rock", "Bug", "Ghost", "Steel", "Fire", "Water", 
       "Grass", "Electric", "Psychic", "Ice", "Dragon", 
       "Dark", "Fairy"}; 


     //loops the message panes until they get a wrong answer 
     for(int i = 0; i > -1; i++){ 

      //Two integers to randomly select one of the 18 different types 
      int num1 = (int)(Math.random()*18); 
      int num2 = (int)(Math.random()*18); 

      //Creates JOptionPane to show the two randomed types and get input 
      //Name of the buttons 
      Object[] buttons = { "Not Very Effective", "Neutral", "Super Effective", "No Damage" }; 

      //Test output for asking them how effective type 1 is vs type 2 
      System.out.println(num1 + " " + num2 + " " + "How effective is " + 
        myTypeNamesArray[num1] + " against " + myTypeNamesArray[num2] + "? " + 
        "the answer was " + (String)buttons[myTypeArray[num1][num2]] + ". " + i); 

      // **HERE IS WHERE THE MESSAGE IS BLANK SOMETIMES** 
      int answer = JOptionPane.showOptionDialog(null, "How effective is " + 
        myTypeNamesArray[num1] + " against " + myTypeNamesArray[num2] + "?", 
        "Pokemon Type Effectiveness Quiz", JOptionPane.DEFAULT_OPTION, 
        JOptionPane.QUESTION_MESSAGE, null, buttons, buttons[0]); 


      //Test their answers      
      if(answer == myTypeArray[num1][num2]){ 
      } else if(!(answer == myTypeArray[num1][num2])) { 
       // **THIS IS ALSO BLANK SOMETIMES ** 
       JOptionPane.showMessageDialog(null, "Sorry, the answer was " + 
         (String)buttons[myTypeArray[num1][num2]] + ". You said " + 
         buttons[answer] + "\nYou got " + i + " correct."); 
       break; 
      } else { 
       break; 
      } 
     } 
    } catch (Exception e) { 
     System.out.println("The error was " + e); 
    } 

}//end main 

} 
+0

Запустите код в событии Swing Event или EDT, вызывая 'SwingUtilities.invokeLater (новый Runnable() {public void run() {... ваш код идет здесь ...}});' –

+0

Случайность из выбранных индексов не говорит вам о случайности пустых диалогов? – Typo

+0

@HovercraftFullOfEels Я рассмотрю его. Я никогда не узнавал/не слышал об этом до – jjthemagicman

ответ

2

Прерывистый характер этой проблемы предполагает выпуск поточного. Попробуйте запустить код в потоке событий Swing. Что-то вроде:

public static void main(String[] args) { 
    SwingUtilities.invokeLater(new Runnable() { 
    public void run() { 
     doOnEventThread(); 
    } 
    }); 
} 

public static void doOnEventThread() { 
    try{ 
     /*creates the matrix of the different types 
     *and their effectiveness to each other. 0 
     *represents "Not very effective", 1 is "Neutral" 
     *2 is "Super effective", 3 is "No Damage" 
     */ 

     int[][] myTypeArray = 
      {{1, 1, 1, 1, 1, 0, 1, 3, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1}, 
       {2, 1, 0, 0, 1, 2, 0, 3, 2, 1, 1, 1, 1, 0, 2, 1, 2, 0}, 
       {1, 2, 1, 1, 1, 0, 2, 1, 0, 1, 1, 2, 0, 1, 1, 1, 1, 1}, 
       {1, 1, 1, 0, 0, 0, 1, 0, 3, 1, 1, 2, 1, 1, 1, 1, 1, 2}, 
       {1, 1, 3, 2, 1, 2, 0, 1, 2, 2, 1, 0, 2, 1, 1, 1, 1, 1}, 
       {1, 0, 2, 1, 0, 1, 2, 1, 0, 2, 1, 1, 1, 1, 2, 1, 1, 1}, 
       {1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 2, 1, 2, 1, 1, 2, 0}, 
       {3, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 0, 1}, 
       {1, 1, 1, 1, 1, 2, 1, 1, 0, 0, 0, 1, 0, 1, 2, 1, 1, 2}, 
       {1, 1, 1, 1, 1, 0, 2, 1, 2, 0, 0, 2, 1, 1, 2, 0, 1, 1}, 
       {1, 1, 1, 1, 2, 2, 1, 1, 1, 2, 0, 0, 1, 1 ,1, 0, 1, 1}, 
       {1, 1, 0, 0, 2, 2, 0, 1, 0, 0, 2, 0, 1, 1, 1, 0, 1, 1}, 
       {1, 1, 2, 1, 3, 1, 1, 1, 1, 1, 2, 0, 0, 1, 1, 0, 1, 1}, 
       {1, 2, 1, 2, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 3, 1}, 
       {1, 1, 2, 1, 2, 1, 1, 1, 0, 0, 0, 2, 1, 1, 0, 2, 1, 1}, 
       {1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 2, 1, 3}, 
       {1, 0, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 0, 0}, 
       {1, 2, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 2, 2, 1}}; 

     //Names for the types 
     String[] myTypeNamesArray = {"Normal", "Fighting", "Flying", "Poison", "Ground", 
       "Rock", "Bug", "Ghost", "Steel", "Fire", "Water", 
       "Grass", "Electric", "Psychic", "Ice", "Dragon", 
       "Dark", "Fairy"}; 


     //loops the message panes until they get a wrong answer 
     for(int i = 0; i > -1; i++){ 

      //Two integers to randomly select one of the 18 different types 
      int num1 = (int)(Math.random()*18); 
      int num2 = (int)(Math.random()*18); 

      //Creates JOptionPane to show the two randomed types and get input 
      //Name of the buttons 
      Object[] buttons = { "Not Very Effective", "Neutral", "Super Effective", "No Damage" }; 

      //Test output for asking them how effective type 1 is vs type 2 
      System.out.println(num1 + " " + num2 + " " + "How effective is " + 
        myTypeNamesArray[num1] + " against " + myTypeNamesArray[num2] + "? " + 
        "the answer was " + (String)buttons[myTypeArray[num1][num2]] + ". " + i); 

      // **HERE IS WHERE THE MESSAGE IS BLANK SOMETIMES** 
      int answer = JOptionPane.showOptionDialog(null, "How effective is " + 
        myTypeNamesArray[num1] + " against " + myTypeNamesArray[num2] + "?", 
        "Pokemon Type Effectiveness Quiz", JOptionPane.DEFAULT_OPTION, 
        JOptionPane.QUESTION_MESSAGE, null, buttons, buttons[0]); 


      //Test their answers      
      if(answer == myTypeArray[num1][num2]){ 
      } else if(!(answer == myTypeArray[num1][num2])) { 
       // **THIS IS ALSO BLANK SOMETIMES ** 
       JOptionPane.showMessageDialog(null, "Sorry, the answer was " + 
         (String)buttons[myTypeArray[num1][num2]] + ". You said " + 
         buttons[answer] + "\nYou got " + i + " correct."); 
       break; 
      } else { 
       break; 
      } 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

} 

Редактировать
Для получения дополнительной информации о потоке событий Свинг и многопоточных вопросов, пожалуйста, посмотрите на статью, Concurrency in Swing. Но для повторного итерации, когда вы оказываетесь против программного неправильного поведения, которое прерывисто, это не происходит все время, подумайте «проблема с потоками».

+0

Спасибо, что, кажется, исправил его. Я до сих пор не понимаю, как и почему, я посмотрю, но у меня еще нет пустых окон. – jjthemagicman

+0

@jjthemagicman: см. Править для ответа и ссылки для получения дополнительной информации об этом. –

+0

Полезно знать, спасибо. Я прочитал статью, и она объясняет это довольно хорошо. – jjthemagicman

Смежные вопросы