Java: How To Use Arrays - java

I was learning about arrays today in school, and I am trying to do this problem, but cannot figure it
// Fortune Teller
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
public class FortuneTeller extends JFrame
implements ActionListener
{
private static final EasySound ding = new EasySound("ding.wav");
// Declare an array of "fortunes" (strings):
___________________________________________
...
private JTextField display;
public FortuneTeller()
{
super("Fortune Teller");
display = new JTextField(" Press \"Next\" to see your fortune...", 25);
display.setBackground(Color.WHITE);
display.setEditable(false);
JButton go = new JButton("Next");
go.addActionListener(this);
Container c = getContentPane();
c.setLayout(new FlowLayout());
c.add(display);
c.add(go);
}
public void actionPerformed(ActionEvent e)
{
// Pick and display a random fortune:
___________________________________________
...
display.setText(" " + __________________ );
ding.play();
}
public static void main(String[] args)
{
JFrame window = new FortuneTeller();
window.setBounds(300, 300, 300, 100);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(false);
window.setVisible(true);
}
}
I am trying to fill in the blanks.
For the first one,, would it just be just be String [] Fortune;?
But how would I end up initializing it?
And then for the second part, what would I have to do?
Please help as I am extremely lost.

Here are some hints to help you (without actually doing your homework for you).
You can create and populate an array of strings in one line using the following syntax:
String[] colours = {"Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet"};
You can generate a random number between zero and x (inclusive) using the following syntax:
int randomNumber = Math.random() * (x + 1);
You can select a random string from an array with the following syntax:
String randomColour = colours[Math.random() * colours.length];

As found by the simple Google search "How to declare an array in Java":
String[] fortune = {"You're going to be right","You're going to die","You're going to find a cat"};
This also initializes the array.
Then to get the an element of the array, you do:
fortune[1];
//Returns: You're going to die
For this though, I'd do a random number generator to pick a number between 0 and the length of the array:
int value = Math.random() * fortune.length;
fortune[value];

Related

Array input numbers 0-2 and output corresponding letters a,b,c

I have created the array with the elements ("A","B","C")
if the user enters ‘0’ output “A” to the outputlabel,e.g.,outputLabel.setText(array[0]).
I am just getting errors in the command prompt when i enter in the correct numbers. Any help with this would be highly appreciated. I have the gui created correctly. Just unsure about the array and outputs.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GuiFrame extends JFrame implements ActionListener {
String[] stringArray = {"A", "B", "C"};
JTextField inputArea;
JLabel theOutputLabel;
public GuiFrame() {
JPanel panel = new JPanel();
JLabel label1 = new JLabel("Please enter the index of the array to
output: ");
JLabel outputLabel = new JLabel("Array index");
JTextField userInput = new JTextField ();
JButton inputButton = new JButton("Go");
String inputFromUser = userInput.getText();
Container contentPane = getContentPane();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(label1);
panel.add(outputLabel);
panel.add(userInput);
panel.add(inputButton);
inputButton.addActionListener(this);
contentPane.add(panel);
setSize(250, 250);
setVisible(true);
userInput.setSize(250,50);
System.out.println(inputFromUser);
String stringArray[] = new String[3];
}
public static void main(String[] args){
new GuiFrame();
}
#Override
public void actionPerformed(ActionEvent e) {
String userInput = inputArea.getText();
try {
do {
if (e.getActionCommand().equals("0"))
theOutputLabel.setText(stringArray[0]);
if (e.getActionCommand().equals("1"))
theOutputLabel.setText(stringArray[1]);
if (e.getActionCommand().equals("2"))
theOutputLabel.setText(stringArray[2]);
}while(e.getActionCommand().equals("0") || e.getActionCommand().equals("1") || e.getActionCommand().equals("2"));
System.out.println("You have entered a number that is outside of the range of the array index please try again");
}
catch (ArrayIndexOutOfBoundsException arrayError){
System.out.println("Array Index Out of Bounds");
arrayError.printStackTrace();
}
}
}
What you have now defeats the purpose of using an array. Imagine you had to do it for all letters of the Alphabet, would you add 26 conditions? What if you have thousands of options?
Thererfore, instead of
/** DON'T DO THIS */
if (e.getActionCommand().equals("0"))
theOutputLabel.setText(stringArray[0]);
if (e.getActionCommand().equals("1"))
theOutputLabel.setText(stringArray[1]);
if (e.getActionCommand().equals("2"))
theOutputLabel.setText(stringArray[2]);
You should parse the input and get element from the array according to the index.
/** DO THIS */
int index = Integer.parseInt(e.getActionCommand());
theOutputLabel.setText(stringArray[index]);
Integer.parseInt() could throw a java.lang.NumberFormatException if the input is not a valid integer, so you have to add a catch for that.
If you want to have the index available for test in the while condition, then declare it without initializing before the do block.
Hey apart from what #isapir has suggested also please check that there are few places in your code that would result into NullPointerExceptions like :
JTextField inputArea; // Not assigned will lead to NPE
JLabel theOutputLabel; // Not assigned will lead to NPE
String userInput = inputArea.getText(); // Because of inputArea unassigned this line will throw NPE for sure so fix that as well.
So I'm assuming what exception you were getting in cmdPrompt would be NPE one so better fix your basic bug first and check your constructor code properly. Lastly, it's always better to share the exception details before post questions on SO.
e.getActionCommand().equals("0") this line will not give what you have entered in frame pop-up. Check this also instead use inputArea.getText() will give you user's entered number digit.

How to set JButton to change color gradually when clicked

I wanted to create JButton to change color every time it is clicked but it doesn't change after second click.
It is strange because with Random().nextInt(250) instead of i it works.
What could be the problem?
Here's the code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main {
public static void main(String[] args) {
JFrame jf = new JFrame();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel jp = new JPanel();
jp.setLayout(new BorderLayout(100, 100));
JButton l = new JButton("Hello");
l.setBackground(new Color(245, 12, 53));
jp.add(l, BorderLayout.EAST);
jf.add(jp);
jf.setSize(200, 200);
jf.setLocationRelativeTo(null);
jf.setVisible(true);
l.addActionListener(new ActionListener() {
Integer i = new Integer(0);
Color c = new Color(150, 10, i);
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (i < 200) {
i += 50;
c = new Color(150, 10, i);
l.setBackground(c);
} else
i = 0;
}
});
}
}
I debugged your code and saw that the value of c change, every time I click the button. The first value is (r=150,g=10,b=50), then turns into (r=150,g=10,b=100), then (r=150,g=10,b=150) etc.
This means that the color is indeed changing. It's just that the difference is too small for you to notice.
So why does random.nextInt work?
With a random value in the blue component. The value can jump very suddenly from 0 to 200. The color difference is so large that your eyes can see it. But with a gradual change of 50 every time, you only notice it the first time.
Just test it with new Color(0, 0, i). I think that will make a bigger difference. It will go from black to blue!
Works fine for me.
Although the code should probably be something like:
if (i < 200)
i += 50;
else
i = 0;
c = new Color(150, 10, i);
l.setBackground(c);
Otherwise there will be one click that doesn't change the color.
You may want to consider using HSL Color this will allow you to change the Color in a more meaningful way by either changing the hue of the Color or shade/tone of the Color.

Issues creating java GUI with while loop

I am creating a java GUI which is a fortune teller. The GUI will spit out one of twelve fortunes every time you click the "get my fortune" button, the strings will never repeat back to back, can can repeat later after other strings have gone before it. I have made already for the most part. But now I am having some trouble creating the while loops to display the strings without repeating. I have looked at my book which didn't really help. If you guys could point me in the right direction,it would be much appreciated. Thanks!
I entered all of the code so you can see the variables used. But my question starts at class RndButtonListener.
package FortuneTellerRunner;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
/**
*
* #author a3cal_000
*/
class FortuneTellerFrame extends JFrame
{
final private JPanel mainPnl, titlePnl, displayPnl, buttonPnl, imagePnl;
final private JButton quitBtn, rndBtn;
final private JLabel titleLbl, iconLbl;
final private JTextArea displayTa;
final private JScrollPane scroller;
public String[] fortune = new String [12];
int newIndex, oldIndex;
private static final int HEIGHT = 250;
private static final int WIDTH = 450;
public FortuneTellerFrame()
{
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPnl = new JPanel();
mainPnl.setLayout(new BorderLayout());
displayPnl = new JPanel();
buttonPnl = new JPanel();
titlePnl = new JPanel();
ImageIcon icon = new ImageIcon("FortuneTellerIcon.JPEG");
iconLbl = new JLabel(icon);
titleLbl = new JLabel("Fortune Teller!");
displayTa = new JTextArea();
imagePnl = new JPanel();
scroller = new JScrollPane();
// Create the layout of the title panel
titlePnl.setLayout(new GridLayout(2,1));
add(mainPnl);
// Set the label to the panel.
titlePnl.add(titleLbl);
titlePnl.add(iconLbl);
// add the panel to the main panel.
mainPnl.add(titlePnl, BorderLayout.NORTH);
mainPnl.add(scroller, BorderLayout.CENTER);
mainPnl.add(displayTa, BorderLayout.CENTER);
// Create the "Get my fortune button.
rndBtn = new JButton("Get My Fortune!");
quitBtn = new JButton("Quit");
// Add the buttons to the buttonPnl in grid layout.
buttonPnl.add(rndBtn);
buttonPnl.add(quitBtn);
// Create the grid layout for the button panel.
buttonPnl.setLayout( new GridLayout(1, 2));
// Add the button panel to the grid layout, South.
mainPnl.add(buttonPnl, BorderLayout.SOUTH);
ActionListener listener = new RndButtonListener();
rndBtn.addActionListener(listener);
quitBtn.addActionListener(listener);
}
class RndButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
fortune[0] = "He who throws dirt is losing ground.";
fortune[1] = "You will find the love of your life in food.";
fortune[2] = "Do or do not, there is no try.";
fortune[3] = "Tomorrow is a better day to try anything of importance.";
fortune[4] = "Life's not about how hard you can hit, but how hard you can get hit and keep moving forward.";
fortune[5] = "You can't be late until you show up.";
fortune[6] = "If you think things can't get worse it's probably only because you lack sufficent imagination.";
fortune[7] = "If youre at the top it means you have further to fall.";
fortune[8] = "Even in last place, youre still in the race.";
fortune[9] = "The road to riches is paved on the failures of others.";
fortune[10] = "If you feel like your going no where, get off the treadmill.";
fortune[11] = "Thinking about going to the gym is just as good as going.";
Random rnd = new Random(fortune.length);
do
{
newIndex = rnd.nextInt(fortune.length);
}
while(newIndex == oldIndex);
do
{
System.out.println(fortune[newIndex]);
displayTa.append(fortune[newIndex] + "||");
displayTa.updateUI();
mainPnl.updateUI();
oldIndex = newIndex;
}
while(newIndex != oldIndex);
class QuitButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
System.exit(0);
}
}
}
}
}
The basic problem is you are re-creating the Random with the same seed each time, which is generally creating the same random sequence over and over again.
Instead try using...
do {
newIndex = (int) Math.round(Math.random() * (fortune.length - 1));
} while (newIndex == oldIndex);
You also don't need the second loop, it's just clutter that confuses the situation.
You may also find that...
displayTa.append(fortune[newIndex] + "\n");
produces nicer output (IMHO)
You may also wish to take a look at How to use Scroll Panes
Your program run fine, but this is a problem, fortune.length is a random seed which return me only 6 and 8 when I later called Random.nextInt().
Random rnd = new Random(fortune.length);
Do it this way
Random rnd = new Random();
and also consider the formatting solution given by MadProgrammer.
Random() gives you same number pattern. Try Random(System.currentTimeMillis()). It uses current time as seed, so you can get real random numbers.
I did something similar to this just today, so let's see if I can remember... I made an ArrayList of type int of how many items I had (fortunes)
ArrayList<Integer> fortuneSeq = new ArrayList<Integer>();
Then add in some numbers starting from 0 to code for the fortunes.
for(int i = 0; i < fortune.length; i++) {
fortuneSeq.add(i);
}
Then I used the shuffle() method from the Collections class to randomize the list.
Collections.shuffle(fortuneSeq);
After that, just loop through to access the fortunes.
for(int i = 0; i < fortune.length; i++) {
System.out.println(fortune[fortuneSeq.get(i)]);
//...
}
Edit: Silly autocorrect, you don't like programmers.
Edit: Fixed some furtunes instead of fortunes and fixed println statement.

Selection sort without a loop [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
For this program I want to implement an array of sorting and searching algorithms. The array will be filled with random numbers. Then I want to draw each array element as a bar (making something like a bar graph). I have a step and run button in the GUI the step is supposed to use selection sort. The problem I am having is: I only know how to do selection sort with a loop. However, I can not use a loop because I have to show the array being sorted step by step. Can anyone show me how to do selection sort without a loop? I will be adding all of the code I have so far because this is my first time posting anything, and I want to make sure I am specific.
ArrayViewer:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.util.Scanner;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ArrayViewer
{
static int[] array;
static int size;
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
//ask for the size of the array until the user enters a size in the right range
do
{
System.out.print("Enter the size of the array (should be between 10 and 80): ");
size=in.nextInt();
}
while (size<10 || size>80);
array= ArrayUtil.randomIntArray(size,100);//create a random array of given size and entries ranging from 0 to 100
final ArrayComponent arrayComp= new ArrayComponent(array); //construct an arrayComponent with the random array
class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//I want the selection sort algorithm to go in here so I can just assign this to my stepButton.
}
}
final JFrame frame=new JFrame("Sorting"); //create and setup the frame
frame.setSize(1200,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel buttonPanel= new JPanel(); // panel to hold the buttons
JPanel panel=new JPanel(new BorderLayout()); // panel to hold the button panel and the array component; uses BorderLayout: read about it in the API
JButton stepButton=new JButton("Step"); //button to go through the algorithm step by step
JButton runButton=new JButton("Run"); //button to run the algorithm
ActionListener listener = new ButtonListener();
stepButton.addActionListener(listener);
buttonPanel.add(stepButton);
buttonPanel.add(runButton);
panel.add(buttonPanel,BorderLayout.PAGE_START); //add the buttonPanel at the top of the panel
panel.add(arrayComp,BorderLayout.CENTER); //add the arraycoponent object in the center of teh panel
frame.add(panel);
frame.setVisible(true);
//print the entries in the array
//System.out.println(arrayComp);
}
}
ArrayComponent:
import javax.swing.JComponent;
import java.awt.Rectangle;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Dimension;
import java.awt.Color;
public class ArrayComponent extends JComponent
{
private int[] theArray;
final int dx=6; //the width of thebars (as well as the with of the spaces between bars)
private int space=0;
int index1 =0;
int index2 =0;
public ArrayComponent(int[] a)
{
theArray=a;
space=600-12*theArray.length/2; //space amount on the horizontal axes to center the graph
//600 is the frame width in the viewer program
//For each bar 12 units on the horixzontal axis is used including the space following it.
//something.addActionListener(new ButtonListener());
}
public void setIndices(int i, int j)
{
index1 = i;
index2= j;
}
public void paintComponent(Graphics g)
{
Graphics2D pen= (Graphics2D) g;
for (int k=0;k<theArray.length;k++)
{
pen.drawRect(space+2*k*dx,5,dx,theArray[k]);
//space: initial space
//2*k*dx: the (horizontal) distance of te kth bar from the start of the graph
//5: bars are located on y=5
//dx: the width of the bars
//theArray[k]: height of the kth bar
}
pen.fillRect(space+2*index1*dx,5,dx,theArray[index1]);
pen.fillRect(space+2*index2*dx,5,dx,theArray[index2]);
}
public String toString()
{
String str=("array=[");
int k=0;
for (k=0;k<theArray.length-1;k++)
str=str+theArray[k]+", ";
str=str+theArray[k]+"]";
return str;
}
}
ArrayUtil(creates the random array):
import java.util.Random;
/**
This class contains utility methods for array manipulation.
*/
public class ArrayUtil
{
private static Random generator = new Random();
/**
Creates an array filled with random values.
#param length the length of the array
#param n the number of possible random values
#return an array filled with length numbers between
0 and n - 1
*/
public static int[] randomIntArray(int length, int n)
{
int[] a = new int[length];
for (int i = 0; i < a.length; i++)
a[i] = generator.nextInt(n);
return a;
}
}
Sorry if the post is lengthy. The program already draws the arrays, it just does not sort them. Thanks for the help.
Let activeIndex refer to the index of the array element to be sorted next (starting with value 0).
Write a method, say stepSelectionSort, which will execute only the one step of selection sort and return. The sorting begins at array[activeIndex].
{5,4,3,2,1} -> activeIndex=0 -> Step.click -> stepSelectionSort() sorts array element at 0 -> {1,4,3,2,5} -> draw() -> activeIndix=1 -> Step.click -> stepSelectionSort() sorts array element 1.
Temporarily write code to do full sort inside a loop
Take all code within the loop and put it in a method
Remove the loop & call the method once each time the user clicks "Step" GUI button

How to create an array by inputting numbered into a textfield, Java applet

My assignment is to input 20 numbers via a text field then out the mean, the median and the total using a while loop. I should be able to figure out the while loop myself, but I can't get the text field to input numbers into an array. Please help, here is my code so far:
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.*;
import java.awt.event.*;
public class whileloopq extends Applet implements ActionListener
{
Label label;
TextField input;
int[] numArray = new int[20];
int num;
public void init ()
{
Label label = new Label("Enter numbers");
TextField input = new TextField(5);
add(label);
add(input);
input.addActionListener(this);
}
public void actionPerformed (ActionEvent ev)
{
int num = Integer.parseInt(input.getText());
int index = 0;
numArray[index] = num;
index++;
input.setText("");
}
public void paint (Graphics graf)
{
graf.drawString("Array" + numArray, 25, 85);
}
}
Any help would be much appreciated.
(Answer written under the assumption that this is a homework assignment.)
You know how to parse an integer from a string, as you show with your usage of Integer.parseInt, but you are calling it to parse the entire 20 characters as one integer. You need to get each character individually to be parsed.
I recommend using a for loop, and String#substring to substring the input text into several strings of length one.
Alternatively, you can split the input text around an empty string and then iterate through the resulting array (note that the first string in the array will be empty), but the other approach is more likely the one expected from someone new to Java, so you'll have to use your judgement here.
In actionPerformed() you are trying to read from class filed input.setText("");
but in init() you didn't initialized that field but created and added to applet local variable
TextField input = new TextField(5);
so class field is steal null. Change it to
input = new TextField(5);
import java.awt.*;
public class frame4array extends Frame
{
Checkbox c1[];
TextField t1[];
int i;
frame4array(String p)
{
super(p);
c1=new Checkbox[2];
t1=new TextField[2];
for(i=0;i<2;i++)
{
t1[0]=new TextField();
t1[0].setBounds(200, 50, 150, 30);
t1[1]=new TextField();
t1[1].setBounds(200, 80, 150, 30);
c1[0]=new Checkbox("Singing");
c1[0].setBackground(Color.red);
c1[0].setBounds(430,200,120,40);
c1[1]=new Checkbox("Cricket",true);
}
for(i=0;i<2;i++)
{
add(t1[i]);
add(c1[i]);
}
setFont(new Font("Arial",Font.ITALIC,40));
}
public static void main(String s[])
{
frame4array f1=new frame4array("hello");
f1.setSize(600,500);
f1.setVisible(true);
}
}

Categories

Resources