Ahmadz Issa
Ahmadz Issa

Reputation: 765

I get the same number with addition method?

I was practicing on a bank account program , and I faced this small problem.

I made it as a method the make it easier to understand.

The main method

public static void main(String[] args) {
    Scanner in=new Scanner(System.in);
    double b=0;

    while(b!=-1){
        b=in.nextInt();
        ddd(b);
    }
}

The addition method

public static void Addition(double b){
    double g=0;
    g+=b; 

    System.out.println( "GGGGGGGG"+  g );   
}

The problem is that I get the same input I enter each time . I know that the problem from the

double g=0;

Because each time I call the method addition g will be initialized to Zero because of this statement double g=0;, but I should to initial it, or I will get compilation error.

What should I do to fix this problem.

Upvotes: 0

Views: 98

Answers (2)

Jace J McPherson
Jace J McPherson

Reputation: 450

You can make the double g a member of the class by declaring it outside of methods. So here's an example class

class TestClass {

    static double g = 0;

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        double b = 0;
        while (b != -1) {
            b = scan.nextDouble() //you need to change nextInt() to nextDouble()
            add(b);
        }
        System.out.println(g);
    }

    public static void add(double b) {
        g += b;    //g refers to the variable about the main method
    }
}

This may not be exactly how your class works, but using the variable g outside of a method makes sure the class retains its value even when the method has ended. Hope this helps!

Upvotes: 4

Koray Tugay
Koray Tugay

Reputation: 23780

Initialize it just before the while statement.

Upvotes: 0

Related Questions