java - Issues on cast Object to Integer or String -
i have implement interface iexecutable console menu application.the method implementing is: object execute(object o); display menu. read console menu option integer or string. on execution have error : java.lang.string cannot cast java.lang.integer question best way make conversion.
consolemenu.java
public object execute(object o) { show(); o = read(); try{ int choice = integer.parseint((string) o); // error on line iexecutable menuoption = getmenuoptions(choice); if(menuoption != null){ o = menuoption.execute(o); return o; } } catch(exception e){ system.out.println("invalid option"+ e.getmessage()); } return null; } private static iexecutable getmenuoptions(int i){ for(menuoptions option : options){ if(option.getkey() == && option.getisactive()){ return option; } } return null; } public static object read(){ string option = null; bufferedreader buffer = new bufferedreader(new inputstreamreader(system.in)); try { option = buffer.readline(); return option; } catch (ioexception e) { system.out.println("ioexception " +e.getmessage()); } return null; }
main.java
public class main { public static void main(string[] args) { integer = new integer(1); consolemenu menu = new consolemenu("math operations"); menu.addmenuoption(new suboption()); menu.addmenuoption(new addoption()); = (integer) menu.execute(i); } }
i read console menu option integer or string
if user can either input 3 or x menu option, should not parse value integer.
if have code menuoptions, change key property string not integer. if not, quick fix may needed
private static iexecutable getmenuoptions(string i){ for(menuoptions option : options){ if(i.equals(option.getkey()+"")) && option.getisactive()){ return option; } } return null; }
which may called
iexecutable menuoption = getmenuoptions((string) o);
Comments
Post a Comment