问题
返回整数值。
private static int getIntFromUser(String aa) {
int aaa = 0;
while (true && aaa <= 0) {
try {
System.out.println(aa + ": ");
aaa = in.nextInt();
if (aaa <= 0) {
System.out.println("Please enter a positive number.");
}
} catch (Exception e) {
System.out.println("Please enter an integer: ");
in.next();
}
}
in.next();
return aaa;
}
问题
使用while循环尝试/捕捉无法正常工作?
答案 0 :(得分:0)
自己测试,它会正确返回aaa(删除方法底部的in.next()
并将其替换为in.nextLine()
)。当您进行return
呼叫时,您需要将其发送到某个地方。例如System.out
或类似int x = getUserFromInput("test: ");
public class Tester {
private static Scanner in = new Scanner(System.in);
private static int getIntFromUser(String aa) {
int aaa = 0;
while (true && aaa <= 0) {
try {
System.out.println(aa + ": ");
aaa = in.nextInt();
if (aaa <= 0) {
System.out.println("Please enter a positive number.");
}
} catch (Exception e) {
System.out.println("Please enter an integer: ");
in.next();
}
}
in.nextLine();
return aaa;
}
public static void main(String[] a) {
System.out.println(getIntFromUser("test123"));
}
}
<强>输出强>