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

时间:2017-04-28 07:46:36

标签: java

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 \ n。我没有得到的是如何避免它。以及它为什么适用于值1-4

1 个答案:

答案 0 :(得分:3)

尝试

 Scanner sc = new Scanner(System.in);

 int choice = sc.nextInt();

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