2014-10-27 72 views
-2

我瀏覽過這個。我有一個char數組[10 20 30]。我想將其轉換爲整型數組或整型數組列表,使得我的int數組變成 int [] charToInt = {10,20,30}; 我需要最初的指導來解決這個問題。我不想要整個代碼。只是一個提示。而且我會編寫這個提示。提前將char數組轉換爲int數組與空間

感謝

+0

我不明白。你的意思是你有一個char數組'''','0','','2','0',...}'?你的意思是你想將它轉換爲一個int數組'{10,20,...}'? – Radiodef 2014-10-27 22:08:29

+0

@Radiodef:是的,這是正確的 – Shehlina 2014-10-27 22:10:17

+0

是一個「或」對不起 – Shehlina 2014-10-27 22:10:37

回答

1

更新時間:這裏正在例如

import java.util.ArrayList; 

public class Example { 
    public static void main(String[] args) { 
    char[] input = { '1', '0', ' ', '2', '0', ' ', '3', '0'}; 
    ArrayList<Integer> output = extractIntegers(input); 

    for (int i : output) { 
     System.out.println(i); 
    } 
    } 

    private static ArrayList<Integer> extractIntegers(char[] chars) { 
    int start = -1; 
    ArrayList<Integer> integers = new ArrayList<Integer>(); 
    for (int i = 0; i < chars.length; i++) { 
     boolean isDigit = Character.isDigit(chars[i]); 
     if (start != -1 && !isDigit) { 
     integers.add(parseInt(chars, start, i)); 
     start = -1; 
     } else if (start == -1 && isDigit) { 
     start = i; 
     } 
    } 
    if (start != -1) { 
     integers.add(parseInt(chars, start, chars.length)); 
    } 
    return integers; 
    } 

    private static int parseInt(char[] chars, int start, int stop) { 
    return Integer.parseInt(new String(chars, start, stop - start)); 
    } 
} 
  1. 保存此代碼在一個名爲Example.java
  2. 編譯$ javac Example.java
  3. 運行它$ java Example
+0

我說char數組不是字符串array.But謝謝 – Shehlina 2014-10-27 22:16:52

+0

請編輯你的答案,包括你到目前爲止的代碼,幷包括輸入文件的內容。 – 2014-10-27 22:17:33

+0

@PeterSutton 1.詢問char數組2.不檢查非數字字符串值,將String轉換爲int可能會拋出異常 – sotcha 2014-10-27 22:25:07

1

char數組轉換與結構{'number', ' ', 'number', ' ', ... }int陣列將是一個辦法:

public static int[] toIntArray(final char[] source) { 
    if (source == null || source.length == 0) { // check for null or empty array 
     return new int[0]; 
    } 

    final String sourceAsStr = String.copyValueOf(source); // convert array to string 
    final String[] numbers = sourceAsStr.split(" "); // split string on "space"; each part contains a number 
    final int[] result = new int[numbers.length]; 

    for(int i = 0; i < numbers.length; i++) { 
     try { 
      result[i] = Integer.parseInt(numbers[i]); 
     } catch (final NumberFormatException e) { 
      // handle exception 
      return new int[0]; // return empty array on exception 
     } 
    } 
    return result; 
} 

Ex充足:

System.out.println(Arrays.toString(toIntArray(new char[] {'1', '0', ' ', '2', '0', ' ', '3', '0'}))); 
System.out.println(Arrays.toString(toIntArray(new char[] {'1', '0', '-', '2', '0', '-', '3', '0'}))); 
System.out.println(Arrays.toString(toIntArray(null))); 

結果:

[10, 20, 30] 
[] 
[]