java - 无法使用java中的扫描器扫描字符串数组的所有元素

标签 java string

我无法在 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/

相关文章:

c++ - 为什么此代码使用带字符串的映射 (C++) 会出现运行时错误?

java - 如何在java中使用R模型来预测多个模型?

java - 使用可观察对象或事件或接口(interface)传递值

java - 在另一个接口(interface)中使用一个接口(interface)

java - 在新 Activity 中查看和下载壁纸时遇到问题

javascript - 从 Array 中的对象中获取关键数据并将它们转换为一个分隔的字符串

javascript - Javascript 字符串长度是常数时间吗?

c++ - 如何将字符串的所有单词写入不同的变量?

java - Hibernate:未知的mappedBy in:,引用的属性未知:

javascript - 一个数组和一个显示为字符串的变量