当我将String输入拆分为数组时,该数组只有1个Element。这是为什么?

时间:2014-06-21 15:02:18

标签: java arrays input split

当我将String输入拆分为数组时,该数组只有1个Element。这是为什么?从昨天开始,我还没有找到解决方案。我用它来帮助我Splitting String and put it on int array

class ISBNcheck2 {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Enter input: "); //ask for input
        String input = keyboard.nextLine(); // read input
        int length = input.length();

        String[] strArray = input.split(" "); //<---- THIS IS A PROBLEM, MY GUESS.
        // SOMEHOW strARRAY and intARRAY ONLY HAVE 1 ELEMENT STORED.?????

        int[] intArray = new int[strArray.length];
        for (int i = 0; i < strArray.length; i++) {
            intArray[i] = Integer.parseInt(strArray[i]);
        }

        for (int i = 0; i < intArray.length; i++) {
            System.out.println(intArray.length); // just a check
            System.out.println(intArray[i]); // just a check
        }

        //System.out.println();
        if (isIntegerclass.isValidISBN(input) && length == 10) {
            System.out.println("True: ");

            // I WANT TO BE ABLE TO ACCESS THE ELEMENTS LIKE THIS. BUT IT HAS ONLY 1 ELEMENT FOR SOME STRANGE REASON.
            System.out.println(" " + intArray[0] + " - " + intArray[1] + " " + intArray[2] + " " + intArray[3] + " - " + intArray[4] + " " + intArray[5] + " " + intArray[6] + " " + intArray[7] + " " + intArray[8] + " - " + intArray[9]); //print
        } else {
            System.out.println("This is not the right input...");
            System.out.println("The number must be 10 letters(numbers only) long. No need for dashes in between.");
            System.out.println("[] - [][][] - [][][][][] - []");
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我认为这会按照您想要的方式分割输入。随地吐痰&#34;&#34;将每个数字视为单独的字符串。但是,这会在第一个数字之前生成额外的空字符串。 copyOfRange删除额外的。

import java.util.Arrays;

public class Test {
  public static final void main(String[] args) throws InterruptedException {
    String[] raw = "01234".split("");
    String[] strArray = Arrays.copyOfRange(raw, 1, raw.length);
    System.out.println(Arrays.toString(strArray));
  }
}

打印:

[0, 1, 2, 3, 4]