2017-09-30 2 views
0

내가 가장 좋은 방법은 될 수있는 JTextArea에로 내 배열에서 임의의 문자열 요소를 추가 가야할지 알아내는 문제에 봉착의 연속 선택이 같은 문자열을 가질 수 없습니다 . 내 문제는 내 배열 출력에서 ​​동일한 두 문자열을 연속적으로 가질 수 없다는 것입니다. (마지막으로 제시된 것과 같을 수 없다). 나는 진짜 루프 동안, 루프를 위해 노력했다. 이 제약 조건을 어떻게 작성해야할지 모르겠습니다. 올바른 방향으로 향한 어떤 포인터라도 감사 할 것입니다. 이 이슈에 잠시 동안 머물렀고 맨 아래로 stackoverlow를 내 렸습니다. 내 코드가 지금은 잘 실행되지만 내가 만난 문제는 createBottomPanel() 메서드에서 btnSubmit actionlistener 내에 있습니다. 감사합니다임의의 문자열은 서로 자바

package Tell; 

import java.awt.*; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.image.BufferedImage; 
import java.io.File; 
import java.io.IOException; 
import javax.imageio.ImageIO; 
import javax.swing.*; 
import java.util.Random; 

public class FortuneTellerFrame extends JFrame { 

JPanel pnlTop, pnlMiddle, pnlBottom; 
JButton btnSubmit, btnQuit; 
JLabel lblFortuneTeller, lblPassword; 
JTextArea txaResults; 
JScrollPane jsp; 
String[] fortunes = {"A loved one will die","You will recieve a gift", 
    "A mysterious person will come into your life","You will encounter misfortune soon", 
    "Life will become easier for you","Sadness will overcome you", 
    "Good tidings are in your future","Some sum of money will find its way to you", 
    "Good news is around the corner","Persevere and you shall be rewarded", 
    "You will run out of time at a bad moment","You will fall and break a leg"}; 

public FortuneTellerFrame() { 
    add(this.createTopPanel(), BorderLayout.NORTH); 
    add(this.createMiddlePanel(), BorderLayout.CENTER); 
    add(this.createBottomPanel(), BorderLayout.SOUTH); 

    // Always set the size of data and the default close operation. 
    // Visibility needs to be set to true to be seen as well 
    this.setSize(400, 300); 
    this.setVisible(true); 
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 


    } 
    private JPanel createTopPanel() 
    { 
     pnlTop = new JPanel(); 
     pnlTop.setLayout(new GridLayout(2,2)); 
     ImageIcon icon = new ImageIcon("ball.jpg"); 
     Image image1 = icon.getImage(); // transform it 
     Image newimg = image1.getScaledInstance(75, 75, java.awt.Image.SCALE_SMOOTH); 
     icon = new ImageIcon(newimg); // transform back 
     JLabel label = new JLabel("Fortune Teller",icon,JLabel.CENTER); 
     label.setForeground(Color.red); 
     label.setFont(new Font ("Lucida Sans Unicode", Font.BOLD, 20)); 
     label.setHorizontalTextPosition(JLabel.CENTER); 
     label.setVerticalTextPosition(JLabel.BOTTOM); 

     pnlTop.add(label); 

     return pnlTop; 
    } 

    private JPanel createMiddlePanel() 
    { 
     pnlMiddle = new JPanel(); 
     txaResults = new JTextArea(10, 30); 
     txaResults.setFont(new Font ("Serif", Font.ITALIC, 10)); 
     jsp = new JScrollPane(txaResults,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, 
       JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); 
     pnlMiddle.add(jsp); 

     return pnlMiddle; 
    } 
    private JPanel createBottomPanel() 
    { 

     pnlBottom = new JPanel(); 
     btnSubmit = new JButton("Read My Fortune!"); 
     btnQuit = new JButton("Quit"); 
     btnSubmit.setFont(new Font ("Arial", Font.BOLD, 9)); 
     btnQuit.setFont(new Font ("Arial", Font.BOLD, 9));  

     btnQuit.addActionListener(e ->{ 
      System.exit(0); 
     }); 

     btnSubmit.addActionListener(e ->{ 
      //String username = this.txtFortuneTeller.getText(); 

      Random rand = new Random(); 
      String x = fortunes[rand.nextInt(fortunes.length)]; 

      this.txaResults.append(x + "\n"); 
     }); 

     pnlBottom.add(btnSubmit); 
     pnlBottom.add(btnQuit); 

     return pnlBottom; 
    } 

}

+2

왜 무작위하지 ​​운명 (한 번)을 그런 다음 반복하십시오. –

+0

'Collections.shuffle (Arrays.toList (fortunes))'가 그것을 할 것입니다. –

+0

@AndyTurner 나는 코드를 다음과 toList 방법에 대한 찾을 수 없습니다 기호 오류가 계속. 목록 및 배열 라이브러리를 가져 왔지만 어떤 이유로 든 여전히 오류가 발생합니다. 유형과 관련이있을 수 있습니까? 내 배열 요소는 문자열 –

답변

0

내가 올바른 이해하고 각각의 대답은 여러 번 발생할 수 있지만, 두 번 발생하면 직접 연속적으로, 가장 쉬운 방법은 마지막 재산을 기억하고 건너 뛸 것하지 않으면 :

class FortuneAppenderAction implements ActionListener { 

    private String lastFortune = null; 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     Random rand = new Random(); 
     String x; 
     do { 
      x = fortunes[rand.nextInt(fortunes.length)]; 
     } 
     while (x.equals(lastFortune)); 
     lastFortune = x; 
     txaResults.append(x + "\n"); 
    } 
} 

그리고 createBottomPanel()에서 :

btnSubmit.addActionListener(new FortuneAppenderAction());