【问题标题】:Java - string split errorJava - 字符串拆分错误
【发布时间】:2014-04-29 23:12:43
【问题描述】:

我正在尝试拆分字符串并将每个子字符串返回到 Java 中的数组(在 c# 中更容易),但编译器没有它。当我尝试调用数组中索引高于 0 的任何字符串的值时,我不断收到索引越界错误。这是我正在使用的代码:

public class hello {
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int setter = 3000;
        String num = in.next();
        String[] numbers = num.split(" ");
        int j = numbers.length;
        for (int i =0; i < numbers.length ; i++) {
            System.out.println(numbers[i]);
        }
        System.out.println(j);

即使返回的数组长度也是1。

【问题讨论】:

  • 我的第一个输入是 5..then..."1 2 3 4 5"
  • 您的in.next() 只返回一个令牌。您可能想要in.nextLine()。如果您不费心阅读 Javadoc 并调用错误的方法,那么一切都“在 C# 中更容易”。
  • 先生。华莱士,修复了错误,但现在它只接受一行输入而不是两行
  • 对,您可能需要插入一个额外的调用 nextLine() 以读取第一次输入后出现的换行符。
  • 好的,添加一个额外的调用解决了这个问题,它似乎可以正常工作,感谢华莱士先生。

标签: java string split


【解决方案1】:

正如 David Wallace 在 cmets 中所说:您应该使用 Scanner 中的 nextLine... 但是...为什么要读取行来拆分成 int?

public static void main(final String[] args) {
    final Scanner in = new Scanner(System.in);
    String line = null;

    List<List<Integer>> all = new ArrayList<>();

    while ((line = in.nextLine()) != null) {
        final String[] tokens = line.split(" ");
        List<Integer> forOneLine = new ArrayList<>();
        for (final String token : tokens) {
            try {
                final Integer value = Integer.valueOf(token);
                forOneLine.add(value);
            } catch (final NumberFormatException e) {
                // Not an Integer
            }
        }
        all.add(forOneLine); 
    }

现在可以了吗?

【讨论】:

  • 它的工作原理是用户首先输入他想输入的数字......即5......然后他输入5个数字“1 2 3 4 5”并且这些数字被拆分成一个数组。
【解决方案2】:

最终解析为整数

 public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        String n = in.nextLine();
        int ne = Integer.parseInt(n);
        String m = in.nextLine();
        String[] numbers = m.split(" ");
        System.out.println(n);
        System.out.println(m);
        for (String string : numbers) {
            System.out.println(string);
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多