Java - 结果输出不正确
Java - Result not outputting correctly
我正在尝试完成一个程序,该程序显示一周的平均、最热和最冷温度,还显示最热和最冷的日子。用户输入从周日到周六的 7 个温度。它几乎可以工作,但似乎底部附近的方法中有一个名为 searchTemp 的错误,此方法查看 highest/lowest 温度在温度数组中出现了多少次,然后创建所需大小的数组,然后迭代所有值,存储原始数组中出现 high/low 温度的索引,然后 returns 具有索引位置值的新数组。理想情况下,我会将这些值映射到包含星期日到星期六字符串的数组,并打印出温度最高或最低的所有日子。问题是,现在如果用户输入 18 作为最高值,然后他们再次输入 18,而不是程序输出类似 "Monday Wednesday" 的内容,它会输出 Wednesday Wednesday
谁能帮帮我?
public static int[] searchTemp(int[] array, int key) {
int count = 0;
for(int i = 0; i < array.length; i++) {
if(array[i] == key)
count++;
}
int[] indices = new int[count];
for(int j = 0; j < indices.length; j++) {
for(int i = 0; i < array.length; i++) {
if(array[i] == key)
indices[j] = i;
}
}
return indices;
}
}
我相信它就在这里
int[] indices = new int[count];
for(int j = 0; j < indices.length; j++) {
for(int i = 0; i < array.length; i++) {
if(array[i] == key)
indices[i] = i; <---------
}
}
应该是
indices[j] 不是 i 因为你在这上面使用了内部数组的长度。
searchTemp 应更改如下:
public static int[] searchTemp(int[] array, int key) {
int count = 0;
for(int i = 0; i < array.length; i++) {
if(array[i] == key)
count++;
}
int[] indices = new int[count];
for(int j = 0; j < indices.length; j++) {
for(int i = 0; i < array.length; i++) {
if(array[i] == key) {
if(j > 0 && indices[j - 1] == i){
continue;
}
else {
indices[j] = i;
break;
}
}
}
}
return indices;
}
这将 return 正确 hottest/coldest。
希望对您有所帮助!
我正在尝试完成一个程序,该程序显示一周的平均、最热和最冷温度,还显示最热和最冷的日子。用户输入从周日到周六的 7 个温度。它几乎可以工作,但似乎底部附近的方法中有一个名为 searchTemp 的错误,此方法查看 highest/lowest 温度在温度数组中出现了多少次,然后创建所需大小的数组,然后迭代所有值,存储原始数组中出现 high/low 温度的索引,然后 returns 具有索引位置值的新数组。理想情况下,我会将这些值映射到包含星期日到星期六字符串的数组,并打印出温度最高或最低的所有日子。问题是,现在如果用户输入 18 作为最高值,然后他们再次输入 18,而不是程序输出类似 "Monday Wednesday" 的内容,它会输出 Wednesday Wednesday
谁能帮帮我?
public static int[] searchTemp(int[] array, int key) {
int count = 0;
for(int i = 0; i < array.length; i++) {
if(array[i] == key)
count++;
}
int[] indices = new int[count];
for(int j = 0; j < indices.length; j++) {
for(int i = 0; i < array.length; i++) {
if(array[i] == key)
indices[j] = i;
}
}
return indices;
}
}
我相信它就在这里
int[] indices = new int[count];
for(int j = 0; j < indices.length; j++) {
for(int i = 0; i < array.length; i++) {
if(array[i] == key)
indices[i] = i; <---------
}
}
应该是 indices[j] 不是 i 因为你在这上面使用了内部数组的长度。
searchTemp 应更改如下:
public static int[] searchTemp(int[] array, int key) {
int count = 0;
for(int i = 0; i < array.length; i++) {
if(array[i] == key)
count++;
}
int[] indices = new int[count];
for(int j = 0; j < indices.length; j++) {
for(int i = 0; i < array.length; i++) {
if(array[i] == key) {
if(j > 0 && indices[j - 1] == i){
continue;
}
else {
indices[j] = i;
break;
}
}
}
}
return indices;
}
这将 return 正确 hottest/coldest。 希望对您有所帮助!