字符串变量可能尚未初始化 [英] String Variable might not have been initialized
本文介绍了字符串变量可能尚未初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的代码:
import java.util.Scanner;
public class empMod
{
public static void main(String[] args)
{
int choice;
Scanner input = new Scanner(System.in);
do
{
choice = -1;
System.out.println("Employee Data:");
System.out.println("1. - Employee Name:");
System.out.println("2. - Employee Hire Date:");
System.out.println("3. - Employee Address:");
System.out.println("4. - Employee Number:");
System.out.println("5. - Exit");
choice = input.nextInt();
input.nextLine();
switch (choice)
{
case 1:
String empName = new String ();
System.out.println("Enter the name of the employee:");
String name = input.nextLine();
break;
case 2:
String empDate = new String ();
System.out.println("Enter the hire date of the employee:");
String date = input.nextLine();
break;
case 3:
String empAddress = new String ();
System.out.println("Enter the address of the employee:");
String address = input.nextLine();
break;
case 4:
String empNumb = new String ();
System.out.println("Enter the Employee number:");
int number = input.nextInt();
break;
case 5:
System.out.print("\n");
System.out.println("The name of the employee is: " + empName); // <-- This is the line where the error occurs.
break;
default:
continue;
}
}
while (choice != 6);
}
}
该程序的目的是让用户输入有关员工的信息,然后根据要求显示信息.当我去编译程序时,出现以下错误:
The intent of the program is to have the user input information about the employee, and then at request, have the information displayed. When I go to compile the program, I get the following error:
empMod.java:57: error: variable empName might not have been initialized
System.out.println("The name of the employee is:
" + empName);
^
虽然在另一种情况下会初始化字符串变量,所以我不确定这个问题.
The string variable is initialized in another case though, so I am not sure of the problem.
推荐答案
empName变量仅在 case 1
部分中初始化.那么,如果从未执行此代码块,而 case 5
部分是怎么办?由于变量从未初始化为任何内容,因此会显示什么内容?
The empName variable is only initialized in the case 1
section. So what would happen if this block was never executed, and the case 5
section was? What would be printed, since the variable has never been initialized to anything?
添加
String empName = "";
在循环之前.
这篇关于字符串变量可能尚未初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文