2014-04-29 92 views
-4

我想分割一個字符串,並返回每個子字符串到Java中的數組(在c#中更容易),但編譯器沒有它。我不斷收到索引越界的錯誤,當我試圖調用數組中的任何字符串的值進行索引大於0.下面的代碼我使用:返回Java - 字符串拆分錯誤

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.

+0

什麼是你的輸入? –

+0

我的第一個輸入是5..then ...「1 2 3 4 5」 – MProgramerX

+2

你的'in.next()'只返回一個單一的標記。您可能需要'in.nextLine()'。如果你懶得閱讀Javadoc並調用錯誤的方法,那麼所有東西都「在C#中更容易」。 –

回答

0

由於大衛華萊士在評論中說:你應該使用掃描儀nextLine ... 但...爲什麼要讀取行分裂爲整數?

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); 
    } 

現在可以嗎?

+0

它應該如何工作的是用戶首先輸入他想要輸入的數字......即5 ......然後他輸入5個數字「1 2 3 4 5」,這些數字被分成一個數組。 – MProgramerX

+0

好的,我會評論 – farvilain

0

端起來解析爲一個整數

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); 
     } 
    }