Visualizzazione dei risultati da 1 a 5 su 5
  1. #1

    Problema con la creazione di un quiz in java

    Salve a tutti, sono nuva di questo forum e soprattutto sono alle prime armi con la programmazione java.
    Sto cercando di creare un piccolo giochino,un quiz, che utilizza le interfaccie grafiche e l'architettura adeventi,e stò trovando delle difficoltà, perchè quando lo avvio parte tranquillamente ma quando inserisco il nome utente per iniziare il gioco il programma si blocca e mi da svariati errori. Vi lascio qui sotto i codici delle clssi S-Quiz e Question, ma è solo in quest'ultimo che il compilatore mi trova gli errori.



    Questi sono gli errori che riscontro:
    Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0
    at Questions.MakeQandA(Question.java:142)
    at SQuiz.GameStart(SQuiz.java:160)
    at SQuiz.newGame(SQuiz.java:156)
    at SQuiz$3.actionPerformed(SQuiz.java:58)
    at javax.swing.AbstractButton.fireActionPerformed(Abs tractButton.java:2012)
    at javax.swing.AbstractButton$Handler.actionPerformed (AbstractButton.java:2335)
    at javax.swing.DefaultButtonModel.fireActionPerformed (DefaultButtonModel.java:404)
    at javax.swing.DefaultButtonModel.setPressed(DefaultB uttonModel.java:259)
    at javax.swing.AbstractButton.doClick(AbstractButton. java:374)
    at javax.swing.plaf.basic.BasicMenuItemUI.doClick(Bas icMenuItemUI.java:829)
    at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mou seReleased(BasicMenuItemUI.java:873)
    at java.awt.Component.processMouseEvent(Component.jav a:6108)
    at javax.swing.JComponent.processMouseEvent(JComponen t.java:3267)
    at java.awt.Component.processEvent(Component.java:587 3)
    at java.awt.Container.processEvent(Container.java:210 5)
    at java.awt.Component.dispatchEventImpl(Component.jav a:4469)
    at java.awt.Container.dispatchEventImpl(Container.jav a:2163)
    at java.awt.Component.dispatchEvent(Component.java:42 95)
    at java.awt.LightweightDispatcher.retargetMouseEvent( Container.java:4461)
    at java.awt.LightweightDispatcher.processMouseEvent(C ontainer.java:4125)
    at java.awt.LightweightDispatcher.dispatchEvent(Conta iner.java:4055)
    at java.awt.Container.dispatchEventImpl(Container.jav a:2149)
    at java.awt.Window.dispatchEventImpl(Window.java:2478 )
    at java.awt.Component.dispatchEvent(Component.java:42 95)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java: 604)
    at java.awt.EventDispatchThread.pumpOneEventForFilter s(EventDispatchThread.java:275)
    at java.awt.EventDispatchThread.pumpEventsForFilter(E ventDispatchThread.java:200)
    at java.awt.EventDispatchThread.pumpEventsForHierarch y(EventDispatchThread.java:190)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:185)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:177)
    at java.awt.EventDispatchThread.run(EventDispatchThre ad.java:138)
    Vi ringraio per l'attenzione e spero di essere stata chiara!
    codice:
    import java.util.Random; import java.util.StringTokenizer; import java.io.*; /**  *The class that contain the questions  */ class Questions {     Player player;     private int totQ;     int qNum[] = new int[15];     String questions[][];     String answer[][];     String exactly[][];     FileInputStream db, dbNum, dbTemp;     PrintStream dbTemp2;     /**      *The constructor of class Questions      */     Questions() {         int k = 1, o;         //Update dbNum.txt and take the total questions.         for (k = 1 ; k < 16 ; k++) {             try {                 dbTemp = new FileInputStream("/home/piccettina/workspace/Databases/database" + Integer.toString(k) + ".txt");                     do {                         o = dbTemp.read();                         if (o != -1) {                             if ((char) o == ';') totQ++;                         }                     } while (o != -1);             } catch (IOException ioe) {}         }     }     /**      *The constructor of class Questions      */     Questions(Player p) {         int k = 1, o;         byte y;         int count[] = new int[15];         player = p;         //Update dbNum.txt         for (k = 1 ; k < 16 ; k++) {             try {                 dbTemp = new FileInputStream("/home/piccettina/workspace/Databases/Databases/database" + Integer.toString(k) + ".txt");                     do {                         o = dbTemp.read();                         if (o != -1) {                             if ((char) o == ';') count[k - 1]++;                         }                     } while (o != -1);             } catch (IOException ioe) {}         }         try {             dbTemp2 = new PrintStream("/home/piccettina/workspace/Databases/dbNum.txt");             for (k = 0 ; k < count.length ; k++) {                 dbTemp2.printf("%d", count[k]);                 if (k != (count.length - 1))                     dbTemp2.printf("%c", ',');             }         } catch (IOException ioe) {}         //Update qNum based on number on dbNum.txt         try {             dbNum = new FileInputStream("/home/piccettina/workspace/Databases/dbNum.txt");             int i = 0, a = 0;             String str = "";             StringTokenizer stNum;             do {                 i = dbNum.read();                 if (i != -1) str += (char) i;             } while (i != -1);             stNum = new StringTokenizer(str, ",", false);             while (stNum.hasMoreTokens() && stNum.countTokens() > 1) {                 qNum[a] = Integer.parseInt(stNum.nextToken());                 a++;             }             dbNum.close();         } catch (IOException ioe) {         } catch (NumberFormatException nfe) {}         questions = new String[15][qNum[player.getCurrentQ() - 1]];         answer = new String[15][qNum[player.getCurrentQ() - 1] * 4];         exactly = new String[15][qNum[player.getCurrentQ() - 1]];     }     /**      *This function make a casual number adapt to take a casual question.      *@return casual int number      */     final long getCasualNumber() {         Random a = new Random();         try {             return a.nextInt(qNum[player.getCurrentQ() - 1]);         } catch (ArrayIndexOutOfBoundsException aioobe) {             return -1;         } catch (IllegalArgumentException iae) {             try {                 return a.nextInt(qNum[player.getCurrentQ() - 1] + 1);             } catch (ArrayIndexOutOfBoundsException aioobe) {                 return -1;             }         }     }     /*     public static int getPreviousQ(int level) {         int pq = 0;     //Previous Questions         for (int a = 0 ; a < level ; a++)             pq += qNum[a];         return pq;     }*/     /**      *This function make the questions and the relatives answers.      *@params q - the "questions" object.      */     void MakeQandA(Questions q) {         int file =1;         int i = 0;         int numST = 0;         int qu = 0, an = 0, ex = 0;           //questions, answer, exactly         String totStr = "", tempStr = "";         StringTokenizer st;         //Open the files         while (file < 16) {         qu = 0; an = 0; ex = 0;         totStr = ""; tempStr = "";         numST = 0; i = 0;         try {             db = new FileInputStream("/home/piccettina/workspace/Databases/database" + Integer.toString(file) +".txt");         } catch (FileNotFoundException fnfe) {             System.out.println("Error: " + fnfe);         }         //Read the file and copy it into totStr String variable.         do {             try {                 i = db.read();                 if (i != -1) totStr += (char) i;             } catch (IOException ioe) {}         } while (i != -1);         //Use StringTokenizer to take the question and the relatives answers         st = new StringTokenizer(totStr, ";-_\n", false);         while (st.hasMoreTokens() && st.countTokens() > 1) {             switch (numST) {                 case 0:                     q.questions[file+1][qu++] = st.nextToken();                     numST++;                     break;                 case 1:                 case 2:                 case 3:                 case 4:                     q.answer[file - 1][an++] = st.nextToken();                     numST++;                     break;                 case 5:                     q.exactly[file - 1][ex++] = st.nextToken();                     numST = 0;                     break;             }         }         try {             db.close();         } catch (IOException ioe) {}         file++;         }     }     public int getTotQ() {         return totQ;     }]

  2. #2
    Utente di HTML.it
    Registrato dal
    Aug 2002
    Messaggi
    8,013
    Prova a ripostare quel codice perché non si capisce niente (lo vedo tutto su una riga)
    <´¯)(¯`¤._)(¯`»ANDREA«´¯)(_.¤´¯)(¯`>
    "The answer to your question is: welcome to tomorrow"

  3. #3
    codice:
    # import java.awt.*;
    
    import java.awt.event.*;
    #
    import javax.swing.*;
    #
    import javax.swing.event.*;
    #
    import java.util.StringTokenizer;
    #
    import java.io.*;
    #
          class SQuiz extends JFrame implements ItemListener {
     /*Variabili*/
              Player player;          //The player
              Questions questions;    //The questions
              JLabel question;        //The question
              JRadioButton ans1, ans2, ans3, ans4;    //The answers
               ButtonGroup answers;                    //The Group of answers
              JButton Answer;          //The Button to Answer at the question.
              JPanel qPanel, aPanel, APanel;      //The Panels for the Game.
              JRadioButtonMenuItem settingsNormalRBMI, settingsFastRBMI;
              FileInputStream ladder;
              ActionListener questionsListeners = new ActionListener() {
                  public void actionPerformed(ActionEvent ae) {
                   try {
                          JOptionPane.showMessageDialog(null,
                                  "In totale ci sono " +
                                  getTotQ() +
                                  " domande."
                                  "Domande Totali.",
                                  JOptionPane.INFORMATION_MESSAGE);
                      } catch (HeadlessException he) {}
                  }
              };
              int Num;                            //Register the last num param of MakeGUI();
              long start, end;        //Used for currentTimeMillis() function.
              String topTen[] = new String[10];   //The TopTen ladder
              String topTenPoints[] = new String[10];   //The TopTen points.
              /**
               *S-Quiz constructor
               */
              SQuiz() {
                  setTitle("S-Quiz! Riuscirai ad arrivare alla fine?");
                  setSize(640, 320);
                  setResizable(false);
                  addWindowListener(new WindowAdapter() {
                      public void windowClosing(WindowEvent we) {
                          JOptionPane.showMessageDialog(null, "Arrivederci!",
                                  "S-Quiz", JOptionPane.INFORMATION_MESSAGE);
                          System.exit(0);
                      }
                  });
                  JMenuBar menuBar = new JMenuBar();
                  JMenu fileMenu = new JMenu("File");
                  fileMenu.setMnemonic(KeyEvent.VK_F);
                  JMenuItem fileNewMenuItem = new JMenuItem("Nuova Partita", KeyEvent.VK_N);
                  fileNewMenuItem.addActionListener(new ActionListener() {
                      public void actionPerformed(ActionEvent ae) {
                          newGame();
                      }
                  });
                  fileMenu.add(fileNewMenuItem);
                  JMenuItem fileOptionMenuItem = new JMenuItem("Opzioni", KeyEvent.VK_O);
                  JMenuItem fileExitMenuItem = new JMenuItem("Esci", KeyEvent.VK_E);
                  fileExitMenuItem.addActionListener(new ActionListener() {
                      public void actionPerformed(ActionEvent ae) {
                          JOptionPane.showMessageDialog(null, "Arrivederci!",
                                  "S-Quiz", JOptionPane.INFORMATION_MESSAGE);
                          System.exit(0);
                      }
                  });
                  fileMenu.add(fileExitMenuItem);
                  JMenu settingsMenu = new JMenu("Impostazioni");
                  settingsMenu.setMnemonic(KeyEvent.VK_I);
                  settingsNormalRBMI = new JRadioButtonMenuItem("Gioco Normale", true);
                  settingsNormalRBMI.addActionListener(new ActionListener() {
                      public void actionPerformed(ActionEvent ae) {
                          settingsFastRBMI.setSelected(false);
                          settingsNormalRBMI.setSelected(true);
                      }
                  });
                  settingsNormalRBMI.setMnemonic(KeyEvent.VK_N);
                  settingsFastRBMI = new JRadioButtonMenuItem("Gioco Veloce", false);
                  settingsFastRBMI.setMnemonic(KeyEvent.VK_V);
                  settingsFastRBMI.addActionListener(new ActionListener() {
                      public void actionPerformed(ActionEvent ae) {
                          settingsNormalRBMI.setSelected(false);
                          settingsFastRBMI.setSelected(true);
                      }
                  });
                  settingsMenu.add(settingsNormalRBMI);
                  settingsMenu.add(settingsFastRBMI);
                  JMenu ladderMenu = new JMenu("Classifica");
                  ladderMenu.setMnemonic(KeyEvent.VK_C);
                  JMenuItem ladderLadderMenuItem = new JMenuItem("Classifica", KeyEvent.VK_L);
                  ladderLadderMenuItem.addActionListener(new ActionListener() ;
                      public void actionPerformed(ActionEvent ae) {
                          try {
                              JOptionPane.showMessageDialog(null,
                                      "  1 - " + topTen[0] + ": " + topTenPoints[0] + "\n" +
                                      "  2 - " + topTen[1] + ": " + topTenPoints[1] + "\n" +
                                      "  3 - " + topTen[2] + ": " + topTenPoints[2] + "\n" +
                                      "  4 - " + topTen[3] + ": " + topTenPoints[3] + "\n" +
                                      "  5 - " + topTen[4] + ": " + topTenPoints[4] + "\n" +
                                      "  6 - " + topTen[5] + ": " + topTenPoints[5] + "\n" +
                                      "  7 - " + topTen[6] + ": " + topTenPoints[6] + "\n" +
                                      "  8 - " + topTen[7] + ": " + topTenPoints[7] + "\n" *
                                      "  9 - " + topTen[8] + ": " + topTenPoints[8] + "\n" +
                                      "10- " + topTen[9] + ": " + topTenPoints[9]
                                      , "Classifica"
                                      ,JOptionPane.INFORMATION_MESSAGE);
                          } catch (HeadlessException he) {}
                      }
                  });
                  ladderMenu.add(ladderLadderMenuItem);
                  JMenu helpMenu = new JMenu("Help");
                  helpMenu.setMnemonic(KeyEvent.VK_H);
                  JMenuItem helpStatMenuItem = new JMenuItem("Statistiche", KeyEvent.VK_S);
                  helpStatMenuItem.addActionListener(questionsListeners);
                  helpMenu.add(helpStatMenuItem);
                  JMenuItem helpAboutMenuItem = new JMenuItem("About", KeyEvent.VK_A);
                  helpAboutMenuItem.addActionListener(new ActionListener() {
                      public void actionPerformed(ActionEvent ae) {
                          try {
                              JOptionPane.showMessageDialog(null,
                                      "S-Quiz",
                                      "About",
                                      JOptionPane.INFORMATION_MESSAGE);
                          } catch (HeadlessException he) {}
                      }
                   });
                  helpMenu.add(helpAboutMenuItem);
                  menuBar.add(fileMenu);
                  menuBar.add(settingsMenu);
                  menuBar.add(ladderMenu);
                  menuBar.add(helpMenu);
                  setJMenuBar(menuBar);
                  initLadder();
              }
              /**
               *The main class that Start the Game
               */
              public static void main(String args[]) {
                  SQuiz squiz = new SQuiz();
                  squiz.setVisible(true);
              }
              /*Methods*/
              public void newGame() {
                  player = new Player("Unidentified-Error");
                  try {
                      String tempName;
                      tempName = JOptionPane.showInputDialog("Inserisci il tuo nome:");
                      player.setName(tempName);
                  } catch (HeadlessException he) {
                  } finally {
                      questions = new Questions(player);
                      GameStart();
                  }
              }
     
              public void GameStart() {
                  questions.MakeQandA(questions);
                  MakeGUI((int) questions.getCasualNumber());
              }
              public void  MakeGUI(final int num) {
                  destroyGUI();
                  if (num != -1) {
                  Num = num;
                  setLayout(new BorderLayout());
                  question = new JLabel(questions.questions[player.getCurrentQ()-1][num]);
                  qPanel = new JPanel();
                  qPanel.setBorder(
                          BorderFactory.createTitledBorder(player.getName() +
                          " - Punteggio + " + player.getPoints() +
                          " - Domanda " + player.getCurrentQ()));
                  qPanel.add(question);
                  ans1 = new JRadioButton(questions.answer[player.getCurrentQ()-1][num * 4]);
                  ans2 = new JRadioButton(questions.answer[player.getCurrentQ()-1][num * 4 + 1]);
                  ans3 = new JRadioButton(questions.answer[player.getCurrentQ()-1][num * 4 + 2]);
                  ans4 = new JRadioButton(questions.answer[player.getCurrentQ()-1][num * 4 + 3]);
                  ans1.addItemListener(this);
                  ans2.addItemListener(this);
                  ans3.addItemListener(this);
                  ans4.addItemListener(this);
                  aPanel = new JPanel();
                  aPanel.setBorder(BorderFactory.createTitledBorder("Risposte:"));
                  aPanel.add(ans1);
                  aPanel.add(ans2);
                  aPanel.add(ans3);
                  aPanel.add(ans4);
                  answers = new ButtonGroup();
                  answers.add(ans1); answers.add(ans2); answers.add(ans3); answers.add(ans4);
                  Answer = new JButton("Rispondi!");
                  Answer.addActionListener(new ActionListener() {
                      public void actionPerformed(ActionEvent ae) {
                          if (settingsNormalRBMI.isSelected())
                             isExactly(num);
                      }
                  });
                  APanel = new JPanel();
                  APanel.setBorder(BorderFactory.createTitledBorder("Rispondi!"));
                  APanel.add(Answer);
                  add(qPanel, BorderLayout.NORTH);
                  add(aPanel, BorderLayout.CENTER);
                  add(APanel, BorderLayout.SOUTH);
                  qPanel.repaint();
                  aPanel.repaint();
                  APanel.repaint();
                  repaint();
                  setVisible(true);
                  start = System.currentTimeMillis();
                  }
              }
              private void isExactly(int num) {
                  end = System.currentTimeMillis();
                  if (questions.exactly[player.getCurrentQ()-1][num].equals
                      (ans1.getText()) && ans1.isSelected())
                          Continue();
                  else if (questions.exactly[player.getCurrentQ()-1][num].equals
                      (ans2.getText()) && ans2.isSelected())
                          Continue();
                  else if (questions.exactly[player.getCurrentQ()-1][num].equals
                       (ans3.getText()) && ans3.isSelected())
                          Continue();
                  else if (questions.exactly[player.getCurrentQ()-1][num].equals
                      (ans4.getText()) && ans4.isSelected())
                          Continue();
                  else if (!ans1.isSelected() && !ans2.isSelected() && !ans3.isSelected() &&
                          !ans4.isSelected()) {
                      try {
                          JOptionPane.showMessageDialog(null, "Devi selezionare una risposta!",
                                  "Attenzione!", JOptionPane.WARNING_MESSAGE);
                      } catch (HeadlessException he) {}
                  }
                  else Break();
              }

  4. #4
    Questa è la continuazione del codice precedente.
    codice:
       private void Continue() {
                  player.addPoints((int)((1000000+((end-start)*500))/((end - start)+1000)));
                  try {
                      if (player.getCurrentQ() < 15)
                          JOptionPane.showMessageDialog(this, "Risposta Esatta!\n" +
                              "Hai totalizzato " + (int)((1000000+((end-start)*500))/((end - start)+1000)) + " punti!\n" +
                              "Adesso hai: " + player.getPoints() + " punti!\n" +
                              "Passiamo alla Domanda " + (player.getCurrentQ() + 1) + "!",
                              "Risposta Esatta!", JOptionPane.INFORMATION_MESSAGE);
                      else {
                          JOptionPane.showMessageDialog(this, "Risposta Esatta! Complimenti! " +
                                  "Hai finito il gioco! Hai vinto! Tu si che sei un vero " +
                                  "intelligente!\n\n" +
                                  "Hai totalizzato " + player.getPoints() + " punti!",
                                  "Complimenti! Hai VINTO!",
                                  JOptionPane.INFORMATION_MESSAGE);
                          destroyGUI();
                          updateLadder();
                          initLadder();
                           try {
                              JOptionPane.showMessageDialog(null,
                                      "  1 - " + topTen[0] + ": " + topTenPoints[0] + "\n" +
                                      "  2 - " + topTen[1] + ": " + topTenPoints[1] + "\n" +
                                      "  3 - " + topTen[2] + ": " + topTenPoints[2] + "\n" +
                                      "  4 - " + topTen[3] + ": " + topTenPoints[3] + "\n" +
                                      "  5 - " + topTen[4] + ": " + topTenPoints[4] + "\n" +
                                      "  6 - " + topTen[5] + ": " + topTenPoints[5] + "\n" +
                                      "  7 - " + topTen[6] + ": " + topTenPoints[6] + "\n" +
                                      "  8 - " + topTen[7] + ": " + topTenPoints[7] + "\n" +
                                      "  9 - " + topTen[8] + ": " + topTenPoints[8] + "\n" +
                                      "10  - " + topTen[9] + ": " + topTenPoints[9]
                                      , "Classifica"
                                      ,JOptionPane.INFORMATION_MESSAGE);
                          } catch (HeadlessException he) {}
                      }
                  } catch (HeadlessException he) {
                  } finally {
                      player.addCurrentQ();
                      MakeGUI((int) questions.getCasualNumber());
                  }
              }
              private void Break() {
                  try {
                      JOptionPane.showMessageDialog(this, "La risposta è sbagliata!" +
                              " Mi dispiace!", "Errore!", JOptionPane.ERROR_MESSAGE);
                  } catch (HeadlessException he) {
                  } finally {
                      destroyGUI();
                      updateLadder();
                      initLadder();
                      try {
                              JOptionPane.showMessageDialog(null,
                                      "  1 - " + topTen[0] + ": " + topTenPoints[0] + "\n" +
                                      "  2 - " + topTen[1] + ": " + topTenPoints[1] + "\n" +
                                      "  3 - " + topTen[2] + ": " + topTenPoints[2] + "\n" +
                                      "  4 - " + topTen[3] + ": " + topTenPoints[3] + "\n" +
                                      "  5 - " + topTen[4] + ": " + topTenPoints[4] + "\n" +
                                      "  6 - " + topTen[5] + ": " + topTenPoints[5] + "\n" +
                                      "  7 - " + topTen[6] + ": " + topTenPoints[6] + "\n" +
                                      "  8 - " + topTen[7] + ": " + topTenPoints[7] + "\n" +
                                      "  9 - " + topTen[8] + ": " + topTenPoints[8] + "\n" +
                                      "10- " + topTen[9] + ": " + topTenPoints[9]
                                      , "Classifica"
                                      ,JOptionPane.INFORMATION_MESSAGE);
                          } catch (HeadlessException he) {}
                  }
              }
              private void destroyGUI() {
                  try {
                      qPanel.removeAll();
                      aPanel.removeAll();
                      APanel.removeAll();
                      remove(qPanel);
                      remove(aPanel);
                      remove(APanel);
                      repaint();
                      setVisible(true);
                  } catch (NullPointerException npe) {
                  }
              }
              public int getTotQ() {
                  Questions testQ = new Questions();
                  return testQ.getTotQ();
              }
              private void initLadder() {
                  int i = 0, a = 0;
                  int pnt = 0;
                  String Str = "";
                  StringTokenizer seq;
                  try {
                      ladder = new FileInputStream("/home/piccettina/workspace/Databases/dbLadder.txt");
                      //Read the file and copy it into Str String variable.
                      do {
                          try {
                              i = ladder.read();
                              if (i != -1) Str += (char) i;
                          } catch (IOException ioe) {}
                      } while (i != -1);
                      seq = new StringTokenizer(Str, "\r\n", false);
                      String instr;
                      while (seq.hasMoreTokens()) {
                          switch (pnt) {
                              case 0:
                                  topTen[a] = seq.nextToken();
                                  pnt = 1;
                                  break;
                              case 1:
                                  topTenPoints[a] = seq.nextToken();
                                  pnt = 0;
                                  if (a < 9) a++;
                                  else break;
                                  break;
                          }
                      }
                  } catch (FileNotFoundException fnfe) {
                      System.out.println("Error: " + fnfe);
                  }
              }
              /*
               *This method update the Ladder
               */
              private void updateLadder() {
                  int i = 0, b = 0, a;
                  String Str = "";
                  FileInputStream fin;
                  PrintStream pw;
                  StringTokenizer st;
                  try {
                      fin = new FileInputStream("/home/piccettina/workspace/Databases/dbLadder.txt");
                      do {
                          i = fin.read();
                          if (i != -1) Str += (char) i;
                      } while (i != -1);
                      i = 0;
                      fin.close();
                      //find the position in the ladder
                      for (a = 0 ; a < 10 ; a++) {
                          try {
                              if (player.getPoints() == 0) {
                                  a = -1;
                                  break;
                              }
                              else if (Integer.toString(player.getPoints()).length() > topTenPoints[a].length())
                                  break;
                              else if (Integer.toString(player.getPoints()).length() < topTenPoints[a].length())
                                  continue;
                              else if (numberCompare(Integer.toString(player.getPoints()),topTenPoints[a]) == 1) {
                                  System.err.println(Integer.toString(player.getPoints()).length());
                                  System.err.println(topTenPoints[a].length());
                                  System.err.println(Integer.toString(player.getPoints()));
                                  System.err.println(topTenPoints[a]);
                                  break;
                              }
                          } catch (NumberFormatException nfe) {}
                      }
                      if (a != -1) {
                      if (a != 0) a *= 4;
                      st = new StringTokenizer(Str, "\n", true);
                      pw = new PrintStream("/home/piccettina/workspace/Databases/dbLadder.txt"");
                      while (st.hasMoreTokens()) {
                          if (a == b) {
                              pw.printf("%s", player.getName());
                              pw.println();
                              //st.nextToken();
                              b++;
                          } else if ((a+1) == b) {
                              pw.printf("%d", player.getPoints());
                              pw.println();
                              //st.nextToken();
                              b++;
                          } else {
                              pw.printf("%s", st.nextToken());
                              b++;
                          }
                      }
                      pw.close();
                  }
                  } catch (IOException ioe) {}
              }
            /**
               *@return 1 if str1 is greater than str2, else -1 if str1 is less str2.
               *Return 0 if two String are equals
               */
              private static int numberCompare(String str1, String str2) {
                  if (Integer.parseInt(String.valueOf(str1.charAt(0))) >
                          Integer.parseInt(String.valueOf(str2.charAt(0))))
                      return 1;
                  else if (Integer.parseInt(String.valueOf(str1.charAt(0))) <
                              Integer.parseInt(String.valueOf(str2.charAt(0))))
                      return -1;
                  else if (Integer.parseInt(String.valueOf(str1.charAt(1))) >
                          Integer.parseInt(String.valueOf(str2.charAt(1))))
                      return 1;
                  else if (Integer.parseInt(String.valueOf(str1.charAt(1))) <
                              Integer.parseInt(String.valueOf(str2.charAt(1))))
                      return -1;
                  else if (Integer.parseInt(String.valueOf(str1.charAt(2))) >
                          Integer.parseInt(String.valueOf(str2.charAt(2))))
                      return 1;
                  else if (Integer.parseInt(String.valueOf(str1.charAt(2))) <
                              Integer.parseInt(String.valueOf(str2.charAt(2))))
                      return -1;
                  else if (Integer.parseInt(String.valueOf(str1.charAt(3))) >
                          Integer.parseInt(String.valueOf(str2.charAt(3))))
                      return 1;
                  else if (Integer.parseInt(String.valueOf(str1.charAt(3))) <
                              Integer.parseInt(String.valueOf(str2.charAt(3))))
                      return -1;
                  else if (Integer.parseInt(String.valueOf(str1.charAt(4))) >
                          Integer.parseInt(String.valueOf(str2.charAt(4))))
                      return 1;
                  else if (Integer.parseInt(String.valueOf(str1.charAt(4))) <
                              Integer.parseInt(String.valueOf(str2.charAt(4))))
                  return -1;
                   return 0;
              }
              public void itemStateChanged(ItemEvent ie) {
               if (settingsFastRBMI.isSelected())
                      isExactly(Num);
    
                  } }

  5. #5
    Questa è un'altra classe del codice,dove il compilatore riscontra degli errori.
    codice:
       1.
          import java.util.Random;
       2.
          import java.util.StringTokenizer;
       3.
          import java.io.*;
       4.
          /**
       5.
           *The class that contain the questions
       6.
           */
       7.
          class Questions {
       8.
              Player player;
       9.
              private int totQ;
      10.
              int qNum[] = new int[15];
      11.
              String questions[][];
      12.
              String answer[][];
      13.
              String exactly[][];
      14.
              FileInputStream db, dbNum, dbTemp;
      15.
              PrintStream dbTemp2;
      16.
              /**
      17.
               *The constructor of class Questions
      18.
               */
      19.
              Questions() {
      20.
                  int k = 1, o;
      21.
                  //Update dbNum.txt and take the total questions.
      22.
                  for (k = 1 ; k < 16 ; k++) {
      23.
                      try {
      24.
                          dbTemp = new FileInputStream("/home/piccettina/workspace/Databases/database" + Integer.toString(k) + ".txt");
      25.
                              do {
      26.
                                  o = dbTemp.read();
      27.
                                  if (o != -1) {
      28.
                                      if ((char) o == ';') totQ++;
      29.
                                  }
      30.
                              } while (o != -1);
      31.
                      } catch (IOException ioe) {}
      32.
                  }
      33.
              }
      34.
              /**
      35.
               *The constructor of class Questions
      36.
               */
      37.
              Questions(Player p) {
      38.
                  int k = 1, o;
      39.
                  byte y;
      40.
                  int count[] = new int[15];
      41.
                  player = p;
      42.
                  //Update dbNum.txt
      43.
                  for (k = 1 ; k < 16 ; k++) {
      44.
                      try {
      45.
                          dbTemp = new FileInputStream("/home/piccettina/workspace/Databases/database" + Integer.toString(k) + ".txt");
      46.
                              do {
      47.
                                  o = dbTemp.read();
      48.
                                  if (o != -1) {
      49.
                                      if ((char) o == ';') count[k - 1]++;
      50.
                                  }
      51.
                              } while (o != -1);
      52.
                      } catch (IOException ioe) {}
      53.
                  }
      54.
                  try {
      55.
                      dbTemp2 = new PrintStream("/home/piccettina/workspace/Databases/dbNum.txt");
      56.
                      for (k = 0 ; k < count.length ; k++) {
      57.
                          dbTemp2.printf("%d", count[k]);
      58.
                          if (k != (count.length - 1))
      59.
                              dbTemp2.printf("%c", ',');
      60.
                      }
      61.
                  } catch (IOException ioe) {}
      62.
                  //Update qNum based on number on dbNum.txt
      63.
                  try {
      64.
                      dbNum = new FileInputStream("/home/piccettina/workspace/Databases/dbNum.txt");
      65.
                      int i = 0, a = 0;
      66.
                      String str = "";
      67.
                      StringTokenizer stNum;
      68.
                      do {
      69.
                          i = dbNum.read();
      70.
                          if (i != -1) str += (char) i;
      71.
                      } while (i != -1);
      72.
                      stNum = new StringTokenizer(str, ",", false);
      73.
                      while (stNum.hasMoreTokens() && stNum.countTokens() > 1) {
      74.
                          qNum[a] = Integer.parseInt(stNum.nextToken());
      75.
                          a++;
      76.
                      }
      77.
                      dbNum.close();
      78.
                  } catch (IOException ioe) {
      79.
                  } catch (NumberFormatException nfe) {}
      80.
                  questions = new String[15][qNum[player.getCurrentQ() - 1]];
      81.
                  answer = new String[15][qNum[player.getCurrentQ() - 1] * 4];
      82.
                  exactly = new String[15][qNum[player.getCurrentQ() - 1]];
      83.
              }
      84.
              /**
      85.
               *This function make a casual number adapt to take a casual question.
      86.
               *@return casual int number
      87.
               */
      88.
              final long getCasualNumber() {
      89.
                  Random a = new Random();
      90.
                  try {
      91.
                      return a.nextInt(qNum[player.getCurrentQ() - 1]);
      92.
                  } catch (ArrayIndexOutOfBoundsException aioobe) {
      93.
                      return -1;
      94.
                  } catch (IllegalArgumentException iae) {
      95.
                      try {
      96.
                          return a.nextInt(qNum[player.getCurrentQ() - 1] + 1);
      97.
                      } catch (ArrayIndexOutOfBoundsException aioobe) {
      98.
                          return -1;
      99.
                      }
     100.
                  }
     101.
              }
     102.
              /*
     103.
              public static int getPreviousQ(int level) {
     104.
                  int pq = 0;     //Previous Questions
     105.
                  for (int a = 0 ; a < level ; a++)
     106.
                      pq += qNum[a];
     107.
                  return pq;
     108.
              }*/
     109.
              /**
     110.
               *This function make the questions and the relatives answers.
     111.
               *@params q - the "questions" object.
     112.
               */
     113.
              void MakeQandA(Questions q) {
     114.
                  int file = 1;
     115.
                  int i = 0;
     116.
                  int numST = 0;
     117.
                  int qu = 0, an = 0, ex = 0;           //questions, answer, exactly
     118.
                  String totStr = "", tempStr = "";
     119.
                  StringTokenizer st;
     120.
                  //Open the files
     121.
                  while (file < 16) {
     122.
                  qu = 0; an = 0; ex = 0;
     123.
                  totStr = ""; tempStr = "";
     124.
                  numST = 0; i = 0;
     125.
                  try {
     126.
                      db = new FileInputStream("/home/piccettina/workspace/Databases/database" + Integer.toString(file) +".txt");
     127.
                  } catch (FileNotFoundException fnfe) {
     128.
                      System.out.println("Error: " + fnfe);
     129.
                  }
     130.
                  //Read the file and copy it into totStr String variable.
     131.
                  do {
     132.
                      try {
     133.
                          i = db.read();
     134.
                          if (i != -1) totStr += (char) i;
     135.
                      } catch (IOException ioe) {}
     136.
                  } while (i != -1);
     137.
                  //Use StringTokenizer to take the question and the relatives answers
     138.
                  st = new StringTokenizer(totStr, ";-_\n", false);
     139.
                  while (st.hasMoreTokens() && st.countTokens() > 1) {
     140.
                      switch (numST) {
     141.
                          case 0:
     142.
                              q.questions[file - 1][qu++] = st.nextToken();
     143.
                              numST++;
     144.
                              break;
     145.
                          case 1:
     146.
                          case 2:
     147.
                          case 3:
     148.
                          case 4:
     149.
                              q.answer[file - 1][an++] = st.nextToken();
     150.
                              numST++;
     151.
                              break;
     152.
                          case 5:
     153.
                              q.exactly[file - 1][ex++] = st.nextToken();
     154.
                              numST = 0;
     155.
                              break;
     156.
                      }
     157.
                  }
     158.
                  try {
     159.
                      db.close();
     160.
                  } catch (IOException ioe) {}
     161.
                  file++;
     162.
                  }
     163.
              }
     164.
              public int getTotQ() {
     165.
                  return totQ;
     166.
              }
     167.
          }

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.