我被困在一个作业中,我们必须用“否”替换来自"is"数组的每个输出,并保持任何其他输出不变。
我一直收到错误 cannot convert from String to String[]
,我不确定如何解决这个问题,因为我找不到任何 String
到 Javadoc 中的 String[]
转换。
一段时间以来,我一直在努力寻找解决方案,所以我只需要朝着正确的方向努力。
String[] makeItANegativeArray(String[] inputArray) {
String x = "no";
if (inputArray.equals("yes")) {
return x;
} else {
return inputArray;
}
}
最佳答案
让我们看一下代码
//Start the function
String[] makeItANegativeArray( String [] inputArray ) {
// function needs String[] as input
// function suspects String[] as output (or return)
// initialise the variable x
String x = "no";
// if the input array is equal to the string VALUE "yes"
// (which is WEIRD because it's an ARRAY not a VALUE)
if (inputArray.equals("yes"))
{
//return A VALUE
//so here we return a VALUE while the function is suspecting an ARRAY
//this causes the error
return x;
}
else
{
//return an array
//(hence if this happens, the function terminates at the first iteration)
return inputArray;
}
}
显然,您的输入是一个数组
,您的输出也应该是一个数组
。
因此,在返回任何内容之前,您必须遍历输入数组的每个元素并构造和输出数组。
例如:
String[] makeItANegativeArray( String[] inputArray ) {
String x = "yes";
String y = "no";
for (int i = 0; i < inputArray.length; i++)
{
if (inputArray[i].equals("yes"))
{
inputArray[i] = y;
}
else
{
inputArray[i] = x;
}
}
return inputArray;
}
它所做的是将数组中的每个“yes”变成“no”,将每个“no”变成“< em>是的”。 所以它有点“反转”数组。
这是它应该做的吗?
或者,
如果您只是想将整个数组变成只有“no”的数组,那么请执行以下操作:
String[] makeItANegativeArray( String[] inputArray ) {
String x = "no";
for (int i = 0; i < inputArray.length; i++)
{
if (inputArray[i].equals("yes"))
{
inputArray[i] = x;
}
}
return inputArray;
}
关于java - 更改数组的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19082585/