gpt4 book ai didi

Java - 扫描仪闲置

转载 作者:太空宇宙 更新时间:2023-11-04 11:45:57 26 4
gpt4 key购买 nike

创建一个从用户获取输入的java程序,它的类型必须是“byte”并且在[0,8]区间内。我使用一种方法首先检查输入是否是一个字节,然后如果是,则检查该字节是否适合间隔,然后将该值返回到我的主方法。

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(),因此当输入 789 时,它需要另一个输入,然后是另一个输入。

关于Java - 扫描仪闲置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42353978/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com