我正在尝试创建一个程序,用于打印一周中每天的温度。我不知道为什么我的代码正在打印" null"而不是一周中的每一天。我之前从未见过这个错误(我在开始编程课程中)并且我无法在教科书中找到任何信息。到目前为止,这是我的代码......
import java.util.Scanner;
public class TempsInOneWeek {
public static void main(String[] args) {
Scanner scnr = new Scanner (System.in);
final int NUMBER_OF_DAYS = 7;
String[] dayOfWeek = new String[NUMBER_OF_DAYS];
int[] temp = new int [7]; //array of 7 temperatures for 7 days of the week
int tempForDay = 0;
int i = 0; //loop variable
System.out.println("Enter the temperature for each day, beginning with Sunday.");
for (i = 0; i <= temp.length; ++i) {
temp[i] = scnr.nextInt();
System.out.println(dayOfWeek[i] + "/'s temperature was: " + temp[i] + " degrees.");
}
dayOfWeek[i] = "Sunday";
dayOfWeek[i] = "Monday";
dayOfWeek[i] = "Tuesday";
dayOfWeek[i] = "Wednesday";
dayOfWeek[i] = "Thursday";
dayOfWeek[i] = "Friday";
dayOfWeek[i] = "Saturday";
temp[i] = scnr.nextInt();
temp[i] = scnr.nextInt();
temp[i] = scnr.nextInt();
temp[i] = scnr.nextInt();
temp[i] = scnr.nextInt();
temp[i] = scnr.nextInt();
temp[i] = scnr.nextInt();
}
显然阵列在错误的位置,但它现在不会影响输出,所以我想表明我至少在这里尝试。真的我唯一的问题是如何打印一周的日子。关于如何处理上面的两个数组,可能还有一点方向。
答案 0 :(得分:0)
只需在循环
之前移动以下分配dayOfWeek[i] = "Sunday";
dayOfWeek[i] = "Monday";
dayOfWeek[i] = "Tuesday";
dayOfWeek[i] = "Wednesday";
dayOfWeek[i] = "Thursday";
dayOfWeek[i] = "Friday";
dayOfWeek[i] = "Saturday";
答案 1 :(得分:0)
当您尝试从阵列中检索数据时......
System.out.println(dayOfWeek[i] + "/'s temperature was: " + temp[i] + " degrees.");
...此时你还没有把任何东西放到数组中。
创建阵列时......
String[] dayOfWeek = new String[NUMBER_OF_DAYS];
这将创建数组并使用 null
填充每个索引请记住,当您声明并初始化数组时,除非您显式填充数组,否则它将填充数组类型的默认值(在您的情况下为String - 并且String的默认值为null)。
因此,您需要在尝试检索数据之前将实际填充数组的代码行移动到 ...
dayOfWeek[i] = "Sunday";
dayOfWeek[i] = "Monday";
dayOfWeek[i] = "Tuesday";
dayOfWeek[i] = "Wednesday";
dayOfWeek[i] = "Thursday";
dayOfWeek[i] = "Friday";
dayOfWeek[i] = "Saturday";
for (i = 0; i <= temp.length; ++i) {
temp[i] = scnr.nextInt();
System.out.println(dayOfWeek[i] + "/'s temperature was: " + temp[i] + "
degrees.");
}