gpt4 book ai didi

java - System.in.read 导致循环执行三次

转载 作者:行者123 更新时间:2023-12-01 20:27:20 24 4
gpt4 key购买 nike

import java.io.IOException;
import java.io.InputStreamReader;

public class doSwitch {

public static void main(String[] args) throws IOException {

char choice;

do {
System.out.println("Welcome User");
System.out.println("1. Change plan");
System.out.println("2. Pay Bill");
System.out.println("3. Complaints");
System.out.println("4. De-activate account");
System.out.println("Choose one the above option");


choice = (char) System.in.read();


} while (choice < '1' || choice > '4');

System.out.println("User's Choice:" + choice);

///////////////////////////// switch
///////////////////////////// case////////////////////////////////////

switch (choice) {

case '1':
System.out.println("There are different plans than you can opt for");
break;
case '2':
System.out.println("Pay bill using credit card or debit card");
break;
case '3':
System.out.println("In case of complaint call 121");
break;
case '4':
System.out.println("Are you sure you want to discontinue with us");
break;

}
}
}

如果我输入 1 到 4 之间的值,此代码可以正常工作。但是如果该值大于 4,则它会执行循环 3 次。我发现它的值是\n,\r。我不明白的是我怎样才能避免它。以及为什么它适用于值 1-4

最佳答案

尝试

 Scanner sc = new Scanner(System.in);

int choice = sc.nextInt();

System.in.read() 读取单个字节。在您的情况下,它读取实际输入的字符。如果该字符不等于 1-4,则循环继续并读取下一个字节,该字节将作为返回字符。扫描仪对象会为您处理这个问题。

关于java - System.in.read 导致循环执行三次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43674818/

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