2017-03-31 125 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 :) –