10

ここで少し厄介なケースがあります。ここで、入力を適切に受け取ることができません。私は常に を介して入力を行ってき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
4

3 に答える 3

16

BufferedReader#readストリームから単一の文字 [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も確認できます。

于 2012-11-16T06:38:00.443 に答える
2

inp.read(); methodによる問題 ID 。一度に1文字ずつ返され、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]);
}
于 2012-11-16T06:39:32.197 に答える
1

クラスを使用BufferedReaderする場合と同様に、個別の整数を 1 行で個別に読み取ることはできません。Scannerただし、クエリに関して次のようなことができます。

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
       }
    }
}

これがお役に立てば幸いです。

于 2017-07-04T16:05:46.997 に答える