2011-05-31 137 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;

使用上面的聲明,這將解決您的錯誤