2017-03-31 48 views
1

一個小程序,我編碼的一部分:的Java:方法返回String或詮釋

String maxs = ""; 
int maxi = 0; 

在這一部分,我定義了兩個變量intString

public Class(String max){ 
    try { 
      this.maxi = Integer.parseInt(max); 
     }catch (Exception e){ 
      this.maxs = max; 
     } 
} 

我想這樣我會去定義這兩個變量之一,如果字符串不解析爲int它將被保存爲正常的字符串。

現在,我需要檢查什麼,我需要返回:

private TypeOfReturn getMax(){ 
    if(this.maxi == 0){ 
     // return maxs (return String) 
    } else if (this.maxs.equals("")) { 
     // return maxi (return int) 
    } else return null; 
} 

的quastion是,我怎麼補法getMax()的缺失部分?

在Java中它甚至可以使用嗎?

+2

TypeOfReturn可以是'Object'。 –

+0

this.maxi = Integer.parseInt(max);最大來自哪裏? – Omore

+0

檢查這個http://stackoverflow.com/questions/2127318/java-how-can-i-do-dynamic-casting-of-a-variable-from-one-type-to-another –

回答

1

使用Object而不是TypeOfReturn 您可以將TypeoOfReturn更改爲Object,然後返回相應的類型。

+0

謝謝,我做到了這一點,它確實工作。 –

0

使您的TypeOfReturn成爲String對象類型,並將maxi轉換爲String並在else if條件中返回該String。

注意:不能同時返回int和String。

+0

我將TypeOfReturn更改爲Object。它確實有效。無論如何感謝 –

1

另一種方法來找出快,如果一個字符串是一個數字或沒有,這是你的程序的主要部分,是使用lambda表達式在Java 8這樣的:

String max = "123"; 
boolean isNumber = max.chars().allMatch(Character::isDigit); 
System.out.println(isNumber); 

哪位能給你輸出

true 
+0

謝謝..非常有幫助 –

+0

很高興我可以幫助,如果你覺得它有幫助,請給我一個upvote :) –