我无法在 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();
}
关于java - 无法使用java中的扫描器扫描字符串数组的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17771616/