Java Program to Find Area of Rectangle

Code

import java.util.Scanner;

public class AreaOfRectangle
{
    public static void main(String args[])
    {
        int length, breadth, area;
        
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the length of the rectangle: ");
        
        length = sc.nextInt();
        System.out.println("Enter the breadth of the rectangle: ");
        
        breadth = sc.nextInt();
        area = length* breadth;
        System.out.println("Area of the rectangle is: "+area);
    }
}

Output

Enter the length of the rectangle: 10
Enter the breadth of the rectangle: 20
Area of the rectangle is: 200

Java Program to Find Area of Circle

Code

import java.util.Scanner;

public class Circle 
{
    public static void main(String[] args) 
    {
        int r;
        double pi = 3.14, area;
        
        Scanner s = new Scanner(System.in);
        System.out.print("Enter radius of circle: ");
        r = s.nextInt();
        
        area = pi * r * r;
        System.out.println("Area of circle: "+area);
    }            
}

Output

Enter radius of circle: 5
Area of circle: 78.5

Python Exercise: Ice Cream Sundae - Ordering Menu

You are expected to build an interactive application to order ice cream Sundays in an ice-cream parlour.
You are expected to use the concepts you learnt from the Object-Oriented programming session. The complete building process is divided into questions given below after you solve all the questions you will the complete ordering application.

Let's get started!!

Q1: Declare a class "ice_cream". It needs to have the following constants and instance methods defined.

  1. Radius of a small scoop (r_small = 1.5)
  2. Radius of large scoop (r_large = 2.5)
  3. Value of pie (pi = 3.14)
  4. An instance method "flavour" - it should print enter your flavour.

Given below is the example of a sample class and its methods and variables for reference:

class chocolate:

   chocolate_length=10
   chocolate_breadth=2
   
   def area(self):
       print("Enter your favourite chocolate")

# Declare class here:
class ice_cream:
    # Declare class variables:
    r_small = 1.5
    r_large = 2.5
    pi = 3.14
    
    # Declare instance methods:
    def flavour(self):
        print("Enter your flavour")

# Call the class:
order = ice_cream()

order.flavour()        

Q2: Modify the class "ice_cream" to add a method which can calculate the cost of the Ice cream based on its size.

Cost of ice cream is 0.5$ per unit volume. Take the input from the user about what size of ice cream scoops they want small or large. Based on that calculate the volume of the scoop and use the volume and the cost per volume to calculate the cost of ice cream.

Hint: Declare a class similar to example above. Add new function that calculates the cost depending on the scope size. Use If-else statement to calculate ice-cream cost.

class ice_cream:
    r_small = 1.75
    r_large = 2.5
    pi = 3.14
        
    def flavour(self):
        print("Enter your flavour")
        size = input("Would you like a small scoop or a large scoop (enter s/l)")
        cost = self.cost_ice_cream(size)
        print ("The cost of ice cream is ", cost)
        
    def cost_ice_cream(self, size):
        if size=="s":
            vol = 4/3 * (self.r_small**3)
            cost = vol * 0.5
            return cost
        elif size=="l":
            vol = 4/3 * (self.r_large**3)
            cost = vol * 0.5
            return cost
        else:
            print("Please enter a valid size")
            
# Call the function:
order = ice_cream()
order.flavour()            

Q3: In the above function find a way to round up the cost to the next integer value.

Hint: In the same class as above, add a additional element to the cost variable that rounds up the cost to the next nearest integer.
For example: if the cost is 10.41, the output should be 11$

##### For rounding up an integer value you could use either the ceil() or round()

import math

class ice_cream:
    r_small = 1.75
    r_large = 2.5
    pi = 3.14
        
    def flavour(self):
        print("Enter your flavour")
        size = input("Would you like a small scoop or a large scoop (enter s/l)")
        cost = self.cost_ice_cream(size)
        print ("The cost of ice cream is ", math.ceil(cost))
        
    def cost_ice_cream(self, size):
        if size=="s":
            vol = 4/3 * (self.r_small**3)
            cost = vol * 0.5
            return cost
        elif size=="l":
            vol = 4/3 * (self.r_large**3)
            cost = vol * 0.5
            return cost
        else:
            print("Please enter a valid size")
  
 # Call the function:
order = ice_cream()
order.flavour()                     

Question 4: Modify the flavour function to give the options of available flavours and take as input the choice of the customer.

The available options are Vanilla, Chocolate, Butterscotch, Blue_berry.

Hint: Add a new function that asks the user to input the choice of flavour.

import math

class ice_cream:
    r_small = 1.5
    r_large = 2.5
    pi = 3.14
        
    def flavour(self):
        print ("Available flavours of ice cream are Vanilla, Chocolate, Butterscotch, Blue_berry")
        flv = input("Which flavour of ice cream would you like ")
        size = input("Would you like a small scoop or a large scoop (enter s/l)")
        i_cost = self.cost_ice_cream(size)
        print ("The cost of ice cream is ", math.ceil(i_cost))
        
    def cost_ice_cream(self, size):
        if size=="s":
            vol = 4/3 * (self.r_small**3)
            cost = vol * 0.5
        elif size=="l":
            vol = 4/3 * (self.r_large**3)
            cost = vol * 0.5
        else:
            print("Please enter a valid size")
        return cost
        
order = ice_cream()
order.flavour()

Question 5: Build a new class called "toppings". It should have all the functionality of the ice_cream class.

The toppings class will also have a method which will take as input the choice of toppings that the customer wants.
The available choices of toppings are: Hot_fudge, Sprinkles, Caramel, Oreos, Nuts

Hint: Create a new class that ask the user to choose one or more toppings

class toppings(ice_cream):
    
    def sel_toppings(self):
        print ("Available toppings are Hot_fudge, Sprinkles, Caramel, Oreos, Nuts")
        top = input ("Enter any number of toppings of your choice separated by a comma: ")
        top_list = top.split(",")
        print ("The toppings you selected are : ",top_list)
        
sundae = toppings()
sundae.sel_toppings()       

Question 6: Add a method to calculate the cost of selected toppings, given the cost of each of the topping is 2$.

Hint: Now in the class for toppings, add a function to calculate the cost per topping added.

class toppings(ice_cream):
    
    def sel_toppings(self):
        print ("Available toppings are Hot_fudge, Sprinkles, Caramel, Oreos, Nuts")
        top = input ("Enter any number of toppings of your choice separated by a comma: ")
        top_list = top.split(",")
        t_cost = self.top_cost(top_list)
        print ("The cost for selected toppings is ",t_cost)
        
    def top_cost(self, top_list):
        cost = len(top_list) * 2
        return cost
        
 sundae = toppings()
sundae.sel_toppings()       

Question 7:  Now you have all the functionality needed to create the ordering menu. 

1. An order can be for simply Ice Cream or an Ice Cream sundae. 
2. There can be multiple items in an order. 
3. Calculate the cost of each order placed.

Hint: Club both the class you have created above and finally create an Ice-cream ordereing machine that display a welcome message: "Welcome to  Ice Cream parlour". Asks the user if he/she wants and ice cream or ice cream-sundae. Ask the choice of flavour and toppings and returns the total cost. Dont forget to ask if the user wants another item after he finishes ordering the first one

import math

class ice_cream:
    r_small = 1.5
    r_large = 2.5
    pi = 3.14
        
    def flavour(self):
        print ("Available flavours of ice cream are Vanilla, Chocolate, Butterscotch, Blue_berry")
        flv = input("Which flavour of ice cream would you like ")
        size = input("Would you like a small scoop or a large scoop (enter s/l)")
        i_cost = self.cost_ice_cream(size)
        if order_type == "i":
            print ("The cost of the ice Cream is ", math.ceil(i_cost))
        return math.ceil(i_cost)
        
    def cost_ice_cream(self, size):
        if size=="s":
            vol = 4/3 * (self.r_small**3)
            cost = vol * 0.5
        elif size=="l":
            vol = 4/3 * (self.r_large**3)
            cost = vol * 0.5
        else:
            print("Please enter a valid size")
        return cost
            
    
class toppings(ice_cream):
    
    def sel_toppings(self):
        print ("Available toppings are Hot_fudge, Sprinkles, Caramel, Oreos, Nuts")
        top = input ("Enter any number of toppings of your choice separated by a comma: ")
        top_list = top.split(",")
        i_cost = self.flavour()
        t_cost = self.top_cost(top_list)
        print ("The cost for sunday is ",t_cost+ i_cost)
        
    def top_cost(self, top_list):
        cost = len(top_list) * 2
        return cost
    

print ("Welcome to the upGrad Ice Cream parlour")
 
while True:     
    print ("Would like an ice cream(i) or a Sundae(s)?")
    order_type = input("Enter your response (i/s)")
    if order_type == "i":
        order = ice_cream()
        order.flavour()
    elif order_type == "s":
        sundae = toppings()
        sundae.sel_toppings()
    else:
        print ("Enter a valid choice")
        
    print ("Would like to order anything else")
    more = input ("Enter your response as (y/n)")
    
    if more == "n":
        break 

What is the Advantage of Generic Collection in Java?

Here are 3 main advantages:

  1. Typecasting not required
  2. Type-Safe, checked at compile time
  3. Confirms the stability of the code by making it bug detectable at compile time

How to Make Map Synchronized in Java?

Use Collections class

public static Map synchronizedMap(Map m){}
public static SortedMap synchronizedSortedMap(SortedMap m){}

How to Create Synchronized Set in Java?

Using Collections Class

public static Set synchronizedSet(Set s){}
public static SortedSet synchronizedSortedSet(SortedSet s){}

Why do we Override equals() method in Java?

The equals method is used to check whether two objects are the same or not. It needs to be overridden if we want to check the objects based on the property.

For example, Employee is a class that has 3 data members: id, name, and salary. However, we want to check the equality of employee object by the salary. Then, we need to override the equals() method.

How to Override Equals and HashCode method in Java?

Here are some key points:

  • if you override equals, you must override hashCode.
  • hashCode must generate equal values for equal objects.
  • equals and hashCode must depend on the same set of significant fields. You must use the same set of fields in both of these methods. You are not required to use all fields. For example, a calculated field that depends on others should very likely be omitted from equals and hashCode
  • if a class overrides equals, it must override hashCode
  • when they are both overridden, equals and hashCode must use the same set of fields
  • if two objects are equal, then their hashCode values must be equal as well
  • if the object is immutable, then hashCode is a candidate for caching and lazy initialization

Overriding Equal

@Override
public boolean equals(Object o) {
    if (o == this)
        return true;
    if (!(o instanceof Money))
        return false;
    Money other = (Money)o;
    boolean currencyCodeEquals = (this.currencyCode == null && other.currencyCode == null)
      || (this.currencyCode != null && this.currencyCode.equals(other.currencyCode));
    return this.amount == other.amount && currencyCodeEquals;
}

Overriding HashCode

@Override
public final int hashCode() {
    int result = 17;
    if (city != null) {
        result = 31 * result + city.hashCode();
    }
    if (department != null) {
        result = 31 * result + department.hashCode();
    }
    return result;
}

What is hashCode() method in Java?

The hashCode() method returns a hash code value (an integer number). The hashCode() method returns the same integer number if two keys (by calling equals() method) are identical.

However, it is possible that two hash code numbers can have different or the same keys.

If two objects do not produce an equal result by using the equals() method, then the hashcode() method will provide the different integer result for both the objects.

teststep banner