gpt4 book ai didi

java - 满足 Java 的返回要求

转载 作者:太空宇宙 更新时间:2023-11-04 11:48:59 28 4
gpt4 key购买 nike

所以我相对较新,我有以下代码,我想知道如何制作这样我可以返回临时变量,同时满足java的返回要求。我希望返回临时值,但由于它位于 if-else block 内,因此从技术上讲,它不会在其外部初始化。不知道该怎么做

public String put(String id, String name) {
String temp;
for (int i=0;i<ids.length;i++) {
if (!(ids[i].equalsIgnoreCase(id))) {
if (ids.length<10){
ids[ids.length]=id;
names[names.length] = name;
}
else
System.out.println("There are too many members in the collection");
}
else

if ((ids[i].equalsIgnoreCase(id))) {
temp = names[i];
names[i] = name;
return temp;
}
}
}

最佳答案

您可以使用 null 或空来初始化您的 temps 属性, 然后在方法的 then 末尾返回它,而不是在 else block 中:

public String put(String id, String name) {
String temp = null;//initialize your attribute with null or "" empty
for (int i = 0; i < ids.length; i++) {
if (!(ids[i].equalsIgnoreCase(id))) {
if (ids.length < 10) {
ids[ids.length] = id;
names[names.length] = name;
} else {
System.out.println("There are too many members in the collection");
}
} else if ((ids[i].equalsIgnoreCase(id))) {
temp = names[i];
names[i] = name;
}
}
//return temp in the end if it not changes i the else block it return null or ""
return temp;
}

因此,如果 temp 未更改,则返回 null

关于java - 满足 Java 的返回要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42044000/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com