创建一个获取用户输入的Java程序,它必须是类型'字节',并且在区间[0,8]中。 我正在使用一种方法来首先检查输入是否是一个字节,然后如果这真的检查该字节是否适合间隔,然后将该值返回给我的主要方法。Java - 扫描仪站立空闲
public static byte GetShiftedLeft(){
byte l = GetByte(SHIFT_L_MSG);
while (l < 0 || l > 8){
System.out.println(l + " is not between the range");
l = GetByte(SHIFT_L_MSG);
}
return l;
}
public static byte GetShiftedRight(){
byte r = GetByte(SHIFT_R_MSG);
while (r < 0 || r > 8){
System.out.println(r + " is not between the range");
r = GetByte(SHIFT_R_MSG);
}
return r;
}
public static byte GetByte(String prompt){
System.out.print(prompt);
Scanner stdin = new Scanner(System.in);
while (!stdin.hasNextByte()){
System.out.println("*** "+stdin.next() + " is not a byte ***");
System.out.print("Try again\n"+prompt);
stdin.next();
}
return stdin.nextByte();
}
当我运行程序检查它,如果第一输入不是一个字节,但随后的下一个输入是一个字节,但不适合在间隔中,该消息不显示和扫描仪闲置。
输出运行:
enter #left-shift bits in the interval [0,8]: 145
*** 145 is not a byte ***
Try again
enter #left-shift bits in the interval [0,8]: 12
4
enter #right-shift bits in the interval [0,8]: 12
12 is not between the range
enter #right-shift bits in the interval [0,8]: 11
11 is not between the range
enter #right-shift bits in the interval [0,8]: 10
10 is not between the range
enter #right-shift bits in the interval [0,8]: 789
*** 789 is not a byte ***
Try again
enter #right-shift bits in the interval [0,8]: 12
然后,它只是站在那里...作为线5 & 6从输出
为什么要调用'stdin.next()'两次? – shmosel
我打电话给它两次,第一次打印输入给出告诉用户它不是一个字节,第二次告诉程序期待另一个输入。据我现在了解,它可以完成只是第一个,它工作得很好 –