Skip to content

Instantly share code, notes, and snippets.

@BlakeStevenson
Created October 6, 2025 23:32
Show Gist options
  • Select an option

  • Save BlakeStevenson/9e3056a421781e0c0d1d6d6a90b87e36 to your computer and use it in GitHub Desktop.

Select an option

Save BlakeStevenson/9e3056a421781e0c0d1d6d6a90b87e36 to your computer and use it in GitHub Desktop.
import java.util.Scanner;
import java.math.BigInteger;
public class AssignmentSolutions {
private static final Scanner SC = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Java Assignment #2: Q1–Q10");
while (true) {
System.out.println();
System.out.println("Choose a task:");
System.out.println(" 1) Q1 - Check Pass or Fail");
System.out.println(" 2) Q2 - Electricity Bill Calculator");
System.out.println(" 3) Q3 - Print Multiplication Table (1 to 10)");
System.out.println(" 4) Q4 - Sum of Digits of a Number");
System.out.println(" 5) Q5 - Check Prime Number (using method)");
System.out.println(" 6) Q6 - Factorial (using method)");
System.out.println(" 7) Q7 - Armstrong Number Check");
System.out.println(" 8) Q8 - Reverse a Number (no strings)");
System.out.println(" 9) Q9 - Bank Interest Calculation (using method)");
System.out.println("10) Q10 - Library Management System (methods + loops)");
System.out.println(" 0) Exit");
int choice = readIntInRange("Enter choice (0–10): ", 0, 10);
switch (choice) {
case 0: System.out.println("Goodbye!"); return;
case 1: q1PassFail(); break;
case 2: q2ElectricityBill(); break;
case 3: q3MultiplicationTable(); break;
case 4: q4SumOfDigits(); break;
case 5: q5CheckPrime(); break;
case 6: q6Factorial(); break;
case 7: q7Armstrong(); break;
case 8: q8ReverseNumber(); break;
case 9: q9BankInterest(); break;
case 10: q10LibraryBorrow(); break;
default: System.out.println("Unknown option. Try again.");
}
}
}
/* -------------------------------------------------------------------------
* Utility: robust integer input with range checking.
* Prompts until the user enters a valid integer within [min, max].
* ------------------------------------------------------------------------- */
private static int readIntInRange(String prompt, int min, int max) {
while (true) {
System.out.print(prompt);
try {
String line = SC.nextLine().trim();
int val = Integer.parseInt(line);
if (val < min || val > max) {
System.out.printf("Please enter an integer in [%d, %d].%n", min, max);
continue;
}
return val;
} catch (NumberFormatException ex) {
System.out.println("Invalid integer. Please try again.");
}
}
}
/* -------------------------------------------------------------------------
* Utility: robust integer input with validation rule (e.g., non-negative).
* validatorName is used in error messages for clarity.
* ------------------------------------------------------------------------- */
private static int readIntWithRule(String prompt, String validatorName) {
while (true) {
System.out.print(prompt);
try {
String line = SC.nextLine().trim();
int val = Integer.parseInt(line);
// Basic guardrails; specific questions may add more checks inline
if ("nonNegative".equals(validatorName) && val < 0) {
System.out.println("Please enter a non-negative integer.");
continue;
}
if ("positive".equals(validatorName) && val <= 0) {
System.out.println("Please enter a positive integer (> 0).");
continue;
}
return val;
} catch (NumberFormatException ex) {
System.out.println("Invalid integer. Please try again.");
}
}
}
/* -------------------------------------------------------------------------
* Utility: robust double input with a simple rule key.
* ------------------------------------------------------------------------- */
private static double readDoubleWithRule(String prompt, String rule) {
while (true) {
System.out.print(prompt);
try {
String line = SC.nextLine().trim();
double val = Double.parseDouble(line);
if ("nonNegative".equals(rule) && val < 0) {
System.out.println("Please enter a non-negative number.");
continue;
}
if ("positive".equals(rule) && val <= 0) {
System.out.println("Please enter a positive number (> 0).");
continue;
}
return val;
} catch (NumberFormatException ex) {
System.out.println("Invalid number. Please try again.");
}
}
}
/* =========================================================================
* Q1: Check Pass or Fail
* Algorithm (High-Level):
* 1) Read an integer mark (0–100 recommended; we validate non-negative).
* 2) If mark >= 50 -> "Pass", else -> "Fail".
* Error Handling:
* - Reprompt on invalid integers or negatives.
* ========================================================================= */
private static void q1PassFail() {
System.out.println("\n[Q1] Check Pass or Fail");
int marks = readIntWithRule("Enter marks (0–100): ", "nonNegative");
if (marks >= 50) System.out.println("Pass");
else System.out.println("Fail");
}
/* =========================================================================
* Q2: Electricity Bill Calculator
* Billing Rules:
* - $5/unit for first 100 units
* - $7/unit for units 101–300
* - $10/unit for units > 300
* Algorithm:
* 1) Read non-negative integer units.
* 2) Use if-else to compute tiered total.
* 3) Print final amount.
* ========================================================================= */
private static void q2ElectricityBill() {
System.out.println("\n[Q2] Electricity Bill Calculator");
int units = readIntWithRule("Enter units consumed (>= 0): ", "nonNegative");
long total = 0;
if (units <= 100) {
total = units * 5L;
} else if (units <= 300) {
total = 100 * 5L + (units - 100) * 7L;
} else {
total = 100 * 5L + 200 * 7L + (units - 300) * 10L;
}
System.out.println("Total bill: $" + total);
}
/* =========================================================================
* Q3: Multiplication Table (1..10)
* Algorithm:
* 1) Read an integer n.
* 2) for i = 1..10, print "n x i = (n*i)".
* Error Handling: robust integer read.
* ========================================================================= */
private static void q3MultiplicationTable() {
System.out.println("\n[Q3] Multiplication Table (1..10)");
int n = readIntWithRule("Enter an integer for the table: ", "none");
for (int i = 1; i <= 10; i++) {
System.out.printf("%d x %d = %d%n", n, i, n * i);
}
}
/* =========================================================================
* Q4: Sum of Digits
* Algorithm:
* 1) Read a positive integer.
* 2) While n > 0: sum += n % 10; n /= 10.
* 3) Print sum.
* Error Handling: require positive integer.
* ========================================================================= */
private static void q4SumOfDigits() {
System.out.println("\n[Q4] Sum of Digits of a Number");
int n = readIntWithRule("Enter a positive integer: ", "positive");
int sum = 0, copy = n;
while (copy > 0) {
sum += (copy % 10);
copy /= 10;
}
System.out.println("Sum of digits: " + sum);
}
/* =========================================================================
* Q5: Check Prime Number (Using Methods)
* Algorithm:
* 1) Read integer n (>= 2 recommended).
* 2) isPrime(n): return false for n<2; check divisors up to sqrt(n).
* 3) Print "Prime Number" or "Not a Prime Number".
* ========================================================================= */
private static void q5CheckPrime() {
System.out.println("\n[Q5] Prime Number Check");
int n = readIntWithRule("Enter an integer (>= 2 recommended): ", "none");
if (isPrime(n)) System.out.println("Prime Number");
else System.out.println("Not a Prime Number");
}
/** Returns true if num is prime, else false. */
private static boolean isPrime(int num) {
if (num < 2) return false;
if (num % 2 == 0) return num == 2;
int limit = (int)Math.sqrt(num);
for (int d = 3; d <= limit; d += 2) {
if (num % d == 0) return false;
}
return true;
}
/* =========================================================================
* Q6: Factorial Using a Method
* Algorithm:
* 1) Read integer N (>= 0).
* 2) factorial(N): multiply 1..N iteratively using BigInteger to avoid overflow.
* 3) Print result.
* ========================================================================= */
private static void q6Factorial() {
System.out.println("\n[Q6] Factorial (N!)");
int n = readIntWithRule("Enter a non-negative integer N: ", "nonNegative");
BigInteger f = factorial(n);
System.out.println(n + "! = " + f.toString());
}
/** Computes n! with BigInteger to avoid overflow. */
private static BigInteger factorial(int n) {
BigInteger result = BigInteger.ONE;
for (int i = 2; i <= n; i++) {
result = result.multiply(BigInteger.valueOf(i));
}
return result;
}
/* =========================================================================
* Q7: Armstrong Number Check
* Definition: An n-digit number equals the sum of each digit raised to the power n.
* Algorithm:
* 1) Read non-negative integer x.
* 2) Count digits (n). Handle x=0 => n=1 by definition.
* 3) Sum (digit^n) for each digit using integer power.
* 4) Compare sum to original.
* ========================================================================= */
private static void q7Armstrong() {
System.out.println("\n[Q7] Armstrong Number Check");
int x = readIntWithRule("Enter a non-negative integer: ", "nonNegative");
int nDigits = (x == 0) ? 1 : (int)Math.floor(Math.log10(x)) + 1;
// Compute sum of each digit^nDigits without using floating point pow
int sum = 0, copy = x;
while (copy > 0) {
int d = copy % 10;
sum += intPow(d, nDigits);
copy /= 10;
}
if (x == 0) sum = 0; // 0 is Armstrong (0^1 = 0)
if (sum == x) System.out.println("Armstrong Number");
else System.out.println("Not an Armstrong Number");
}
/** Fast integer power (base^exp) with simple loop, safe for small digits/exp. */
private static int intPow(int base, int exp) {
int result = 1;
for (int i = 0; i < exp; i++) result *= base;
return result;
}
/* =========================================================================
* Q8: Reverse a Number Without Using Strings
* Algorithm:
* 1) Read integer N (can be negative; we’ll preserve sign).
* 2) Work with absolute value: rev = rev*10 + (n%10); n/=10
* 3) Reapply sign and print reversed.
* Edge Cases:
* - Leading zeros vanish (e.g., 120 -> 21). This is expected behavior.
* ========================================================================= */
private static void q8ReverseNumber() {
System.out.println("\n[Q8] Reverse a Number (no strings)");
int n = readIntWithRule("Enter an integer (can be negative): ", "none");
boolean neg = n < 0;
int copy = Math.abs(n);
long rev = 0; // use long to detect overflow
while (copy > 0) {
rev = rev * 10 + (copy % 10);
copy /= 10;
}
if (neg) rev = -rev;
// Validate within int bounds:
if (rev < Integer.MIN_VALUE || rev > Integer.MAX_VALUE) {
System.out.println("Reversed value exceeds 32-bit integer range.");
} else {
System.out.println("Reversed: " + (int)rev);
}
}
/* =========================================================================
* Q9: Bank Interest Calculation (Using Methods)
* Rates:
* - amount < 10000 -> 3%
* - 10000..50000 -> 5%
* - > 50000 -> 7%
* Algorithm:
* 1) Read deposit amount (>= 0).
* 2) interest = calculateInterest(amount).
* 3) final = amount + interest; print both.
* ========================================================================= */
private static void q9BankInterest() {
System.out.println("\n[Q9] Bank Interest Calculation");
double amount = readDoubleWithRule("Enter deposit amount (>= 0): ", "nonNegative");
double interest = calculateInterest(amount);
double finalAmount = amount + interest;
System.out.printf("Interest earned: $%.2f%n", interest);
System.out.printf("Final amount : $%.2f%n", finalAmount);
}
/** Returns interest based on tiered rates. */
private static double calculateInterest(double amount) {
if (amount < 10000.0) return amount * 0.03;
else if (amount <= 50000.0) return amount * 0.05;
else return amount * 0.07;
}
/* =========================================================================
* Q10: Library Management System (Using Methods & Loops)
* Requirement:
* - User can borrow up to 3 books.
* - Use while loop to allow attempts until "exit".
* - borrowBook(booksBorrowed): if <3 allow, else deny.
*
* Algorithm:
* 1) Initialize booksBorrowed = 0.
* 2) Loop: prompt user either to "borrow" or "exit".
* 3) If "borrow": call borrowBook(booksBorrowed).
* - If allowed: increment booksBorrowed and confirm.
* - Else: print limit reached.
* 4) If "exit": break loop.
* 5) Print summary.
* Error Handling:
* - Any input other than "borrow" or "exit" shows a friendly hint and reprompts.
* ========================================================================= */
private static void q10LibraryBorrow() {
System.out.println("\n[Q10] Library Management System (max 3 books)");
int booksBorrowed = 0;
while (true) {
System.out.print("Type 'borrow' to borrow a book or 'exit' to stop: ");
String cmd = SC.nextLine().trim().toLowerCase();
if ("exit".equals(cmd)) {
System.out.println("Exiting borrowing process.");
break;
} else if ("borrow".equals(cmd)) {
if (borrowBook(booksBorrowed)) {
booksBorrowed++;
System.out.printf("Borrowed successfully. Total borrowed: %d/3%n", booksBorrowed);
} else {
System.out.println("Borrow denied: You have reached the 3-book limit.");
}
} else {
System.out.println("Unrecognized command. Please type 'borrow' or 'exit'.");
}
}
System.out.println("You borrowed " + booksBorrowed + " book(s) this session.");
}
/** Returns true if user can borrow (<3), false if limit reached. */
private static boolean borrowBook(int booksBorrowed) {
return booksBorrowed < 3;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment