Balla Baby Balla Baby - 3 years ago 149
Java Question

Random string from array, can't have two same strings chosen in succession of each other Java

I'm having an issue figuring out what the best way to go about appending a random String element from my array into the JTextArea may be. My problem is that I can't have the same two strings from my array output in succession of each other. (can't be the same as the last presented). I've tried while true loops, for loops. I'm just not quite sure how to write this constraint. Any pointers in the right direction would be appreciated. Been at this issue for a while and I've scowered stackoverlow top to bottom. My code runs fine now but the problem I've encountered is in the createBottomPanel() method within the btnSubmit actionlistener. Thanks

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;
}


}

Answer Source

If I understand correct and each answer may occur multiple times, but not in direct succession, the easiest approach would be to remember the last fortune and skip if it occurs twice:

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" );
    }
}

And in createBottomPanel():

btnSubmit.addActionListener( new FortuneAppenderAction() );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download