0

This is the code. I gives me an error where the switch is. Please help. Maybe a link to a site where i can learn this.

public class Main{
public static void main(String[] args) {
    int swValue;

    System.out.println("***************************************Menu***************************************");
    System.out.println("Spauskite 1 jei norite atspauzdinti programje sukurtu objektu sarasus");
    System.out.println("Spauskite 2 jei norite sukurti naujus objektus, ju duomenis ivedant is klavieturos");
    System.out.println("Spauskite 3 jei norite iskviesti objektu metodus");

    switch (swValue) {
    case 1: System.out.println("1 Selected");
        break;
    case 2: System.out.println("2 Selected");
        break;
    case 3: System.out.println("3 Selected");
        break;
    default: System.out.println("Invalis selection");
    break;
    }
1
  • not much of a menu if the user can't choose an option first (aka: ask the user and initialize swValue with whatever the user tells you) Commented Dec 10, 2013 at 18:18

3 Answers 3

2

It is a compiler error to use a local variable before it's initialized, and you didn't initialize it.

It looks like you will want to read the user input and initialize swValue before the switch statement.

Sign up to request clarification or add additional context in comments.

3 Comments

Can u give me an example how to fix this?
There are many ways, but two off the top of my head: 1) Initialize it to some value with int swValue = 0;, but that's not very useful here. 2) Use a Scanner to read the user input and assign the value to swValue.
A few more ways: 3) Use a BufferedReader to read user input, converting it to an int with Integer.parseInt. 4) Read a command-line parameter in the args parameter of main and convert it to an int. 5) Use JOptionPane to ask the user via a dialog box and convert the answer to an int.
1

Try creating some kind of input reading;

    //print out menu options

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    try {
       swValue = Integer.parseInt(br.readLine());
    } catch (IOException ioe) {
       ioe.printStackTrace();
    }

    //switching code

Comments

0

swValue isn't initialised i.e. there is not value assigned to it. So, how can you compare it to anything ?

If you want to get a value from the user, you can do either :

  1. Accept swValue as a parameter :

    void main(String[] args, int swValue)

  2. Use the Scanner or BufferedReader classes to get input at run-time.

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.