我无法在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();
}
}
}
答案 0 :(得分:1)
你走了:
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();
}