'for'和'switch'之间的冲突?

时间:2015-03-27 10:56:44

标签: java

我想尝试一些可以连续读取用户输入的编程,除非输入是0

但问题是我输入的内容(0除外),它总是显示"请选择一个" (在default部分中)。如果我输入4,它会两次显示此短语!

我不明白为什么。 forswitch之间是否存在冲突?

这是代码:

System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println("Choose one: ");
char ch = (char)System.in.read();
while (ch!= '0') {
    switch(ch) { 
        case '1':
            System.out.println("The If"); 
            break;
        case '2':
            System.out.println("The Case");
            break;
        default:
            System.out.println("Please choose one");        
    }
    ch = (char)System.in.read();         
}

2 个答案:

答案 0 :(得分:1)

问题是char ch = (char)System.in.read();。 Java不支持基于字符的输入,我建议使用一个修复输出的扫描仪,但是用户现在必须在每次输入后按回车。

import java.io.IOException;
import java.util.Scanner;

public class Switch
{
    public static void main(String[] args) throws IOException
    {
        System.out.println("Help on:");
        System.out.println(" 1. if");
        System.out.println(" 2. switch");
        System.out.println("Choose one: ");
        Scanner in = new Scanner(System.in);
        String s = in.nextLine();
        while (!s.equals("0"))
        {
            switch(s)
            {
                case "1":
                    System.out.println("The If");
                    break;
                case "2":
                    System.out.println("The Case");
                    break;
                default:
                    System.out.println("Please choose one");
            }
            s = in.nextLine();
        }
    }
}

如果你不想按回车,你也可以两次阅读这个角色,虽然我只能推测为什么这个工作是通过流发送的控制字符。编辑:我认为它也可能是UTF-16字符的另一个字节,在输入ASCII字符时不使用,但System.in.read()返回的是整数而不是字节。

import java.io.IOException;

public class Switch
{
    public static void main(String[] args) throws IOException
    {
        System.out.println("Help on:");
        System.out.println(" 1. if");
        System.out.println(" 2. switch");
        System.out.println("Choose one: ");
        char ch = (char)System.in.read();
        while (ch!= '0')
        {
            switch(ch)
            {
                case '1':
                    System.out.println("The If");
                    break;
                case '2':
                    System.out.println("The Case");
                    break;
                default:
                    System.out.println("Please choose one");
            }
            ch = (char)System.in.read();
            ch = (char)System.in.read();
        }

    }
}

答案 1 :(得分:0)

System.in.read()从InputStream读取一个字节并返回它。键入1或任何单个数字并按Enter键时,它会读取两个字符。

尝试绑定多位数以查看System.in.read()的行为方式。

您应该使用scanner用于控制台输入:

http://docs.oracle.com/javase/tutorial/essential/io/scanning.html

相关问题