-1

I'm just having a practise at some java coding and was wondering if there was a way to use a String if else statement to change change an integer, as the following doesn't like the c = a * b

    int a, b, c;

    Scanner sc = new Scanner(System.in);
    System.out.println("Enter first number");
    a = sc.nextInt();
    System.out.println("Enter * + - or / ");
    String d = sc.nextLine();
    System.out.println("Enter second number");
    b = sc.nextInt();
    
    if (d.equals("*")){
        c = a * b;
            
    }
    System.out.println(a + " " + d + " b " + " = " + c);
    
    
Danbo
  • 1
  • 2
    [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – T.J. Crowder Aug 20 '21 at 16:24
  • 1
    Does this answer your question? [Variable might not have been initialized error](https://stackoverflow.com/questions/2448843/variable-might-not-have-been-initialized-error) – QBrute Aug 20 '21 at 16:26
  • What is `d` before entering the `if` statement? Add a debug-print like `System.out.println(d)` before `if` and update your question with its output. Also: add a debug-print inside the `if` block to get notified on console when if-block was entered. – hc_dev Aug 20 '21 at 16:28
  • 2
    What does "the following doesn't like" mean? I have never seen such an error message. I highly suggest you add the real error message if you get an error, or an example with expected and actual values if the result is not what you are expecting. – McPringle Aug 20 '21 at 16:34

1 Answers1

4

This happens because the variable "c" is initialized only if the conditional if (d.equals("*")) {...} is true, to solve this you have two options:

Just initialize "c" :

        int a, b, c = 0;

or add else statement

        if (d.equals("*")){
            c = a * b;
        }else {
            c = 0;
        }
fneira
  • 291
  • 1
  • 8
  • 1
    ️ Important advice here: The `else` branch makes each `if` statement _complete_ (and thus less error-prone) because each paths are covered. – hc_dev Aug 20 '21 at 16:30
  • The java compiler checks all possible path to see if local variables are initialized or not. in your code snipped only place c is getting initialized is if statement. it does not find any other path where c is getting initialized .hence it generates a compile time error – vaibhavsahu Aug 20 '21 at 16:35