![](/img/trans.png)
[英]Using BufferedReader or Scanner for processing multiple inputs in Java
[英]Taking inputs with BufferedReader in Java
我這里有一點煩人的情況; 其中我無法正確接受輸入。 我總是通過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
BufferedReader#read
#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與BufferedReader 。
問題是因為inp.read();
方法 。 它一次返回單個字符,因為你將它存儲到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]);
}
您不能像使用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
}
}
}
我希望這能幫到您。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.