-2

I am new to Java and just started.

This is my current code:

 public class MathWork {
    public static void main(String[]args) {
        System.out.println("Enter 3 numbers below for A, B and C");
        Scanner input = new Scanner(System.in);
        System.out.println("Enter A: ");
        double a;input.nextDouble();
        System.out.println("Enter B: ");
        double b;input.nextDouble();
        System.out.println("Enter C: ");
        double c;input.nextDouble();

        System.out.println("X = "+(a+b+c));
        System.out.println("Fuel = ");
        System.out.println("Mean = ");
        System.out.println("Aint = ");
        System.out.println("geo = ");

    input.close();  
    }
}

When I try to run this an error appears for the print statement for X saying that "The local variable a may not have been initialized" but for all three variables. The variables are supposed to be equal to what numbers are inputed so I don't really know how to fix this.

Also yes, I have import java.util.Scanner; at the top.

craigcaulfield
  • 3,241
  • 10
  • 29
  • 38
Ams6483
  • 3
  • 2

2 Answers2

3

Because you are not assigning anything to a , b, c

there are two ways to assign user's entered value to a variable. first :

double a = input.nextDouble();

and the second one is :

double a = 0;
a = input.nextDouble();

so you code becomes :

System.out.println("Enter A: ");
double a = input.nextDouble();
System.out.println("Enter B: ");
double b = input.nextDouble();
System.out.println("Enter C: ");
double c = input.nextDouble();
Mohsen_Fatemi
  • 2,221
  • 2
  • 15
  • 24
0

You have typos in your code. It should be

double a = input.nextDouble();

and not

double a;input.nextDouble();

same for the other variables.

Right now you have two statements. Easy to see if we put a linebreak after the semicolon:

double a;
input.nextDouble();

Meaning that you create a variable double a, but without value and then you read a double-value but do not put it anywhere. It just goes into the trash directly.

Zabuzard
  • 23,461
  • 7
  • 54
  • 77
  • same for the other variables. Otherwise you have two statements, like double a; input.nextDouble(); what you mean by this – stacktome Oct 09 '19 at 20:49
  • Right now, with the semicolon, it is two statements. It is not "create a variable, read a value and put the value to the variable". It is "create a variable, dont use it. read a value, dont use it". Which is easier to spot once we have the linebreak after the semicolon. – Zabuzard Oct 09 '19 at 20:53