1. Introduction to Else-If Ladder
What is Else-If Ladder?
An else-if ladder is a control structure that allows you to check multiple conditions in sequence. It executes the code block corresponding to the first true condition and skips the rest.
Why Use Else-If Ladder?
- Multiple condition checking in order
- Efficient decision making
- Cleaner code compared to nested if-else
- Sequential evaluation of conditions
Syntax:
if (condition1) {
// Code block 1
} else if (condition2) {
// Code block 2
} else if (condition3) {
// Code block 3
} else {
// Default code block
}
2. Complete Code Examples
Example 1: Basic Else-If Ladder
import java.util.Scanner;
public class BasicElseIfLadder {
public static void main(String[] args) {
System.out.println("=== Basic Else-If Ladder Examples ===");
// Example 1: Number classification
demonstrateNumberClassification();
// Example 2: Day of week
demonstrateDayOfWeek();
// Example 3: Temperature analysis
demonstrateTemperatureAnalysis();
// Example 4: User role permissions
demonstrateUserRoles();
}
public static void demonstrateNumberClassification() {
System.out.println("\n1. Number Classification:");
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
// Else-if ladder for number classification
if (number > 0) {
System.out.println(number + " is a POSITIVE number");
} else if (number < 0) {
System.out.println(number + " is a NEGATIVE number");
} else {
System.out.println("The number is ZERO");
}
// Additional classification
if (number % 2 == 0) {
System.out.println(number + " is EVEN");
} else {
System.out.println(number + " is ODD");
}
}
public static void demonstrateDayOfWeek() {
System.out.println("\n2. Day of Week:");
Scanner scanner = new Scanner(System.in);
System.out.print("Enter day number (1-7): ");
int dayNumber = scanner.nextInt();
// Else-if ladder for day of week
if (dayNumber == 1) {
System.out.println("Day " + dayNumber + ": Monday");
} else if (dayNumber == 2) {
System.out.println("Day " + dayNumber + ": Tuesday");
} else if (dayNumber == 3) {
System.out.println("Day " + dayNumber + ": Wednesday");
} else if (dayNumber == 4) {
System.out.println("Day " + dayNumber + ": Thursday");
} else if (dayNumber == 5) {
System.out.println("Day " + dayNumber + ": Friday");
} else if (dayNumber == 6) {
System.out.println("Day " + dayNumber + ": Saturday");
} else if (dayNumber == 7) {
System.out.println("Day " + dayNumber + ": Sunday");
} else {
System.out.println("Invalid day number! Please enter 1-7.");
}
// Day type classification
if (dayNumber >= 1 && dayNumber <= 5) {
System.out.println("It's a WEEKDAY");
} else if (dayNumber == 6 || dayNumber == 7) {
System.out.println("It's a WEEKEND");
}
}
public static void demonstrateTemperatureAnalysis() {
System.out.println("\n3. Temperature Analysis:");
Scanner scanner = new Scanner(System.in);
System.out.print("Enter temperature in Β°C: ");
double temperature = scanner.nextDouble();
// Else-if ladder for temperature analysis
if (temperature < 0) {
System.out.println("βοΈ Freezing cold! Wear heavy winter clothes.");
} else if (temperature >= 0 && temperature < 10) {
System.out.println("π₯Ά Very cold! Wear warm clothes.");
} else if (temperature >= 10 && temperature < 20) {
System.out.println("π Cool weather! A light jacket would be good.");
} else if (temperature >= 20 && temperature < 30) {
System.out.println("π Pleasant weather! Perfect for outdoor activities.");
} else if (temperature >= 30 && temperature < 40) {
System.out.println("π₯΅ Hot! Stay hydrated and wear light clothes.");
} else {
System.out.println("π₯ Extremely hot! Avoid going outside if possible.");
}
// Additional weather suggestions
if (temperature > 35) {
System.out.println("π‘ Suggestion: Use sunscreen and drink plenty of water");
} else if (temperature < 5) {
System.out.println("π‘ Suggestion: Wear multiple layers and protect exposed skin");
}
}
public static void demonstrateUserRoles() {
System.out.println("\n4. User Role Permissions:");
Scanner scanner = new Scanner(System.in);
System.out.print("Enter user role (admin/editor/user/guest): ");
String role = scanner.nextLine().toLowerCase();
// Else-if ladder for role-based permissions
if (role.equals("admin")) {
System.out.println("π ADMIN Permissions:");
System.out.println(" - Full system access");
System.out.println(" - User management");
System.out.println(" - Database administration");
System.out.println(" - System configuration");
} else if (role.equals("editor")) {
System.out.println("βοΈ EDITOR Permissions:");
System.out.println(" - Content creation and editing");
System.out.println(" - Moderate user content");
System.out.println(" - Publish articles");
} else if (role.equals("user")) {
System.out.println("π€ USER Permissions:");
System.out.println(" - View content");
System.out.println(" - Comment on articles");
System.out.println(" - Personal profile management");
} else if (role.equals("guest")) {
System.out.println("π GUEST Permissions:");
System.out.println(" - Browse public content");
System.out.println(" - Limited access");
} else {
System.out.println("β Unknown role! Available roles: admin, editor, user, guest");
}
// Access level summary
if (role.equals("admin") || role.equals("editor")) {
System.out.println("π High-level access granted");
} else if (role.equals("user")) {
System.out.println("π Standard access granted");
} else {
System.out.println("π« Restricted access");
}
}
}
Example 2: Student Grading System
import java.util.*;
public class StudentGradingSystem {
public static void main(String[] args) {
System.out.println("=== Student Grading System with Else-If Ladder ===");
Scanner scanner = new Scanner(System.in);
// Get student information
System.out.print("Enter student name: ");
String name = scanner.nextLine();
System.out.print("Enter marks obtained (0-100): ");
int marks = scanner.nextInt();
System.out.print("Enter attendance percentage (0-100): ");
int attendance = scanner.nextInt();
// Grade calculation using else-if ladder
String grade;
String performance;
// Marks-based grading
if (marks >= 90) {
grade = "A+";
performance = "Outstanding";
} else if (marks >= 80) {
grade = "A";
performance = "Excellent";
} else if (marks >= 70) {
grade = "B+";
performance = "Very Good";
} else if (marks >= 60) {
grade = "B";
performance = "Good";
} else if (marks >= 50) {
grade = "C";
performance = "Average";
} else if (marks >= 40) {
grade = "D";
performance = "Below Average";
} else {
grade = "F";
performance = "Fail";
}
// Attendance status
String attendanceStatus;
if (attendance >= 90) {
attendanceStatus = "Excellent";
} else if (attendance >= 80) {
attendanceStatus = "Good";
} else if (attendance >= 70) {
attendanceStatus = "Satisfactory";
} else if (attendance >= 60) {
attendanceStatus = "Needs Improvement";
} else {
attendanceStatus = "Poor";
}
// Overall result
String overallResult;
if (marks >= 40 && attendance >= 75) {
overallResult = "PASS";
} else if (marks >= 40 && attendance < 75) {
overallResult = "PASS (Attendance Warning)";
} else {
overallResult = "FAIL";
}
// Display report
System.out.println("\n" + "=".repeat(50));
System.out.println("STUDENT REPORT CARD");
System.out.println("=".repeat(50));
System.out.println("Name: " + name);
System.out.println("Marks: " + marks + "/100");
System.out.println("Attendance: " + attendance + "%");
System.out.println("Grade: " + grade);
System.out.println("Performance: " + performance);
System.out.println("Attendance Status: " + attendanceStatus);
System.out.println("Overall Result: " + overallResult);
System.out.println("=".repeat(50));
// Additional remarks based on performance
System.out.println("\nREMARKS:");
if (marks >= 90 && attendance >= 90) {
System.out.println("π Exceptional performance! Keep up the excellent work!");
} else if (marks >= 80) {
System.out.println("β
Very good performance. Continue your hard work!");
} else if (marks >= 60) {
System.out.println("π Good effort. There's room for improvement.");
} else if (marks >= 40) {
System.out.println("β οΈ You passed, but need to work harder.");
if (attendance < 75) {
System.out.println("π
Improve your attendance for better results.");
}
} else {
System.out.println("β You need to focus more on studies.");
System.out.println("π‘ Consider seeking help from teachers.");
}
// Subject-wise grading (simulated)
System.out.println("\nSUBJECT-WISE PERFORMANCE:");
String[] subjects = {"Mathematics", "Science", "English", "History", "Computer Science"};
Random random = new Random();
for (String subject : subjects) {
int subjectMarks = random.nextInt(101); // Random marks 0-100
String subjectGrade = calculateSubjectGrade(subjectMarks);
System.out.printf(" %-15s: %3d/100 (%s)%n", subject, subjectMarks, subjectGrade);
}
}
public static String calculateSubjectGrade(int marks) {
// Else-if ladder for subject grade calculation
if (marks >= 95) return "A+";
else if (marks >= 90) return "A";
else if (marks >= 85) return "B+";
else if (marks >= 80) return "B";
else if (marks >= 75) return "C+";
else if (marks >= 70) return "C";
else if (marks >= 60) return "D+";
else if (marks >= 50) return "D";
else if (marks >= 40) return "E";
else return "F";
}
}
Example 3: E-Commerce Discount System
import java.util.*;
public class ECommerceDiscountSystem {
public static void main(String[] args) {
System.out.println("=== E-Commerce Discount System ===");
Scanner scanner = new Scanner(System.in);
Random random = new Random();
// Customer information
System.out.print("Enter customer type (regular/premium/vip): ");
String customerType = scanner.nextLine().toLowerCase();
System.out.print("Enter purchase amount: $");
double purchaseAmount = scanner.nextDouble();
System.out.print("Enter membership duration (in years): ");
int membershipYears = scanner.nextInt();
// Calculate base discount based on customer type
double baseDiscount = calculateBaseDiscount(customerType, purchaseAmount);
// Calculate loyalty discount
double loyaltyDiscount = calculateLoyaltyDiscount(membershipYears);
// Calculate seasonal discount (random for demo)
double seasonalDiscount = random.nextDouble() * 10; // 0-10%
// Calculate total discount
double totalDiscount = baseDiscount + loyaltyDiscount + seasonalDiscount;
double maxAllowedDiscount = 50.0; // Maximum 50% discount
totalDiscount = Math.min(totalDiscount, maxAllowedDiscount);
// Calculate final amount
double discountAmount = (purchaseAmount * totalDiscount) / 100;
double finalAmount = purchaseAmount - discountAmount;
// Display invoice
displayInvoice(customerType, purchaseAmount, baseDiscount,
loyaltyDiscount, seasonalDiscount, totalDiscount,
discountAmount, finalAmount);
// Additional benefits
displayAdditionalBenefits(customerType, purchaseAmount, membershipYears);
}
public static double calculateBaseDiscount(String customerType, double purchaseAmount) {
double discount = 0.0;
// Else-if ladder for base discount calculation
if (customerType.equals("vip")) {
if (purchaseAmount >= 1000) {
discount = 25.0;
} else if (purchaseAmount >= 500) {
discount = 20.0;
} else if (purchaseAmount >= 200) {
discount = 15.0;
} else {
discount = 10.0;
}
} else if (customerType.equals("premium")) {
if (purchaseAmount >= 1000) {
discount = 20.0;
} else if (purchaseAmount >= 500) {
discount = 15.0;
} else if (purchaseAmount >= 200) {
discount = 10.0;
} else {
discount = 5.0;
}
} else if (customerType.equals("regular")) {
if (purchaseAmount >= 1000) {
discount = 15.0;
} else if (purchaseAmount >= 500) {
discount = 10.0;
} else if (purchaseAmount >= 200) {
discount = 5.0;
} else {
discount = 0.0;
}
} else {
System.out.println("Unknown customer type. No discount applied.");
discount = 0.0;
}
return discount;
}
public static double calculateLoyaltyDiscount(int membershipYears) {
double discount = 0.0;
// Else-if ladder for loyalty discount
if (membershipYears >= 10) {
discount = 15.0;
} else if (membershipYears >= 5) {
discount = 10.0;
} else if (membershipYears >= 3) {
discount = 5.0;
} else if (membershipYears >= 1) {
discount = 2.0;
} else {
discount = 0.0;
}
return discount;
}
public static void displayInvoice(String customerType, double purchaseAmount,
double baseDiscount, double loyaltyDiscount,
double seasonalDiscount, double totalDiscount,
double discountAmount, double finalAmount) {
System.out.println("\n" + "=".repeat(60));
System.out.println(" INVOICE");
System.out.println("=".repeat(60));
System.out.printf("Customer Type: %s%n", customerType.toUpperCase());
System.out.printf("Purchase Amount: $%.2f%n", purchaseAmount);
System.out.println("\nDISCOUNT BREAKDOWN:");
System.out.printf(" Base Discount (%s): %.1f%%%n", customerType, baseDiscount);
System.out.printf(" Loyalty Discount: %.1f%%%n", loyaltyDiscount);
System.out.printf(" Seasonal Discount: %.1f%%%n", seasonalDiscount);
System.out.printf(" Total Discount: %.1f%%%n", totalDiscount);
System.out.printf(" Discount Amount: $%.2f%n", discountAmount);
System.out.println("-".repeat(40));
System.out.printf("FINAL AMOUNT: $%.2f%n", finalAmount);
System.out.println("=".repeat(60));
}
public static void displayAdditionalBenefits(String customerType,
double purchaseAmount,
int membershipYears) {
System.out.println("\nADDITIONAL BENEFITS:");
// Else-if ladder for additional benefits
if (customerType.equals("vip")) {
System.out.println("π VIP Benefits:");
if (purchaseAmount >= 500) {
System.out.println(" - Free express shipping");
System.out.println(" - Priority customer support");
}
if (membershipYears >= 3) {
System.out.println(" - Exclusive VIP events access");
System.out.println(" - Personal shopping assistant");
}
System.out.println(" - Early access to sales");
System.out.println(" - Extended return policy");
} else if (customerType.equals("premium")) {
System.out.println("β Premium Benefits:");
if (purchaseAmount >= 300) {
System.out.println(" - Free standard shipping");
}
if (membershipYears >= 2) {
System.out.println(" - Birthday discount coupon");
}
System.out.println(" - Special promotional offers");
} else if (customerType.equals("regular")) {
System.out.println("π Regular Customer Benefits:");
if (purchaseAmount >= 200) {
System.out.println(" - Discount on next purchase");
}
if (membershipYears >= 1) {
System.out.println(" - Loyalty points earned");
}
}
// Purchase-based benefits
if (purchaseAmount >= 1000) {
System.out.println("\nπ° Big Spender Bonus:");
System.out.println(" - Additional 5% cashback");
System.out.println(" - Free gift wrapping");
} else if (purchaseAmount >= 500) {
System.out.println("\nπ― Value Shopper Perk:");
System.out.println(" - Free product sample");
}
// Membership milestone benefits
if (membershipYears >= 10) {
System.out.println("\nπ Decade Club Member!");
System.out.println(" - Special anniversary gift");
System.out.println(" - Lifetime 5% additional discount");
} else if (membershipYears >= 5) {
System.out.println("\nπ 5-Year Milestone!");
System.out.println(" - Exclusive member badge");
}
}
}
Example 4: Tax Calculation System
import java.util.*;
public class TaxCalculationSystem {
public static void main(String[] args) {
System.out.println("=== Income Tax Calculation System ===");
Scanner scanner = new Scanner(System.in);
// Get taxpayer information
System.out.print("Enter annual income: $");
double annualIncome = scanner.nextDouble();
System.out.print("Enter age: ");
int age = scanner.nextInt();
System.out.print("Are you disabled? (yes/no): ");
scanner.nextLine(); // Consume newline
String disabled = scanner.nextLine().toLowerCase();
System.out.print("Filing status (single/married/joint): ");
String filingStatus = scanner.nextLine().toLowerCase();
// Calculate tax using else-if ladder
double taxAmount = calculateIncomeTax(annualIncome, age, disabled, filingStatus);
double effectiveTaxRate = (taxAmount / annualIncome) * 100;
// Display tax calculation
displayTaxCalculation(annualIncome, taxAmount, effectiveTaxRate,
age, disabled, filingStatus);
// Tax planning suggestions
provideTaxSuggestions(annualIncome, taxAmount, effectiveTaxRate, age);
}
public static double calculateIncomeTax(double income, int age,
String disabled, String filingStatus) {
double tax = 0.0;
// Tax exemptions and deductions
double standardDeduction = calculateStandardDeduction(filingStatus, age);
double taxableIncome = Math.max(0, income - standardDeduction);
// Additional deduction for disabled persons
if (disabled.equals("yes")) {
taxableIncome = Math.max(0, taxableIncome - 75000);
}
// Senior citizen benefit
if (age >= 60) {
taxableIncome = Math.max(0, taxableIncome - 50000);
} else if (age >= 80) {
taxableIncome = Math.max(0, taxableIncome - 100000);
}
// Tax calculation using progressive tax slabs (else-if ladder)
if (taxableIncome <= 250000) {
tax = 0.0; // No tax
} else if (taxableIncome <= 500000) {
tax = (taxableIncome - 250000) * 0.05;
} else if (taxableIncome <= 750000) {
tax = 12500 + (taxableIncome - 500000) * 0.10; // 5% on first 2.5L + 10% on next
} else if (taxableIncome <= 1000000) {
tax = 37500 + (taxableIncome - 750000) * 0.15; // 12.5K + 25K + 15% on next
} else if (taxableIncome <= 1250000) {
tax = 75000 + (taxableIncome - 1000000) * 0.20;
} else if (taxableIncome <= 1500000) {
tax = 125000 + (taxableIncome - 1250000) * 0.25;
} else {
tax = 187500 + (taxableIncome - 1500000) * 0.30;
}
// Health and education cess (4%)
tax = tax * 1.04;
return Math.max(0, tax);
}
public static double calculateStandardDeduction(String filingStatus, int age) {
double deduction = 0.0;
// Else-if ladder for standard deduction
if (filingStatus.equals("single")) {
deduction = 50000;
} else if (filingStatus.equals("married")) {
deduction = 75000;
} else if (filingStatus.equals("joint")) {
deduction = 100000;
} else {
deduction = 50000; // Default for unknown status
}
// Additional deduction for senior citizens
if (age >= 60) {
deduction += 25000;
} else if (age >= 80) {
deduction += 50000;
}
return deduction;
}
public static void displayTaxCalculation(double income, double tax,
double effectiveRate, int age,
String disabled, String filingStatus) {
System.out.println("\n" + "=".repeat(60));
System.out.println(" TAX CALCULATION SUMMARY");
System.out.println("=".repeat(60));
System.out.printf("Annual Income: $%,.2f%n", income);
System.out.printf("Age: %d years%n", age);
System.out.printf("Filing Status: %s%n", filingStatus.toUpperCase());
System.out.printf("Disabled: %s%n", disabled.equals("yes") ? "Yes" : "No");
System.out.println("-".repeat(40));
System.out.printf("Tax Amount: $%,.2f%n", tax);
System.out.printf("Effective Tax Rate: %.2f%%%n", effectiveRate);
System.out.printf("Net Income After Tax: $%,.2f%n", income - tax);
System.out.println("=".repeat(60));
// Tax bracket information
System.out.println("\nTAX BRACKET ANALYSIS:");
String taxBracket = getTaxBracket(effectiveRate);
System.out.println("You fall in the: " + taxBracket + " bracket");
}
public static String getTaxBracket(double effectiveRate) {
// Else-if ladder for tax bracket classification
if (effectiveRate == 0.0) {
return "π° Tax-Exempt";
} else if (effectiveRate <= 5.0) {
return "π’ Low Tax";
} else if (effectiveRate <= 10.0) {
return "π‘ Moderate Tax";
} else if (effectiveRate <= 20.0) {
return "π Medium Tax";
} else if (effectiveRate <= 30.0) {
return "π΄ High Tax";
} else {
return "β« Very High Tax";
}
}
public static void provideTaxSuggestions(double income, double tax,
double effectiveRate, int age) {
System.out.println("\nTAX PLANNING SUGGESTIONS:");
// Income-based suggestions
if (income <= 300000) {
System.out.println("π‘ Consider contributing to tax-saving investments");
System.out.println("π‘ Explore government subsidy programs");
} else if (income <= 700000) {
System.out.println("π‘ Maximize Section 80C deductions (up to $1,500)");
System.out.println("π‘ Consider health insurance premium deductions");
} else if (income <= 1200000) {
System.out.println("π‘ Optimize investments in ELSS, PPF, NPS");
System.out.println("π‘ Consider home loan for additional deductions");
} else {
System.out.println("π‘ Consult with tax advisor for complex planning");
System.out.println("π‘ Consider charitable donations for deductions");
}
// Age-based suggestions
if (age < 60) {
System.out.println("π‘ Start retirement planning early");
System.out.println("π‘ Consider long-term investment strategies");
} else if (age >= 60) {
System.out.println("π‘ Utilize senior citizen tax benefits");
System.out.println("π‘ Explore reverse mortgage options");
}
// Tax rate based suggestions
if (effectiveRate > 20.0) {
System.out.println("π‘ High tax burden - consider tax-efficient investments");
System.out.println("π‘ Explore tax-loss harvesting strategies");
} else if (effectiveRate < 5.0) {
System.out.println("π‘ Low tax burden - focus on wealth accumulation");
}
// Additional general suggestions
System.out.println("\nGENERAL TAX TIPS:");
System.out.println("β
Keep all investment and expense documents");
System.out.println("β
File returns before deadline to avoid penalties");
System.out.println("β
Review tax-saving options annually");
System.out.println("β
Consider professional advice for complex situations");
}
}
Example 5: Complex Business Logic with Nested Else-If
```java
import java.util.*;
public class ComplexBusinessLogic {
public static void main(String[] args) {
System.out.println("=== Complex Business Logic with Nested Else-If ===");
Scanner scanner = new Scanner(System.in);
// Loan Application System
demonstrateLoanApplication(scanner);
// Insurance Premium Calculation
demonstrateInsuranceCalculation(scanner);
// Employee Performance Evaluation
demonstrateEmployeeEvaluation(scanner);
}
public static void demonstrateLoanApplication(Scanner scanner) {
System.out.println("\n1. LOAN APPLICATION SYSTEM");
System.out.println("=".repeat(50));
System.out.print("Enter annual income: $");
double income = scanner.nextDouble();
System.out.print("Enter credit score (300-850): ");
int creditScore = scanner.nextInt();
System.out.print("Enter employment years: ");
int employmentYears = scanner.nextInt();
System.out.print("Loan amount requested: $");
double loanAmount = scanner.nextDouble();
System.out.print("Loan purpose (home/car/personal/business): ");
scanner.nextLine(); // Consume newline
String loanPurpose = scanner.nextLine().toLowerCase();
// Loan eligibility check using nested else-if
String eligibility = checkLoanEligibility(income, creditScore, employmentYears,
loanAmount, loanPurpose);
// Display results
System.out.println("\nLOAN APPLICATION RESULTS:");
System.out.println("Eligibility: " + eligibility);
if (!eligibility.equals("REJECTED")) {
double interestRate = calculateInterestRate(creditScore, loanPurpose, employmentYears);
double emi = calculateEMI(loanAmount, interestRate, getLoanTenure(loanPurpose));
System.out.printf("Approved Interest Rate: %.2f%%%n", interestRate);
System.out.printf("Monthly EMI: $%.2f%n", emi);
System.out.printf("Total Payable: $%.2f%n", emi * getLoanTenure(loanPurpose) * 12);
}
}
public static String checkLoanEligibility(double income, int creditScore,
int employmentYears, double loanAmount,
String purpose) {
// Base eligibility checks
if (income <= 0 || creditScore < 300 || creditScore > 850 || employmentYears < 0) {
return "REJECTED - Invalid input data";
}
// Income to loan amount ratio
double incomeToLoanRatio = (loanAmount / income) * 100;
// Main eligibility else-if ladder
if (creditScore >= 750) {
// Excellent credit - most flexible criteria
if (income >= 50000) {
if (incomeToLoanRatio <= 500) { // Loan up to 5x annual income
if (employmentYears >= 2) {
return "APPROVED - Excellent terms";
} else if (employmentYears >= 1) {
return "APPROVED - Good terms";
} else {
return "CONDITIONAL APPROVAL - Probationary employment";
}
} else {
return "REDUCED AMOUNT - Loan amount too high";
}
} else if (income >= 30000) {
if (incomeToLoanRatio <= 300) {
return "APPROVED - Standard terms";
} else {
return "REDUCED AMOUNT - Income insufficient for requested amount";
}
} else {
return "REJECTED - Income too low";
}
} else if (creditScore >= 700) {
// Good credit
if (income >= 60000) {
if (incomeToLoanRatio <= 400 && employmentYears >= 2) {
return "APPROVED - Good terms";
} else if (incomeToLoanRatio <= 300) {
return "APPROVED - Standard terms";
} else {
return "REDUCED AMOUNT - Adjust loan amount";
}
} else if (income >= 40000) {
if (incomeToLoanRatio <= 250 && employmentYears >= 3) {
return "APPROVED - Standard terms";
} else {
return "REJECTED - Income/employment criteria not met";
}
} else {
return "REJECTED - Income too low";
}
} else if (creditScore >= 650) {
// Fair credit - stricter criteria
if (income >= 80000) {
if (incomeToLoanRatio <= 300 && employmentYears >= 3) {
return "APPROVED - Higher interest rate";
} else {
return "REJECTED - Criteria not met for fair credit";
}
} else {
return "REJECTED - Credit score too low for income level";
}
} else if (creditScore >= 600) {
// Poor credit - very strict
if (income >= 100000 && employmentYears >= 5 && incomeToLoanRatio <= 200) {
return "CONDITIONAL APPROVAL - High interest rate";
} else {
return "REJECTED - Credit score insufficient";
}
} else {
return "REJECTED - Credit score below minimum requirement";
}
}
public static double calculateInterestRate(int creditScore, String purpose, int employmentYears) {
double baseRate = 0.0;
// Base rate based on credit score (else-if ladder)
if (creditScore >= 800) {
baseRate = 5.0;
} else if (creditScore >= 750) {
baseRate = 6.0;
} else if (creditScore >= 700) {
baseRate = 7.5;
} else if (creditScore >= 650) {
baseRate = 9.0;
} else if (creditScore >= 600) {
baseRate = 12.0;
} else {
baseRate = 15.0;
}
// Purpose-based adjustment
if (purpose.equals("home")) {
baseRate -= 0.5; // Lower rate for home loans
} else if (purpose.equals("car")) {
baseRate += 0.0; // No change
} else if (purpose.equals("business")) {
baseRate += 1.0; // Higher for business
} else {
baseRate += 0.5; // Personal loans slightly higher
}
// Employment stability adjustment
if (employmentYears >= 5) {
baseRate -= 0.5;
} else if (employmentYears < 2) {
baseRate += 1.0;
}
return Math.max(3.0, baseRate); // Minimum 3% rate
}
public static double calculateEMI(double principal, double rate, int years) {
double monthlyRate = rate / 12 / 100;
int months = years * 12;
return (principal * monthlyRate * Math.pow(1 + monthlyRate, months)) /
(Math.pow(1 + monthlyRate, months) - 1);
}
public static int getLoanTenure(String purpose) {
// Else-if ladder for loan tenure
if (purpose.equals("home")) return 20;
else if (purpose.equals("car")) return 7;
else if (purpose.equals("business")) return 10;
else return 5; // personal loan
}
public static void demonstrateInsuranceCalculation(Scanner scanner) {
System.out.println("\n2. INSURANCE PREMIUM CALCULATION");
System.out.println("=".repeat(50));
System.out.print("Enter age: ");
int age = scanner.nextInt();
System.out.print("Enter health status (excellent/good/fair/poor): ");
scanner.nextLine();
String healthStatus = scanner.nextLine().toLowerCase();
System.out.print("Smoker? (yes/no): ");
String smoker = scanner.nextLine().toLowerCase();
System.out.print("Coverage amount: $");
double coverage = scanner.nextDouble();
System.out.print("Policy type (term/whole/universal): ");
scanner.nextLine();
String policyType = scanner.nextLine().toLowerCase();
// Calculate premium
double premium = calculateInsurancePremium(age, healthStatus, smoker, coverage, policyType);
System.out.printf("\nANNUAL PREMIUM: $%.2f%n", premium);
System.out.printf("MONTHLY PREMIUM: $%.2f%n", premium / 12);
}
public static double calculateInsurancePremium(int age, String health,
String smoker, double coverage,
String policyType) {
double baseRate = 0.0;
// Age-based base rate (else-if ladder)
if (age <= 25) {
baseRate = 0.001; // 0.1% of coverage
} else if (age <= 35) {
baseRate = 0.0015;
} else if (age <= 45) {
baseRate = 0.002;
} else if (age <= 55) {
baseRate = 0.003;
} else if (age <= 65) {
baseRate = 0.005;
} else {
baseRate = 0.008;
}
// Health status multiplier
double healthMultiplier = 1.0;
if (health.equals("excellent")) {
healthMultiplier = 0.8;
} else if (health.equals("good")) {
healthMultiplier = 1