有沒有更好的方法來撰寫這個 getInput() 方法,而不是檢查每個可以傳入的類?
public Object getInput(String prompt, Class<?> type) {
System.out.print(prompt);
Scanner scn = new Scanner( System.in );
String str = scn.nextLine( );
if(type.equals(Integer.class))
return Integer.parseInt(str);
else if (type.equals(Double.class))
return Double.parseDouble(str);
else if (type.equals(Boolean.class))
return Boolean.parseBoolean(str);
else return type.cast(str);
}
它足夠作業,但我想讓它適用于大多數情況,而不必添加更多其他 if 陳述句。除此之外,當我接受輸入并將其分配給變數時,我需要強制轉換為該型別。有沒有辦法解決這個問題?
Invocation:
int num = (int)menu.getInput("Enter an integer: ", Integer.class);
uj5u.com熱心網友回復:
也許您可以嘗試使用反射,因為這些類(Integer,Boolean...)通常有一個靜態valueOf方法:
public static void main(String[] args) {
int input = getInput("1", Integer.class);
System.out.println(input);
}
public static <T> T getInput(String input, Class<T> type) {
try {
Method valueOf = type.getMethod("valueOf", String.class);
return type.cast(valueOf.invoke(null, input));
} catch (Exception e) {
return null;
}
}
uj5u.com熱心網友回復:
您“可能”有幾種方法可以做到這一點,但可能不會讓您每次需要新輸入型別時都修改“基本”輸入法的方法之一是將“決議”作業流程注入方法本身。
也就是說,創建一個interface定義“決議”方法的泛型,該方法可以獲取String特定型別的回傳值并將其傳遞給您的輸入法,例如...
import java.util.Scanner;
public final class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
Integer result = getInput("Please enter an integer: ", new IntParser());
}
public interface Parsable<T> {
public T parse(String value);
}
public class IntParser implements Parsable<Integer> {
@Override
public Integer parse(String value) {
return Integer.parseInt(value);
}
}
public <T> T getInput(String prompt, Parsable<T> parser) {
System.out.print(prompt);
Scanner scn = new Scanner(System.in);
String str = scn.nextLine();
return parser.parse(str);
}
}
現在,如果您不想getInput("Please enter an integer: ", new IntParser());每次都打字??,您可以創建方便的方法來讓您的生活更輕松,例如...
public int getIntInput(String prompt) {
return getInput(prompt, new IntParser());
}
現在,我,我可能會創建一個類來包含這一切......
public class InputManager {
public interface Parsable<T> {
public T parse(String value);
}
public class IntParser implements Parsable<Integer> {
@Override
public Integer parse(String value) {
return Integer.parseInt(value);
}
}
protected Scanner scanner;
public InputManager(Scanner scanner) {
this.scanner = scanner;
}
public InputManager() {
this(new Scanner(System.in));
}
public <T> T getInput(String prompt, Parsable<T> parser) {
System.out.print(prompt);
String str = scanner.nextLine();
return parser.parse(str);
}
public int getIntInput(String prompt) {
return getInput(prompt, new IntParser());
}
}
但是我瘋了??
Important - This doesn't deal with error handling. I might, for example, have the Parsable return null when it's unable to parse the result, otherwise you should probably define a ParsingException so that calls are made aware of their responsibilities
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/427851.html
上一篇:協議中的Swift泛型
