0

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 ("Enter 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?

2 Answers 2

6

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());
Sign up to request clarification or add additional context in comments.

2 Comments

How could I create and print a new string that consists of the state name (all in uppercase letters) followed by the city name (all in lowercase letters) followed again by the state name (uppercase)?
See the bit under "Update". Note that this will work now, since we've initialized city and state before we try to print them out.
0

String city = "";

String state = "";

or

String city = null;

String state = null;

Use the above declaration, this will solve your error

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.