Java 在这种情况下,为char提供默认值

Java 在这种情况下,为char提供默认值,java,Java,根据业务需求,根据传递的输入,我需要返回一个适当的值 例如,如下所示 public String getValue() { if (array.length <2 ) { return ""; } if (array.length == 4) { return "A"; } if (array.length == 3) { return "B"; } if (array.length == 2) { return "B"; } return "Z"; } char c

根据业务需求,根据传递的输入,我需要返回一个适当的值

例如,如下所示

public String getValue()
{

if (array.length <2 ) 
{
return ""; 
}

if (array.length == 4) 
{
return "A";
}
if (array.length == 3) 
{
return "B";
}
if (array.length == 2) 
{
return "B";
}

return "Z";

}


char c = new Myclass().getValue().charAt(0);
//我的问题是,如果长度小于2,那么它将返回null,从而引发java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:0异常


请让我知道,处理这个问题的最佳方法是什么???

您可以将它放在if语句中,如下所示

if(Myclass().getValue() != null && Myclass().getValue().length() > 0) {
     c = new Myclass().getValue().charAt(0);
}

您可能希望在if语句之外的某个地方定义c,最好的处理方法是根据您的需要/上下文

以下是一些您可以根据需要/可能性尝试的想法:

确保没有长度为的数组。您可以将公共字符串getValue返回类型切换为char,因为您只返回char,或者,如果不是选项,则返回null字符:

if (array.length <2 ) 
{
     return "\0"; 
}
然后像这样使用它:

char c = Myclass.getValue(array);

您的代码格式不正确-什么是数组?还有,你寻求的解决办法是什么?是只有您知道的东西吗?您可以修改返回值的类型吗?我不知道您到底想做什么,但您所做的一切似乎都是错误的。为什么您返回字符串,但只期望char?您无法读取空字符串的第一个字符,您实际想做什么?不要将字符串与==:val!==>进行比较!val.isEmptyThanks,修复并添加了更多解释
public static char getValue(Object[] array)
char c = Myclass.getValue(array);