Home arrow static arrow Java Programming [Archive] - Comparing values in a String array
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - Comparing values in a String array
This topic has 2 replies on 1 page.

Posts:49
Registered: 3/31/04
Comparing values in a String array  
Jul 31, 2004 11:14 AM



 
Hello, I am working on a Swing program which contains a String array with 4 items in it. When the user clicks the checkbox to which the array applies the itemStateChanged() method executes, with the first statement determing which item in the array the user selected. Then I want to compare what the user selected versus other items in the array, so that a mathematical calculation can then be made. The getSelectedIndex() method nicely returns the position of the user selected item in the array, but the problem I have is that the method returns it as an integer, whereas the items in the array are strings. I can't seem to convert the integer to a string so that I can then compare the values (if that is possible). Any assistance would be greatly appreciated. A snippet of the program as follows:

 JLabel bedroomLabel = new JLabel("Please select number of bedrooms:");String[] numberOfBedrooms = {"None", "Two bedrooms", "Three bedrooms", "Four bedrooms"};JComboBox bedroomBox = new JComboBox(numberOfBedrooms);  public void itemStateChanged(ItemEvent event)	{		Object source = event.getSource();		if(source == bedroomBox)		{			int bedroomNum = bedroomBox.getSelectedIndex();			String name = String.valueOf(bedroomNum);				if(name.equals(numberOfBedrooms[1]))				{					additionalBedroomPrice += addBedroom;				}				else if(name.equals(numberOfBedrooms[1]))				{					additionalBedroomPrice += addBedroom * 2;				}				else if(name.equals(numberOfBedrooms[1]))				{					additionalBedroomPrice += addBedroom * 3;				}		} 
 

Posts:11,200
Registered: 7/22/99
Re: Comparing values in a String array  
Jul 31, 2004 11:44 AM (reply 1 of 2)



 
JList also has a method called getSelectedValue(). It returns the selected value itself rather than its index.
String bedroomNum = (String) bedroomBox.getSelectedValue();
See also the Swing tutorial on how to use lists: http://java.sun.com/docs/books/tutorial/uiswing/components/list.html
 

Posts:49
Registered: 3/31/04
Re: Comparing values in a String array  
Jul 31, 2004 12:17 PM (reply 2 of 2)



 
Thank you for your prompt reply, that did the trick!

Regards,

Randy
 
This topic has 2 replies on 1 page.