2012-11-16 46 views
6

我在這裏有一個惱人的情況;其中我無法正確接受輸入。我總是通過Scanner進行輸入,而我並不習慣於BufferedReader以Java輸入BufferedReader


INPUT FORMAT


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 
+1

你的m [0] = inp.read();正在讀一個字節或其他東西。做一個readline到一個字符串中,並分割它以得到兩個字段,然後解析它們到整數。 –

+0

'inp.read()'將讀取一個字符(16位)而不是字節(8位)。 –

回答

13

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

2

問題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]); 
} 
0

您無法讀取一行單獨整數分別使用BufferedReader因爲你使用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 
     } 
    } 
} 

我希望這會幫助你。