2011-05-31 136 views
0

我是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(); 

谁能帮助?

回答

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()); 
+0

非常感谢! – Chickadee 2011-05-31 02:10:22

+0

不客气。 – 2011-05-31 02:12:05

+0

如何创建并打印一个由州名(全部用大写字母) 后跟城市名(全部用小写字母)和州名(大写)组成的新字符串? – Chickadee 2011-05-31 02:15:42

0

字符串城市= “”;

String state =“”;

String city = null;

String state = null;

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