1
import java.util.Scanner;

public class Piggy {

    float poson;

public Piggy() {

    this.poson = 0;
    System.out.println("Dimiourgithike koumparas me diathesimo ipoloipo: " + poson + "€");
}

public Piggy(float poso) { 

    if (poso >= 0) { 
        this.poson = poso;
        System.out.println("Dimiourgithike koumparas me diathesimo ipoloipo: " + poso + "€");
    } else {
        this.poson = 0;
        System.out.println("Dimiourgithike koumparas me diathesimo ipoloipo: " + poso + "€");
    }
}

public float epistrofiYpoloipou() {
    return poson;
}

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    String arxiko_poso;

    System.out.println("Doste to arxiko poso pou tha periexei o koumparas: ");
    arxiko_poso = input.nextLine();
    if (arxiko_poso.equals("")) {
        Piggy koumparas = new Piggy();
    } else {
        float init_value = Float.parseFloat(arxiko_poso);
        Piggy koumparas = new Piggy(init_value);
    }

    float upoloipo = koumparas.epistrofiYpoloipou();
    System.out.println("To upoloipo einai: " + upoloipo + "€");
   }
}

Hello. I have made two constructors, one has no arguments and initializes "poson" with 0 and the other takes user input and initializes "poson" with that.

In main() i want to call the first constructor if the user does not input anything when asked, so i created a string and when the user inputs something i convert the string to float and call the second constructor.

But then when i try to call my "epistrofiYpoloipou" function using "koumparas.epistrofiYpoloipou();" i get a "cannot find symbol" error. What am i doing wrong here?

user3120283
  • 85
  • 2
  • 9

1 Answers1

1

You should declare the koumparas variable prior to the if-else statement if you wish to use it outside that statement:

Piggy koumparas;
if (arxiko_poso.equals("")) {
    koumparas = new Piggy();
} else {
    float init_value = Float.parseFloat(arxiko_poso);
    koumparas = new Piggy(init_value);
}

float upoloipo = koumparas.epistrofiYpoloipou();
Eran
  • 387,369
  • 54
  • 702
  • 768
  • Yes this works. Thank you. But can you elaborate on why i have to do that? – user3120283 Nov 12 '17 at 15:10
  • @user3120283 a variable is available only in the scope in which it is declared. `{}` is a scope. You declared the `koumparas` variable in two scopes - the scope of the `if` body, and the scope of the `else` body. Outside these scopes, that variable is unknown to the compiler. – Eran Nov 12 '17 at 15:12
  • Oh i see. Yeah, i'm dumb nevermind. Thank you sir :) – user3120283 Nov 12 '17 at 15:16