变量初始化

时间:2011-05-31 02:02:52

标签: java variables initialization

我是Java的新手,我无法修复脚本方法中的错误。它说“变量城市和州可能尚未初始化”

以下是我如何声明变量:

String city;
String state;

以下是我的错误:

Scanner scan = new Scanner(System.in);
System.out.println ("Enter the city you grew up in: " + city);
city = scan.nextLine();
System.out.println ("Enter the state you live in: " + state);
state = scan.nextLine();

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:6)

您在初始化之前使用citystate。更改订单并将其从println声明中删除。

Scanner scan = new Scanner(System.in);
System.out.println ("Enter the city you grew up in: "); 
city = scan.nextLine();  // <-- Initializes city.
System.out.println ("Enter the state you live in: ");
state = scan.nextLine();  // <-- Initializes state.

<强>更新

System.out.println(state.toUpperCase() + city.toLowerCase() + state.toUpperCase());

答案 1 :(得分:0)

String city =“”;

String state =“”;

String city = null;

String state = null;

使用上述声明,这将解决您的错误