2017-06-21 19 views
-2

我有字符串中的數字。我想通過循環或任何方式將其切入並保持數組,然後讓這個數組再次循環以從最少到最多排列。 如何讓結果與我構建的這些數組相同。 謝謝。如何從字符串中取數字到子串並保持數組?

public class Main 
{ 
    static String input = "1,3,7,11,5,16,13,12,22,14"; 
    public static void main(String[] args) 
    { 
     /* 
     int[] keep = new int[11]; //How I can know if I don't know total index in first time.`enter code here` 
     keep[0] = 1; 
     keep[1] = 3; 
     keep[2] = 7; 
     keep[3] = 11; 
     keep[4] = 5; 
     keep[5] = 16; 
     keep[6] = 13; 
     keep[7] = 12; 
     keep[8] = 22; 
     keep[9] = 14; 

     int[] rank = new int[keep.length]; 
     rank[0] = 1; 
     rank[1] = 3; 
     rank[2] = 5; 
     rank[3] = 7; 
     rank[4] = 11; 
     rank[5] = 12; 
     rank[6] = 13; 
     rank[7] = 14; 
     rank[8] = 16; 
     rank[9] = 22; 
     */ 

     for (int i=0;i<rank.length;i++) 
     { 
      System.out.println(rank[i]); 
     } 

    } 

} 
+0

你的描述非常模糊。我是否需要將這個字符串轉換爲一個整數數組?如果是這樣,你可以通過檢查字符串的split方法來開始。 –

回答

1

你需要使用split方法對您輸入的字符串,然後從String轉換爲integer

String[] splitted=input.split(","); 

int[] keep = new int[splitted.length]; 

for(int i=0;i<splitted.length;i++){ 
    keep[i]= Integer.parseInt(splitted[i]); 
} 
1

,您可以:

  • 的字符串分割結腸
  • 流是導致array
  • map tha噸至整數解析每個元素的數組
  • 結果轉換爲一個數組

所以基本上:

String input = "1,3,7,11,5,16,13,12,22,14"; 
int[] foo = Stream.of(input.split(",")).mapToInt(Integer::parseInt).toArray(); 

System.out.println(Arrays.toString(foo)); 
1

你可以做這樣的事情。

String input = "1,3,7,11,5,16,13,12,22,14"; 

String[] keepStrings = input.split(","); 
int[] keep = new int[keepStrings.length]; 
int[] rank = new int[keep.length];// create a rank array 

// arrays can be duplicated only by doing field by field copy. Otherwise it may lead to aliasing. 
for (int i = 0; i < keepStrings.length; i++) { 
    keep[i] = Integer.parseInt(keepStrings[i]); 
    rank[i] = keep[i]; 
} 

Arrays.sort(rank); 

System.out.println(keep); //[1, 3, 7, 11, 5, 16, 13, 12, 22, 14] 
System.out.println(rank); //[1, 3, 5, 7, 11, 12, 13, 14, 16, 22] 
0
public static void main(String[] args) { 
    String input = "1,3,7,11,5,16,13,12,22,14"; 

    String myArray[] = input.split(","); 
    bubbleMethod(myArray); 
} 

public static int[] setValuesToInt(String theArray[]) { 
    int myArray[] = new int[theArray.length]; 
    for (int i = 0; i < theArray.length; i++) { 
     myArray[i] = Integer.parseInt(theArray[i]); 
    } 

    return myArray; 
} 

public static void bubbleMethod(String theArray[]) { 
    int arrayToSort[] = setValuesToInt(theArray); 

    int n = arrayToSort.length; 
    int temp = 0; 

    for (int i = 0; i < n; i++) { 
     for (int j = 1; j < (n - i); j++) { 

      if (arrayToSort[j - 1] > arrayToSort[j]) { 
       temp = arrayToSort[j - 1]; 
       arrayToSort[j - 1] = arrayToSort[j]; 
       arrayToSort[j] = temp; 
      } 

     } 
    } 

    for(int a : arrayToSort){ 
     System.out.println(a); 
    } 
} 
相關問題