[英]Read Strings separated by newline using BufferedReader into a String array
我讀過許多這樣的問題,但它們都是關於從txt
文件讀取輸入的。 我想從用戶而不是從文件中讀取輸入。
我輸入如下:
6 //number of total Strings to store in array
babu
anand
rani
aarti
nandu
rani
我已經嘗試過以下代碼在String
數組中進行此類輸入:
int n = in.nextInt(); // n= 6 here
String[] s = new String[n]; //String array of size 6 here
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try{
s = br.readLine().split("\\s");
}
catch(Exception e){
System.out.println(e);
}
提供給split()
的regex
是否正確? 我在這里想念的是什么? 如果這不是正確的方法,那么該怎么辦?
當您使用斜杠//s
,正則表達式使用反斜杠( \\
),正確的是\\\\s
。
但是不需要這種拆分,您只需要readLine
,就可以得到所需的內容(假設您不想在行中拆分單詞)。
您應該使用循環讀取所有數據(並擺脫in
變量中似乎包含的Scanner):
String[] s = null
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in)) {
int n = Integer.parseInt(br.readLine());
for (int line = 0; line < n; line++) {
s[line] = br.readLine();
}
} catch(Exception e){
System.out.println(e);
}
將第三行移到第一行之前。
然后在新的第二行中使用它:
int n = Integer.parseInt(br.readLine());
而且,當然,您需要一個循環才能將輸入字符串放入數組中。
這應該有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.