variable initialization
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
精彩评论