parking lot program in Java (BlueJ) [closed]

Posted on

Problem

The program is as following –

import java.util.*;
class ParkingLot
{
    Scanner sc=new Scanner (System.in);
    int vno,hours;
    double fee;
     int input()//to take input
    {
        System.out.println("Enter vehicle no. - ");
        int vno=sc.nextInt();
        System.out.println("Enter the hours -");
        int hours=sc.nextInt();
        return (hours);
    }
     double calculate()//to calculate fee
    {
        if(hours>=1)
        {
            double fee=3;
        }
        else if(hours<1)
        {
            double fee=3+(hours-1)*1.5;
        }
        return (fee);
    }
    void display()//to display fee
    {
        System.out.println("vehicle no. - "+vno+"     hrs = "+hours);
        System.out.println("fee = rs."+fee);
    }
    public static void main()
    {
        ParkingLot obj=new ParkingLot();
        obj.input();
        obj.calculate();
        obj.display();
    }
}

All I want to do is to take the calculated fee from the function called calculate and take the hours entered by the user to calculate the fee. But all I get as output is this –

Enter vehicle no. – 2248 Enter the hours – 2 (this is the input)

vehicle no. – 0
hrs = 0 fee = rs.0.0
(this is the output)

I cannot understand what the problem is. If just the problem can be pointed out, it would be very helpful.

Solution

There are a few problems i see with your code here. Correct me if i am wrong.

  1. Here you have declared your variables vno,hours and fee globally. So why do you need to declare them again in the methods (input and calculate)? Use the same globally declared variables.
  2. In this case your display method takes the vno, hours and fee which is declared globally and not the ones you declared in the methods. Try assigning a value to the global variables given and run the program to see what I mean.
  3. Also “input” method is to take values from the user. So why does it need a return statement at all?
  4. You can actually make it simpler by making sure that each of your method does only one thing at a time.

Leave a Reply

Your email address will not be published. Required fields are marked *