您需要调用该方法print(short value)
if (val > 0 && val < 128)
。呼叫被print(Integer value)
忽略(short)val
。可能是什么问题呢?
输入:45
结论:Это тип Integer, значение 45
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String in = sc.next();
while (!in.equals("exit")){
try{
int val = Integer.parseInt(in);
print((val > 0 && val < 128)?(short)val:val);
}catch (Exception e){
System.out.println("Это не число");
}
in = sc.next();
}
}
public static void print(short value) {
System.out.println("Это тип short, значение " + value);
}
public static void print(Integer value) {
System.out.println("Это тип Integer, значение " + value);
}
}
问题可能是对三元运算符和重载函数的选择如何工作的误解。
如果操作数的类型不同(但兼容),则三元运算符返回更通用的类型。
重载函数的选择发生在编译时。