Friday 3 November 2017

String cannot be cast to java error: Trying to convert string into integer






When trying to add years from a combobox this error
shows:



Exception in thread "AWT-EventQueue-0"
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer



at
LibraryFrame$addListener.actionPerformed(LibraryFrame.java:103)



The
program highlights the 'Integer anInteger = (Integer) selected;' line as the problem?



class addListener implements
ActionListener
{

public void actionPerformed(ActionEvent
e)
{
Object selected = yearCombo.getSelectedItem();


if(e.getSource() == button)
{

System.out.println("Add button clicked!");
String t =
title.getText();
Integer anInteger = (Integer) selected;
int y =
anInteger;

int q =
Integer.parseInt(quantity.getText());
library.addItem(new
LibraryItem(t,y,q));
library.printLibrary();


System.out.println("Thank You!");
}

}
}



Heres
the code where yearCombo is
populated:



label1 = new
JLabel("Year");
yearCombo = new JComboBox();

ArrayList countYear = new ArrayList();
for(int
y=1800; y<=2014; y++)
{
countYear.add(y);

}
for(int x=0; x < countYear.size(); x++)


{
yearCombo.addItem((countYear.get(x) + " "));

}



CODE NOW THROWING A
NUMBER FORMAT EXCEPTION after
changing



 Integer anInteger =
(Integer)
selected;



to




Integer anInteger =
Integer.parseInt(selected.toString());


Answer




This:



yearCombo.addItem((countYear.get(x)
+ " "));
// ^--------------- not
numeric



results
in a string that cannot be converted to a number, no matter what
countYear.get(x) gives
you.



Do you really need to add that space
there?


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...