我只是想知道是否可以创建这样的东西:
String variable = "name of the variable I'm checking";
for (int i = 0; i < 16; i++)
{ // if it's possible what type should the check variable be?
check = (array[0].equals("value1") || array[0].equals("value2") ?
"some value or null?" : throwException(i, variable);
}
public void throwException(int index, String name) throws TelegrammException
{
throw new TelegrammException("Wrong telegramm format at position: "
+ index + "; Name: " + name);
}
如果这不可能,您能否建议一个如何做类似事情的良好实践?
最佳答案
技术上是的,如果您将 throwException
方法的返回类型更改为 String
。
public String throwException(int index, String name) throws TelegrammException
但是,拥有一个表面上返回一个实际上总是抛出字符串的方法是非常不寻常的,并且几乎肯定会使您的代码的 future 读者感到困惑。表达意图的惯用方式是根本不使用三元表达式:
if (array[0].equals("value1") || array[0].equals("value2"))
{
check = "some value or null?";
}
else
{
throwException(i, variable);
}
关于java三元运算符返回函数结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48803174/