我希望用户输入一个字,以便将其分配给String day
。输出是
在DaysOfTheWeek.main(DaysOfTheWeek.java:15)的线程“main”java.lang.NullPointerException中的异常
import java.util.*;"
public class DaysOfTheWeek {
static Scanner scan;
public static void main(String[] args) {
System.out.println("What day is it today?");
String day = scan.next();
int dayNumber = 0;
switch (day.toLowerCase()) {
case "sunday":
dayNumber = 0;
break;
case "monday":
dayNumber = 1;
break;
case "tuesday":
dayNumber = 2;
break;
case "wednesday":
dayNumber = 3;
break;
case "thursday":
dayNumber = 4;
break;
case "friday":
dayNumber = 5;
break;
case "saturday":
dayNumber = 6;
break;
}//switch
}//main
}//end public class
答案 0 :(得分:1)
您没有初始化scan
对象,因此您获得了空指针异常。您应该按照此处有关如何read in input from the console的说明进行操作。
答案 1 :(得分:0)
您尚未初始化扫描仪。
此外,无需将此扫描仪用作静态扫描仪。最好在主方法中初始化扫描仪。
import java.util.*;
public class DaysOfTheWeek {
public static void main(String[] args) {
System.out.println("What day is it today?");
Scanner scan = new Scanner(System.in);
String day = scan.next();
int dayNumber = 0;
switch (day.toLowerCase()) {
case "sunday":
dayNumber = 0;
break;
case "monday":
dayNumber = 1;
break;
case "tuesday":
dayNumber = 2;
break;
case "wednesday":
dayNumber = 3;
break;
case "thursday":
dayNumber = 4;
break;
case "friday":
dayNumber = 5;
break;
case "saturday":
dayNumber = 6;
break;
}//switch
请记住,如果你想使用像Scanner这样的任何对象,那就更好,更容易地使用它。
import java.util.*;
public class DaysOfTheWeek {
public static void main(String[] args) {
System.out.println("What day is it today?");
String day = new Scanner(System.in).next();
int dayNumber = 0;
switch (day.toLowerCase()) {
case "sunday":
dayNumber = 0;
break;
case "monday":
dayNumber = 1;
break;
case "tuesday":
dayNumber = 2;
break;
case "wednesday":
dayNumber = 3;
break;
case "thursday":
dayNumber = 4;
break;
case "friday":
dayNumber = 5;
break;
case "saturday":
dayNumber = 6;
break;
}//switch
因此main方法中的这段代码也是如此。
String day = new Scanner(System.in).next();