[英]Unable to scan all the elements of the string array using scanner in java
我無法掃描Java中字符串數組的所有元素。 我不知道這是什么錯誤..請幫助
我無法掃描數組的第一個元素。它甚至沒有顯示錯誤。
import java.util.*;
public class uhu {
public static void main(String[] args) {
System.out.println("Hit n");
Scanner sc = new Scanner(System.in);
try {
int n = sc.nextInt();//scan the size of the array
String[] str=new String[n];
System.out.println("Enter elements");
for (int i = 1; i < n; i++) //scanning the elements
{
str[i]=sc.nextLine();
}
for (int i = 0; i < n; i++) //printing all the elements
{
System.out.println(str[i]);
}
} finally {
if (sc != null)
sc.close();
}
}
}
干得好 :
System.out.println("Enter elements");
for (int i = 0; i < n; i++) //scanning the elements
{
str[i]= sc.next();
}
從i = 0開始,並使用next()代替nextLine()。
如果您想讀取整行,則BufferedReader可以完成此工作,在本例中,Scanner nextLine()跳過最后一行,或在最后輸入空白行。
使用BufferedReader可以完成您的工作。
System.out.println("Hit n");
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
try {
int n = Integer.parseInt(buf.readLine());//scan the size of the array
String[] str=new String[n];
System.out.println("Enter elements");
for (int i = 0; i < n; i++) //scanning the elements
{
str[i]= buf.readLine();
}
for (int i = 0; i < n; i++) //printing all the elements
{
System.out.println(str[i]);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (buf != null)
buf.close();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.