有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中使用BufferedReader获取输入

我这里有一个有点烦人的案子;我无法正确地接受输入。我总是通过Scanner进行输入,不习惯BufferedReader


输入格式


First line contains T, which is an integer representing the number of test cases.
T cases follow. Each case consists of two lines.

First line has the string S. 
The second line contains two integers M, P separated by a space.

示例

Input:
2
AbcDef
1 2
abcabc
1 1

到目前为止我的代码:


public static void main (String[] args) throws java.lang.Exception
{
    BufferedReader inp = new BufferedReader (new InputStreamReader(System.in));
    int T= Integer.parseInt(inp.readLine());

    for(int i=0;i<T;i++) {
        String s= inp.readLine();
        int[] m= new int[2];
        m[0]=inp.read();
        m[1]=inp.read();

        // Checking whether I am taking the inputs correctly
        System.out.println(s);
        System.out.println(m[0]);
        System.out.println(m[1]);
    }
}

当输入上述示例时,我得到以下输出:

AbcDef
9
49
2
9
97

共 (3) 个答案

  1. # 1 楼答案

    问题id是由于inp.read();method引起的。它一次返回一个字符,因为您将它存储到int类型的数组中,所以这只是存储该数组的ascii值

    你能做的很简单

    for(int i=0;i<T;i++) {
        String s= inp.readLine();
        String[] intValues = inp.readLine().split(" ");
        int[] m= new int[2];
        m[0]=Integer.parseInt(intValues[0]);
        m[1]=Integer.parseInt(intValues[1]);
    
        // Checking whether I am taking the inputs correctly
        System.out.println(s);
        System.out.println(m[0]);
        System.out.println(m[1]);
    }
    
  2. # 2 楼答案

    不能像使用Scanner类那样使用BufferedReader单独读取单行中的单个整数。 尽管如此,您可以对查询执行以下操作:

    import java.io.*;
    class Test
    {
       public static void main(String args[])throws IOException
        {
           BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
           int t=Integer.parseInt(br.readLine());
           for(int i=0;i<t;i++)
           {
             String str=br.readLine();
             String num[]=br.readLine().split(" ");
             int num1=Integer.parseInt(num[0]);
             int num2=Integer.parseInt(num[1]);
             //rest of your code
           }
        }
    }
    

    我希望这对你有帮助

  3. # 3 楼答案

    ^{}从流中读取单个字符[0到65535(0x00-0xffff)],因此无法从流中读取单个整数

                String s= inp.readLine();
                int[] m= new int[2];
                String[] s1 = inp.readLine().split(" ");
                m[0]=Integer.parseInt(s1[0]);
                m[1]=Integer.parseInt(s1[1]);
    
                // Checking whether I am taking the inputs correctly
                System.out.println(s);
                System.out.println(m[0]);
                System.out.println(m[1]);
    

    您还可以检查Scanner vs. BufferedReader