簡體   English   中英

將int數組轉換為int

[英]Convert int array to int

我的應用程序中有一個類,其中存儲了int值:

Characters.class:

public int charPunch(int q) {

    int[] charPunch = {
        15, 
        10, 
        20, 
        25, 
        20, 
        20, 
        15, 
        20, 
        20, 
        25
    };
    return charPunch(q);
}

q值由用戶字符選擇決定。 我正在嘗試理解代碼,因此只是發布了當前的代碼。

在同一個類文件中,我有一個字符串數組,然后我可以使用.toString()轉換(在另一個.class文件中);

Game.class:

oneName = Ch.charName(q).toString();

這為playerOne的oneName了數組值,並將String數組結果轉換為單個String並且正常工作!

我的問題是:我能夠對一組int值做同樣的事嗎?

  • 將int數組更改為String數組,將String數組轉換為單個String然后將String轉換為int是可怕的編程,但我最好的解決方案?

     String onePunch = charPunch(q).toString(); int charPunchInt = Integer.parseInt(charPunch); 

我目前在Characters.class數組的返回行上得到StackOverflowError ,直到進程放棄。

我目前在Characters.class上獲得StackOverflowError

這是因為你在不停止的情況下反復調用相同的方法。 基本上,這是你的代碼看起來像(除了它的其余代碼):

public int charPunch(int q) {
    return charPunch(q);
}

因此它將使用相同的參數調用自身,並且除了填充堆棧內存之外什么都不做,直到您收到指示的錯誤。

一種可能的解決方案可能是在您的方法中添加一些邏輯來停止。 或者,您可能想要訪問數組的元素:

public int charPunch(int q) {
    int[] charPunch = {
        15, 
        10, 
        20, 
        25, 
        20, 
        20, 
        15, 
        20, 
        20, 
        25
    };
    return charPunch[q]; //<- using brackets [] instead of parenthesis ()
}

請注意,如果q的值小於0或大於所用數組的大小,則charPunch方法的當前實現可能會拋出IndexOutOfBoundsException


如果您嘗試執行此代碼:

String onePunch = charPunch(q).toString();
int charPunchInt = Integer.parseInt(charPunch);

它將無法編譯,因為您從charPunch返回一個int 一個int是一種最原始的,沒有任何方法可言 所以,你可以改變你的方法來返回一個Integer ,你可以訪問toString方法,但是通過這樣做,上面的代碼將一個整數轉換成一個字符串,將字符串轉換成一個整數(再次),這似乎無意義的。


我能夠對int值數組執行完全相同的操作嗎?

定義你真正想做的事情,然后你會得到預期的幫助。

有幾個問題可以解決你的問題。

函數charPunch(int q)中的整數值是否總是相同?

您是否嘗試將整個int數組轉換為String或只是通過函數傳遞的值? 在完成作業后,你在做什么?

無論哪種方式,您可能希望查看數組列表和增強的for循環語法(對於每個循環)。

// if values are immutable (meaning they cannot be changed at run time)
static final int charPunches [] = {15,10,20,25};

// function to return string value
protected String getCharPunchTextValue(int q){
    String x = null;
    for(int i: charPunches){ // iterate through the array
        if(q == i){// test equality
            x = Integer.toString(i);// assign string value of integer
        }
    }
    return x; // Return value, what ever needs this value may check for null to test if value exists
}    

暫無
暫無

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

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