Tower's Vault Tower's Vault - 3 months ago 8
Java Question

Java Newbie error: cannot find symbol

I want to allow the person to type for example 112 into the console, press enter, and then end up with "Hello, Mars." as the answer.

I'm getting stuck on "error: cannot find symbol".

import java.util.Scanner;

public class Main {
public static void main(String[] args)
{
int n1 = userVar;

switch ( userVar )
{
case 111:
System.out.println("Hello, Earth.");
break;
case 112:
System.out.println("Hello, Mars.");
break;
case 113:
System.out.println("Hello, Jupiter.");
break;
default:
System.out.println("Hello, Space.");
}

Scanner keyboard = new Scanner(System.in);
n1 = keyboard.nextInt();
}
}


Now, I've tried changing the int to

int userVar;


and

Scanner keyboard = new Scanner(System.in);
userVar = keyboard.nextInt();


But ultimately got stuck with an "error: variable userVar might not have been initialized". Note that I am doing this on Ideone.

Answer

First, give userVar a default value :

int userVar = 0;

Then attempt to assign to it user input :

Scanner keyboard = new Scanner(System.in);
userVar = keyboard.nextInt();