11 Replies - 1870 Views - Last Post: 08 December 2011 - 07:42 AM Rate Topic: -----

#1 AlexAndAHalf   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 22-November 11

Need to condense if-statements

Posted 07 December 2011 - 11:26 PM

Hey everyone! I'm working on my final program for my Intro to Java class for the semester. Essentially, the program I thought of is supposed to have a JLabel at the top saying "I can tell you the colors of certain fruits!", a JComboBox that contains the names of 5 fruits, and a JButton. When the user selects a fruit from the JComboBox and presses the button, a JLabel is added that says "<selected fruits> are <respective color>!". In addition to that, the JLabel that is added when the button is pressed is supposed to be set to the color of the fruit. THAT is where my problem lays. As of right now, I simply have five if-statements (one for each fruit) that determine which fruit is selected, and set the color using the setForeground() method. I would really like to condense these if-statements somehow, but I truly don't know how! I was thinking maybe I could create a container array that is parallel to the fruit and color arrays, but I don't even know if a container array is possible to make!

Help is VERY much appreciated!

Here is my code:

import javax.swing.*;
import java.awt.Color;
import java.awt.*;
import java.awt.event.*;

//The class extends JFrame for GUI purposes, and implements ActionListener
//so events can take place within the JFrame.
public class FinalProject extends JFrame implements ActionListener
{
	//First, I declare GUI elements: the JLabel that lets the user know what the program does,
	//my choice of font, the "Submit Fruit" button that the user will press
	//once they have selected their fruit, and a place holder label that will eventually
	//display a final message.
	JLabel label = new JLabel("I can tell you the colors of certain fruits!");
	Font font = new Font("Times New Roman", Font.BOLD, 20);
	JButton submit = new JButton("Submit Fruit");
	JLabel lastLabel = new JLabel(" ");
	
	//The following two parallel arrays contain the selection of fruits and their respective colors.
	String[] fruit = {"Apples", "Bananas",  "Blueberries", "Limes", "Oranges"};
	String[] color = {"red", "yellow",  "blue", "green", "orange"};
	
	//Now the JComboBox is created, and the fruit array is used as an argument so that the fruits
	//will all appear in the drop down menu.  Also, constants that will be used for the width and height
	//of the JFrame are also declared.
	JComboBox fruitChoice = new JComboBox(fruit);
	final int WIDTH = 425;
	final int HEIGHT = 200;
	Container con = getContentPane();
	
	//Here is where the constructor is formed, and all necessary elements will be added.
	public FinalProject()
	{
		super("Final Program");
		//First, the size of the JFrame is set, default close operation is set to exit on close,
		// the layout is set, and the font of the first label is set.
		setSize(WIDTH, HEIGHT);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setLayout(new FlowLayout());
		label.setFont(font);
		//Now the GUI components will be added, adding an action listener to the submit button
		//so that it can trigger an event.
		con.add(label);
		con.add(fruitChoice);
		con.add(submit);
		submit.addActionListener(this);
	}
	public void actionPerformed(ActionEvent e)
	{
		int index = fruitChoice.getSelectedIndex();
		for(int x = 0; x < 5; x++)
		{
			if(x == index)
			{
				lastLabel.setText(fruit[x] + " are " + color[x]);
				lastLabel.setFont(font);
				
				if(x == 0)
				{
					lastLabel.setForeground(Color.RED);
				}
				if(x == 1)
				{
					lastLabel.setForeground(Color.YELLOW);
				}
				if(x == 2)
				{
					lastLabel.setForeground(Color.BLUE);
				}
				if(x == 3)
				{
					lastLabel.setForeground(Color.GREEN);
				}
				if(x == 4)
				{
					lastLabel.setForeground(Color.ORANGE);
				}
				
				con.add(lastLabel);
			}
		}
		invalidate();
		validate();
	}
	public static void main(String[] args)
	{
		FinalProject frame = new FinalProject();
		frame.setVisible(true);
	}
}




Is This A Good Question/Topic? 0
  • +

Replies To: Need to condense if-statements

#2 AlexAndAHalf   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 22-November 11

Re: Need to condense if-statements

Posted 07 December 2011 - 11:33 PM

Sorry for the excessive comments by the way, kind of part of the assignment haha
Was This Post Helpful? 0
  • +
  • -

#3 Sheph   User is offline

  • D.I.C Lover
  • member icon

Reputation: 447
  • View blog
  • Posts: 1,032
  • Joined: 12-October 11

Re: Need to condense if-statements

Posted 07 December 2011 - 11:40 PM

There is something wrong here. First you set index to the selected fruit. then you loop through each fruit and see if it matches the index. What's the point?
if( index == 0 ) {
  //setForeground(RED)...
}
Furthermore, have you ever heard of a switch statement?
switch(index) {
case 1:
    // if(index==1)
    lastLabel.setForeground( Color.RED );
    break;
case 2:
    //ect.
    break;
}

Was This Post Helpful? 1
  • +
  • -

#4 AlexAndAHalf   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 22-November 11

Re: Need to condense if-statements

Posted 07 December 2011 - 11:45 PM

Thank you for responding!

The point is to determine which fruit the user has selected, and to set the color of the outputted text to the color of that fruit. Is there a better way to do this?

Also, I have personally heard of a switch statement, but I would be unable to use it in this program because we have not learned about them in the class. We're supposed to stick to what the book has covered unfortunately, thank you for the input though!
Was This Post Helpful? 0
  • +
  • -

#5 Sheph   User is offline

  • D.I.C Lover
  • member icon

Reputation: 447
  • View blog
  • Posts: 1,032
  • Joined: 12-October 11

Re: Need to condense if-statements

Posted 07 December 2011 - 11:52 PM

What I meant was, how is your code different than just doing this:
if( index == 1 ) {
    lastLabel.setForeground( Color.RED );
} else if( index == 2 ) {
    lastLabel.setForeground( Color.YELLOW );
} else if( index == 3 ) {
    lastLabel.setForeground( Color.BLUE );
} else if( index == 4 ) {
    lastLabel.setForeground( Color.GREEN );
} else if( index == 5 ) {
    lastLabel.setForeground( Color.ORANGE );
}
I mean, the for loop doesn't really accomplish anything. You are basically saying for x = 0 to x = 5, if x == index, (which can only happen in 1 of the iterations)... then you say if ( x == 0 ) ... which MUST be the same as if (index == 0). So you iterate 5 times for nothing.
Was This Post Helpful? 0
  • +
  • -

#6 AlexAndAHalf   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 22-November 11

Re: Need to condense if-statements

Posted 07 December 2011 - 11:55 PM

Well that's part of the problem I'm posting about...I need a way to incorporate those if-statements into my loop so I can eliminate them and replace them with a single statement in my loop, because (for the reasons you mentioned) I would get points taken off if it is left how it is.

If you have a suggestion of how I can do this, I would be very happy to hear it!
Was This Post Helpful? 0
  • +
  • -

#7 AlexAndAHalf   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 22-November 11

Re: Need to condense if-statements

Posted 08 December 2011 - 12:04 AM

Sorry, that last post was kind of vague, let me clarify:

I need to replace all five if-statements with a single statement that will set the color of the text to the appropriate color of the selected fruit. Basically, I need a way to set the color of my label to the color in the "color" array that is equal to index. Sorry, this is all very hard to explain in text haha.
Was This Post Helpful? 0
  • +
  • -

#8 Sheph   User is offline

  • D.I.C Lover
  • member icon

Reputation: 447
  • View blog
  • Posts: 1,032
  • Joined: 12-October 11

Re: Need to condense if-statements

Posted 08 December 2011 - 12:05 AM

Well, normally I wouldn't advocate the use of parallel arrays, but seeing as you probably haven't started object oriented programming, it like seems a logical solution.
Color[] fruitColors = { Color.RED, Color.YELLOW, Color.BLUE, Color.GREEN, Color.ORANGE };
// in actionPerformed()
lastLabel.setForeground( fruitColors[index] );
I still see no reason to have a for loop in there. On a side note, seeing as java is an object oriented programming language, I think it would benefit you greatly if you learned about OO design on your own free time. ( if you have any ;) )
Was This Post Helpful? 2
  • +
  • -

#9 AlexAndAHalf   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 22-November 11

Re: Need to condense if-statements

Posted 08 December 2011 - 12:09 AM

Thanks so much man! Had no clue you could even create a Color array haha.

And yeah you're right about that, this was an intro class so I'm hoping the followup classes cover it more sufficiently. But as soon as finals week is over I planned on doing plenty of independent study on the subject!
Was This Post Helpful? 0
  • +
  • -

#10 Sheph   User is offline

  • D.I.C Lover
  • member icon

Reputation: 447
  • View blog
  • Posts: 1,032
  • Joined: 12-October 11

Re: Need to condense if-statements

Posted 08 December 2011 - 12:12 AM

I'm glad that you learned something. :)
Was This Post Helpful? 0
  • +
  • -

#11 AlexAndAHalf   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 22-November 11

Re: Need to condense if-statements

Posted 08 December 2011 - 12:17 AM

And by the way, I totally see what you were saying about the loop now. Don't know why that didn't click with me before, but you're right! I eliminated it.
Was This Post Helpful? 0
  • +
  • -

#12 pbl   User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8378
  • View blog
  • Posts: 31,956
  • Joined: 06-March 08

Re: Need to condense if-statements

Posted 08 December 2011 - 07:42 AM

You already have two arrays, have a third one

   String[] fruit = {"Apples", "Bananas",  "Blueberries", "Limes", "Oranges"};  
   String[] colorStr = {"red", "yellow",  "blue", "green", "orange"};  
   Color[] color = {Color.RED, Color.YELLOW, Color.BLUE, .....

   public void actionPerformed(ActionEvent e) {
      int index = combo.getSelectedIndex();
      label.setForeground(color[index])
      label.setText(colorStr[index]);




Would be easier if you created a class FruitAndColor I am sure that macosxnerd101 will catch you, with reason, on that one :)

http://www.dreaminco...arallel-arrays/
Was This Post Helpful? 2
  • +
  • -

Page 1 of 1