如何读取用户输入的字符?

问题描述 投票:0回答:1

当我输入字符时,输出显示为错误的输入。我不明白怎么了编译器中提供的输入为大写字母E或D,但在切换时符合默认大小写。

public static void main(String[] args) throws IOException {
     //Scanner
    //Scanner s = new Scanner(System.in);
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int q = Integer.parseInt(br.readLine());
    char c;
    int i=0, j=0;
    int id=0, jd=0;
    int arr[][] = new int[q][q];
    int temp[][] = new int[q][q];
    for(int ip=0; ip<q; ip++)
    {
        c = (char)br.read();
        switch(c)
        {
            case 'E': 
                    for(int al=i; al<i+1; al++)
                    {
                        for(int al2=j; al2<j++; al2++)
                        {
                        arr[i][j] = Integer.parseInt(br.readLine());  
                        }
                    }

                    }
                    i++;
                    j++;
                    break;

            case 'D':
                     System.out.println(arr[id][jd]);
                     id++;
                     jd++;
                     break;
            default:
                    System.out.println("wrong input");
        }
    }
java char bufferedreader
1个回答
0
投票

tldr:在c = br.readLine().charAt(0)循环中使用c = (char)br.read()而不是for来读取char


如果尝试使用q = 1运行它,然后使用char c = 'E'作为输入,它将按预期工作。

但是与q = 2相同,对于q的其他值,将执行默认大小写,依此类推。

由于键入ED并按enter,程序将读取\r\n,因此第二次使用\r,第三次迭代使用\n

因此,建议使用br.readLine().charAt(0),以便您可以逐行读取char

完整代码如下:

public static void main(String[] args) throws IOException {
     //Scanner
    //Scanner s = new Scanner(System.in);
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int q = Integer.parseInt(br.readLine());
    char c;
    int i=0, j=0;
    int id=0, jd=0;
    int arr[][] = new int[q][q];
    int temp[][] = new int[q][q];
    for(int ip=0; ip<q; ip++)
    {
        c = br.readLine().charAt(0);
        switch(c)
        {
            case 'E': 
                    for(int al=i; al<i+1; al++)
                    {
                        for(int al2=j; al2<j++; al2++)
                        {
                        arr[i][j] = Integer.parseInt(br.readLine());  
                        }
                    }
                    //an extra closing bracket was put here by OP at first
                    i++;
                    j++;
                    break;

            case 'D':
                     System.out.println(arr[id][jd]);
                     id++;
                     jd++;
                     break;
            default:
                    System.out.println(c);
                    System.out.println("wrong input");
        }
    } // one } was missing here too.
}
© www.soinside.com 2019 - 2024. All rights reserved.