﻿ Java exercises and solutions: if else and logical operators

# Java exercises and solutions: if else and logical operators

## if else and logical operators

### Exercise 1: Write a Java program that determines a student’s grade.

The program will read three types of scores(quiz, mid-term, and final scores) and determine the grade based on the following rules:
-if the average score >=90% =>grade=A
-if the average score >= 70% and <90% => grade=B
-if the average score>=50% and <70% =>grade=C

See the example output below:

Quiz score: 80

Mid-term score: 68

Final score: 90

Solution:

import java.util.*;
public class JavaExercises
{
public static void main(String[] args)
{
}

float quiz_score, mid_score,final_score,avg;
Scanner sc=new Scanner(System.in);
System.out.print("Quiz score:");
quiz_score=sc.nextFloat();
System.out.print("Mid-term score:");
mid_score=sc.nextFloat();
System.out.print("Final score:");
final_score=sc.nextFloat();
avg=(quiz_score+mid_score+final_score)/3;

else System.out.println("Invalid");

}

}

### Exercise 2: Write a Java program to calculate the revenue from a sale based on the unit price and quantity of a product input by the user.

The discount rate is 10% for the quantity purchased between 100 and 120 units, and 15% for the quantity purchased greater than 120 units. If the quantity purchased is less than 100 units, the discount rate is 0%. See the example output as shown below:

Enter unit price: 25

Enter quantity: 110

The revenue from sale: 2475.0\$

After discount: 275.0\$(10.0%)

Solution:

import java.util.*;
public class JavaExercises
{
public static void main(String[] args)
{
calculateSale();
}

static void calculateSale(){

float unitprice=0f;
int quantity=0;
float revenue=0f;
float discount_rate=0f, discount_amount=0f;

Scanner sc=new Scanner(System.in);
System.out.print("Enter unit price:");
unitprice=sc.nextFloat();
System.out.print("Enter quantity:");
quantity=sc.nextInt();

if(quantity<100)
revenue=unitprice*quantity;
else if(quantity>=100 && quantity<=120)
{
discount_rate=(float)10/100;
revenue=unitprice*quantity;
discount_amount=revenue*discount_rate;
revenue-=discount_amount;
}

else if(quantity>120)
{
discount_rate=(float)15/100;
revenue=unitprice*quantity;
discount_amount=revenue*discount_rate;
revenue-=discount_amount;
}

System.out.println("The revenue from sale:"+revenue+"\$");
System.out.println("After discount:"+discount_amount+"\$("+discount_rate*100+"%)");

}

}