开发者

variable initialization

开发者 https://www.devze.com 2023-03-09 20:53 出处:网络
I am new to Java and I cant fix an error in a script method. It says \"variables city and state might not have been initialized\"

I am new to Java and I cant fix an error in a script method. It says "variables city and state might not have been initialized"

Here is how I declared the variable:

String city;
String state;

Here is where my errors are:

Scanner scan = new Scanner(System.in);
System.out.println ("En开发者_JAVA技巧ter the city you grew up in: " + city);
city = scan.nextLine();
System.out.println ("Enter the state you live in: " + state);
state = scan.nextLine();

Can anyone help?


You're using city and state before you initialize them. Change the order and remove them from the println statement.

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.

Update

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


String city = "";

String state = "";

or

String city = null;

String state = null;

Use the above declaration, this will solve your error

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号