【发布时间】:2017-09-20 15:09:21
【问题描述】:
我创建了三个基本上做同样事情的方法 readLong、readInt 和 readDouble。唯一的区别是扫描仪调用的方法。如何通过将它们全部转换为一种方法来减少重复代码?
public long readLong(String description)
{
System.out.println(description);
long nrToReturn = 0;
boolean acceptedValue = false;
do {
System.out.println();
System.out.print("Choose one: ");
try
{
nrToReturn = consoleScanner.nextLong(); //Only line thats different except return value
acceptedValue = true;
}catch(Exception e)
{
acceptedValue = false;
consoleScanner.nextLine();
}
}while (!acceptedValue);
consoleScanner.nextLine();
return nrToReturn;
}
【问题讨论】:
-
在code review上发布这个问题。
-
看看Java中的泛型类型
-
这些方法的调用者如何知道调用哪一个?
-
我认为调用者知道调用哪一个,但问题是让一个方法 public static
T readNumber(String description) -
@Michu93 我试过了,但问题是泛型类型 T 不接受 Long。编译器 syes “Cannot cast long to T”。
标签: java console java.util.scanner