2013-12-15 2 views
0

Привет, ребята, я делаю программу, которая помогает мне учиться (машина для флеш-карт). В основном это многомерный массив строк, в котором содержится вопрос и его ответ. Первый вызов, который я сделал, - найти способ случайного выбора вопроса. То, что я сделал, я сделал еще один целочисленный массив, где я перетасовал его при запуске. что мне нужно сделать сейчас, используется массив integer для отображения моего массива многомерных массивов. например. Допустим, мой массив int начался следующим образом {1,2,3,4}. Перемешивая его, он изменился на {3,1,2,4}. Теперь я хочу использовать этот целочисленный массив, как это. ArrayOfQuestionsAndAnswers [IntegerArray [0]] [0], чтобы задать вопрос. То, что я не знаю, как это сделать, - это получить один вопрос за раз. Каждый раз, когда нажимается кнопка, массив Integer должен сделать свой следующий int (это будет 1 в моем примере.) Как я могу это сделать?Как медленно итерации по массиву

Мой код до сих пор:

Основной класс:

public class Core { 

    public static void main(String[] args){ 
     if(Variables.getStart()){ 
      shuffleArray(Variables.getCardNumber()); 
      Variables.setStart(false); 
     } 
    } 
    public static String getCardQuestion(){ 
     return Variables.getCards()[0][0]; 
    } 
    public static String getCardAnswer(){ 
     return Variables.getCards()[0][1]; 
    } 
    // Implementing Fisher–Yates shuffle 
    static void shuffleArray(int[] ar) 
    { 
     Random rnd = new Random(); 
     for (int i = ar.length - 1; i > 0; i--) 
     { 
      int index = rnd.nextInt(i + 1); 
      // Simple swap 
      int a = ar[index]; 
      ar[index] = ar[i]; 
      ar[i] = a; 
     } 
    } 

} 

Variable Класс:

public class Variables { 
     private static int[] cardNumber ={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20}; 
     private static String[][] cards = {{"Apostolic Orgin", "Comes form the apostles"}, 
       {"Biblical inerrancy", "the doctrine that the books are free from error reading the truth"}, 
       {"Divine Inspiration", "the assistance the holy spirit gave the authors or the bible so they could write"}, 
       {"fundamentalist approach", "interpretation of the bible and christian doctrine based on the literal meaning og bible's word"}, {"pentateuch", "first 5 books of old testament"}, 
       {"Torah","Means law, refers to first 5 books of the old testament"},{"Sacred Scripture","The bible/approved list of Judism and Christianity"}, 
       {"Apostolic Succession","passing on of apostolic preaching and authority from apostles to all bishops"}, 
       {"encumenical council","gathering of bishops form around the world to address issues of the church"}, 
       {"Breviary","prayer book that contains the prayers for litergy of the hours"}}; 
     private static boolean start=true; 
     private static int index; 

     public static void setIndex(int i){ 
      index=i; 
     } 
     public static int getIndex(){ 
      return index; 
     } 
     public static void setCardNumber(int[] i){ 
      cardNumber=i; 
     } 
     public static int[] getCardNumber(){ 
      return cardNumber; 
     } 
     public static void setCards(String[][] i){ 
      cards=i; 
     } 
     public static String[][] getCards(){ 
      return cards; 
     } 
     public static void setStart(boolean i){ 
      start=i; 
     } 
     public static boolean getStart(){ 
      return start; 

     } 
    } 

Basic (незавершенные) GUI classs:

import study.religion.firstfinal.core.Core; 

import java.awt.EventQueue; 

import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.border.EmptyBorder; 
import java.awt.event.ActionListener; 
import java.awt.event.ActionEvent; 

public class GUI extends JFrame { 

    private JPanel contentPane; 

    /** 
    * Launch the application. 
    */ 
    public static void main(String[] args) { 
     EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       try { 
        GUI frame = new GUI(); 
        frame.setVisible(true); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
     }); 
    } 

    /** 
    * Create the frame. 
    */ 
    public GUI() { 
     setTitle("Bautista's Religion Review"); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setBounds(100, 100, 450, 300); 
     contentPane = new JPanel(); 
     contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); 
     setContentPane(contentPane); 
     contentPane.setLayout(null); 

     final JLabel label = new JLabel(""); 
     label.setBounds(32, 22, 356, 160); 
     contentPane.add(label); 

     JButton btnShowQuestion = new JButton("Show Question"); 
     btnShowQuestion.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
      label.setText("Question: "+Core.getCardQuestion()); 
      } 
     }); 
     btnShowQuestion.setBounds(62, 216, 121, 23); 
     contentPane.add(btnShowQuestion); 

     JButton btnShowAnswer = new JButton("Show Answer"); 
     btnShowAnswer.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
      label.setText("Answer: "+Core.getCardAnswer()); 
      } 
     }); 
     btnShowAnswer.setBounds(244, 216, 121, 23); 
     contentPane.add(btnShowAnswer); 
    } 

} 
+0

, что и означает, как медленно перебирать массив? –

+0

Вы ищете что-то, управляемое 'events'. Пользователь, нажимая кнопку, является «событием», которое вам нужно «прослушать», а затем выполнить код после. – Houseman

ответ

0

Может вы не просто создаете метод, называемый nextQuestion() в вашем классе Core, который увеличивает счетчик внутри класса?

Добавить целое в класс ядра, как, например:

public class Core { 

    private int counter = 0; 

Затем добавить метод в классе ядра, как, например:

public void nextQuestion(){ 
    counter++; 
} 

Измените getCardQuestion() и getCardAnswer() к:

public static String getCardQuestion(){ 
    return Variables.getCards()[counter][0]; 
} 

public static String getCardAnswer(){ 
    return Variables.getCards()[counter][1]; 
} 

Возможно, добавьте кнопку, которая перейдет к следующему вопросу, и добавьте ActionL который вызывает nextQuestion().

Обратите внимание, что метод nextQuestion() будет продолжать увеличиваться без проверки границ массива. Если вы хотите nextQuestion(), чтобы перевернуться и начать снова изменить заявление, например:

counter = (counter + 1) % Variables.getCards().length; 
0

В классе GUI выполните следующие действия decleration

private int[] RandomInteger = {1,2,3,4} 
private int i,j 

Тогда, как вы говорите, перемешайте его.

Сейчас в nextbutton ActionListener вы можете сделать что-то подобное

if(i < RandomInteger.length()) 
{ 
    ArrayofQuesiontAndAnswer(randominteger[i++])[j++] //declare i and j as a class member 
} 

Надежда это поможет

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