簡體   English   中英

是否可以將String轉換為int數組?

[英]Is String to int Array conversion possible?

我已經編寫了一段代碼,其中我掃描了一個整數假設121,並將其分為3部分,我將其設置為String並嘗試通過split再次將其轉換。但是我不明白嗎? 有沒有簡單的方法可以做到這一點?

  public static void main(String []args){
      Scanner scan = new Scanner(System.in);
      int n = scan.nextInt() ;
      int sum = 0;
      for(int i = 1 ; i<=n; i++){
         String s = Integer.toString(i);

          int[] c = Integer.parseInt(s.split("")); //Here's the problem
          int sm = 0 ;
          for(int x :c){
              sm +=x ;
          }
          System.out.print(sm+" ");
       }
   }

輸入= 12

預期輸出:1 2 3 4 5 6 7 8 9 1 2 3

輸出:Main.java:14:錯誤:不兼容的類型:String []無法轉換為String int [] c = Integer.parseInt(s.split(“”));

您的預期輸出似乎甚至不需要任何整數到字符串的轉換:

int n = scan.nextInt();
for (int i=0; i < n; i++) {
    if (i > 0) System.out.print(" ");
    System.out.print(1 + i % 9);
}

對於n = 12的輸入,將輸出:

1 2 3 4 5 6 7 8 9 1 2 3

您不能將整個數組傳遞給parseInt() 您需要分別解析每個元素:

int[] c = Arrays.stream(s.split(""))
        .mapToInt(Integer::parseInt)
        .toArray();

還是老式的方式:

String[] chars = s.split("");
int[] c = new int[chars.length];
for (int i = 0; i < c.length; i++) {
    c[i] = Integer.parseInt(chars[i]);
}

可以String[]每個字符(從split )映射到int ,然后將其轉換為int[] 喜歡,

int[] c = Arrays.stream(s.split("")).mapToInt(Integer::parseInt).toArray();

沒有其他更改,就會產生(按要求)

1 2 3 4 5 6 7 8 9 1 2 3 

輸入“ 12”。

您也可以使用IntStream這樣操作。


    int n = 12;
    int[] values = IntStream.range(0, n).map(i -> i % 9 + 1).toArray();
    System.out.println(Arrays.toString(values));

產生

[1 2 3 4 5 6 7 8 9 1 2 3]

對於n = 12

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM