亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將整數轉換為數字數組

將整數轉換為數字數組

慕姐4208626 2019-11-29 09:44:51
我嘗試將整數轉換為數組,例如1234到 int[] arr = {1,2,3,4};我寫了一個函數public static void convertInt2Array(int guess)  {    String temp = Integer.toString(guess);    String temp2;    int temp3;    int [] newGuess = new int[temp.length()];    for(int i=0;i<=temp.length();i++) {        if (i!=temp.length()) {            temp2 = temp.substring(i, i+1);        } else {            temp2 = temp.substring(i);            //System.out.println(i);        }        temp3 =  Integer.parseInt(temp2);            newGuess[i] = temp3;    }            for(int i=0;i<=newGuess.length;i++) {                System.out.println(newGuess[i]);            }          }但是拋出一個異常:Exception in thread "main" java.lang.NumberFormatException: For input string: ""    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)    at java.lang.Integer.parseInt(Integer.java:504)    at java.lang.Integer.parseInt(Integer.java:527)    at q4.test.convertInt2Array(test.java:28)    at q4.test.main(test.java:14)Java Result: 1有什么想法嗎?
查看完整描述

3 回答

?
慕斯王

TA貢獻1864條經驗 獲得超2個贊

眼前的問題是由于您使用<= temp.length()而不是< temp.length()。但是,您可以更簡單地實現此目的。即使您使用字符串方法,也可以使用:


String temp = Integer.toString(guess);

int[] newGuess = new int[temp.length()];

for (int i = 0; i < temp.length(); i++)

{

    newGuess[i] = temp.charAt(i) - '0';

}

< newGuess.length()在打印內容時也需要進行相同的更改以使用-否則,對于長度為4的數組(其有效索引為0、1、2、3),您將嘗試使用newGuess[4]。for我編寫的絕大多數循環都<在條件中使用,而不是<=。


查看完整回答
反對 回復 2019-11-29
?
Qyouu

TA貢獻1786條經驗 獲得超11個贊

您不需要轉換int為String,只需使用% 10來獲取最后一位,然后將int除以10即可得到下一位。


int temp = test;

ArrayList<Integer> array = new ArrayList<Integer>();

do{

    array.add(temp % 10);

    temp /= 10;

} while  (temp > 0);

這將使您留下包含相反順序數字的ArrayList。您可以根據需要輕松還原它,并將其轉換為int []。


查看完整回答
反對 回復 2019-11-29
?
皈依舞

TA貢獻1851條經驗 獲得超3個贊

public static void main(String[] args)

{

    int num = 1234567;  

    int[]digits = Integer.toString(num).chars().map(c -> c-'0').toArray();  

    for(int d : digits)

        System.out.print(d);    

}

主要思想是


將int轉換為其String值

Integer.toString(num);

獲取一個int流,它表示組成我們整數的String版本的每個char(?digit)的ASCII值

Integer.toString(num).chars();

將每個字符的ascii值轉換為其值。要獲取char的實際int值,我們必須從實際char的ASCII碼中減去char'0'的ASCII碼值。要獲得我們數字的所有數字,必須對組成與我們數字相等的字符串的每個字符(對應于數字)應用此操作,這是通過將下面的map函數應用于我們的IntStream來完成的。

Integer.toString(num).chars().map(c -> c-'0');

使用toArray()將int流轉換為int數組

Integer.toString(num).chars().map(c -> c-'0').toArray();


查看完整回答
反對 回復 2019-11-29
  • 3 回答
  • 0 關注
  • 1103 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號