我必须为控制台菜单应用程序实现一个接口IExecutable。我正在实现的方法是:对象执行(对象o); 所以我显示菜单。我从控制台读取了一个菜单选项,可以是Integer或String。执行时我有这个错误: java.lang.String无法强制转换为java.lang.Integer 问题是进行转换的最佳方式是什么。
ConsoleMenu.java
public Object execute(Object o) {
show();
o = read();
try{
int choice = Integer.parseInt((String) o); // error on this 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() == i && 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 i = new Integer(1);
ConsoleMenu menu = new ConsoleMenu("MATH OPERATIONS");
menu.addMenuOption(new SubOption());
menu.addMenuOption(new AddOption());
i = (Integer) menu.execute(i);
}
}
答案 0 :(得分:0)
在错误行上:
if (o != null && o instanceof Integer){
Integer choice = (Integer)o;
//complete here
}
答案 1 :(得分:0)
当你致电(String) o
以下是从Object
获取String或Integer对象的更具表现力的方法String.class.cast(o);
Integer.class.cast(o);
我认为,尽管您可能还需要使用instanceOf
运算符来了解上述哪个操作。 instanceOf不是一个很好的方法(见Is instanceof considered bad practice? If so, under what circumstances is instanceof still preferable?),有些人会做任何事情来避免它。在您当前的设计中,我认为您必须包含一个instanceOf检查
答案 2 :(得分:0)
我从控制台读取了一个菜单选项,可以是Integer或String
如果用户可以输入3或X作为菜单选项,则不应解析得到的整数值。
如果您有MenuOptions的代码,请将其key属性更改为字符串而不是整数。 如果不这样做,可能需要快速修复
private static IExecutable getMenuOptions(String i){
for(MenuOptions option : options){
if(i.equals(option.getKey()+"")) && option.getIsActive()){
return option;
}
}
return null;
}
可称为
IExecutable menuOption = getMenuOptions((String) o);