This application demonstrates Scanner input handling and the Math library. The goal is to calculate the future value of an investment based on the compound interest formula.
/*2023-9-12
Assignment 1 - 21 Compound Interest
*/
package MB.assignment1;
import java.util.Scanner;
import java.lang.Math;
public class compoundInterestMB {
public static void main(String[] args){
Scanner myKeyboard = new Scanner(System.in);
//COLLECT INPUT
//P - original principal
System.out.println("enter original principal");
double originalAmt = myKeyboard.nextDouble();
//R - annual interest rate
System.out.println("enter annual interest rate");
double interestRate = myKeyboard.nextDouble();
//N - number of times per year interest is compounded
System.out.println("enter compound interest qty");
double compoundQty = myKeyboard.nextDouble();
//T - time in years the account will earn interest
System.out.println("enter number of years");
double yearDuration = myKeyboard.nextDouble();
/*
Formula
A = P ( 1 + (R/N))^ N*T
*/
double interestEarned = Math.pow(1 + (interestRate/compoundQty),compoundQty*yearDuration);
double finalAmount = originalAmt * interestEarned; // Note: Logic corrected to multiplication
System.out.println("Original amount is: $" + originalAmt);
System.out.println("Interest Rate: " + interestRate + "%");
System.out.println("number of times per year: " + compoundQty);
System.out.println("number of years: " + yearDuration);
System.out.println("Resulting sum: " + finalAmount);
}
}
This exercise focuses on floating-point precision. We calculate a final total based on a fixed tax rate (6.75%) and a standard tip (20%) applied to a subtotal.
/*2023-9-12
Assignment 1-13 Restaurant Bill
compute tax and tip amount based on a given subtotal.
Tax % is 0.0675 Tip is 0.20
*/
package MB.assignment1;
import java.util.Scanner;
public class restaurantbillMB {
public static void main(String[] args){
Scanner myKeyboard = new Scanner(System.in);
System.out.println("Enter amt");//prompt
double subTotal = myKeyboard.nextDouble(); //capture input into var
double taxPct = 0.0675;
double tipPct = 0.20;
double taxTotal = (subTotal * taxPct);
double tipTotal = (subTotal * tipPct);
double finalTotal = (subTotal + tipTotal + taxTotal);
System.out.println("Meal Charge (subtotal): $" + subTotal);
System.out.println("Tax: $" +
String.format("%.2f" , taxTotal));//float precison 2 places
System.out.println("Tip: $" +
String.format("%.2f" , tipTotal));//float precison 2 places
System.out.println("Total Charge: $" +
String.format("%.2f" , finalTotal));//float precison 2 places
}
}
Real-world commerce often requires calculating State and County taxes independently before aggregating them.
/*2023-9-12
Assignment 1-7 Sales Tax
*/
package MB.assignment1;
import java.util.Scanner;
public class salesTaxMB {
public static void main (String[] args){
Scanner myKeyboard = new Scanner(System.in);
double countyTaxRate = 0.04;
double stateTaxRate = 0.02;
double countyTaxRateCharge;
double stateTaxRateCharge;
double subTotal;
double finalTotal;
System.out.println("Enter amt");//prompt
subTotal = myKeyboard.nextDouble(); //capture input into var
//calculate TWO tax charges based on purchase amount
countyTaxRateCharge = (subTotal * countyTaxRate);
stateTaxRateCharge = (subTotal * stateTaxRate);
//final total is the sum of each tax charge to the original amount input by cashier
finalTotal = subTotal + countyTaxRateCharge + stateTaxRateCharge;
System.out.println("Collect: $" +
String.format("%.2f" , finalTotal));//float precison 2 places
}
}
To calculate an average, we must ensure the sum is calculated before the division. In Java, we use parentheses ( ) to force this behavior.
/*2023-9-12
Assignment 1-10 Test Average
*/
package MB.assignment1;
import java.util.Scanner;
public class testAverageMB {
public static void main(String[] args){
Scanner myKeyboard = new Scanner(System.in);
double score1,score2,score3,scoreAverage;
System.out.println("Find average of 3 test scores:");//prompt
System.out.println("Enter Score 1");//prompt
score1 = myKeyboard.nextDouble(); //capture input into var
System.out.println("Enter Score 2");//prompt
score2 = myKeyboard.nextDouble(); //capture input into var
System.out.println("Enter Score 3");//prompt
score3 = myKeyboard.nextDouble(); //capture input into var
scoreAverage = (score1 + score2 + score3) / 3 ;
System.out.println("Scores:" + score1 + ", " + score2 + ", " + score3);
System.out.println("Average:" + scoreAverage);
}
}
Strings in Java are objects, offering built-in methods to transform and analyze text. This lab demonstrates how to handle multi-word input and character isolation.
Counting in Java starts at 0. Using charAt(0) targets the first letter of the string.
/*2023-9-12
Assignment 1-12 String Manipulator
*/
package MB.assignment1;
import java.util.Scanner;
public class stringManipulatorMB {
public static void main(String[] args){
Scanner myKeyboard = new Scanner(System.in);
System.out.println("Enter the name of your favorite city");//prompt
String favCity = myKeyboard.nextLine(); //capture input into (newly declared) var
//number of chars
int favCityCharLen = favCity.length();
//convert to upper
String favCityUpper = favCity.toUpperCase();
//convert to lower
String favCityLower = favCity.toLowerCase();
//get first char
char favCityFirstChar = favCity.charAt(0);
System.out.println("City - " + favCity);
System.out.println("name length: " + favCityCharLen);
System.out.println("all upper: " + favCityUpper);
System.out.println("all lower:" + favCityLower);
System.out.println("first character:" + favCityFirstChar);
}
}
This lab introduces the if statement to categorize numerical data. By evaluating the result of a calculation against specific thresholds, the program can provide a descriptive health status output.
/* 2023-9-28 Lab 2 - Body Mass Index */
package MB.assignment2;
import java.util.Scanner;
public class bodyMassIndexMB {
public static void main(String[] args){
Scanner myKeyboard = new Scanner(System.in);
System.out.println("Enter Weight in Pounds");
int weight = myKeyboard.nextInt();
System.out.println("Enter Height in Inches");
int height = myKeyboard.nextInt();
double BMI = (weight * 703) / (height * height);
System.out.println("Weight:" + weight + " pounds");
System.out.println("Height:" + height + " inches");
System.out.println("BMI: " + BMI);
if(BMI < 18.5){ System.out.println("underweight");}
if(BMI > 25){ System.out.println("overweight");}
else System.out.println("optimal");
}
}
When comparing a single variable against many potential values, a switch statement is often cleaner and more efficient than multiple if-else blocks.
/* 2023-9-28 Lab 2 - Roman Numerals*/
package MB.assignment2;
import java.util.Scanner;
public class romanNumeralsMB {
public static void main(String[] args){
Scanner myKeyboard = new Scanner(System.in);
System.out.println("enter a number 1-10 to find roman numeral");
String userInput = myKeyboard.nextLine();
switch(userInput){
case "1":
System.out.println("I");
break;
case "2":
System.out.println("II.");
break;
case "3":
System.out.println("III");
break;
case "4":
System.out.println("IV");
break;
case "5":
System.out.println("V");
break;
case "6":
System.out.println("VI");
break;
case "7":
System.out.println("VII");
break;
case "8":
System.out.println("VIII");
break;
case "9":
System.out.println("IX");
break;
case "10":
System.out.println("IX");
break;
default:
System.out.println("Invalid choice.");
}
}
}
This milestone combines arithmetic (averaging) with nested logical checks to determine a letter grade based on a 100-point scale.
Using && (AND) allows us to verify if a score falls within a specific range (e.g., between 80 and 89).
/* 2023-9-28 | Lab 2 - Test Scores and Grade */
package MB.assignment2;
import java.util.Scanner;
public class testScoresAndGradeMB {
public static void main(String[] args){
Scanner myKeyboard = new Scanner(System.in);
String letterGrade = "Z"; //init for use in IF statements
System.out.println("Here you will enter 3 test scores");
System.out.println("Enter Score 1");
double score1 = myKeyboard.nextDouble();
System.out.println("Enter Score 2");
double score2 = myKeyboard.nextDouble();
System.out.println("Enter Score 3");
double score3 = myKeyboard.nextDouble();
double scoreAverage = ((score1 + score2 + score3)/3);
if (scoreAverage >= 90 && scoreAverage <= 100 ){
letterGrade="A";
}
else if (scoreAverage >= 80 && scoreAverage <= 89 ){
letterGrade="B";
}
else if (scoreAverage >= 70 && scoreAverage <= 79 ){
letterGrade="C";
}
else if (scoreAverage >= 60 && scoreAverage <= 69 ){
letterGrade="D";
}
else if (scoreAverage <= 68 ){
letterGrade="F";
}
System.out.println("----------------------------------");
System.out.println("Letter grade is " + letterGrade);
System.out.println("Average of your scores: " +
String.format("%.2f" , scoreAverage));//float precison 2 places
System.out.println("----------------------------------");
}
}
Sorting strings alphabetically in Java requires the .compareTo() method rather than simple operators like <.
/* 2023-9-28 | Lab 2 - Sorted Names
INCOMPLETE
*/
package MB.assignment2;
import java.util.Scanner;
public class sortedNamesMB {
public static void main(String[] args){
Scanner myKeyboard = new Scanner(System.in);
String name1, name2, name3;
System.out.println("Enter 3 names");
System.out.println("Enter Name 1");
name1 = myKeyboard.nextLine();
System.out.println("Enter Name 2");
name2 = myKeyboard.nextLine();
System.out.println("Enter Name 3");
name3 = myKeyboard.nextLine();
// test each name to find out which one is less
//need to sort the names in ascending order A-Z
int name1counter=0;
int name2counter=0;
int name3counter=0;
if (name1.compareTo(name2) < 0 ){
name2counter++;
}
else name1counter++;
if (name1.compareTo(name3) < 0 ){
name3counter++;
}
else name1counter++;
if (name2.compareTo(name3) < 0 ){
name3counter++;
}
else name2counter++;
if (name1.compareTo(name3) < 0 ){
name3counter++;
}
else name1counter++;
if (name2.compareTo(name1) < 0 ){
name1counter++;
}
else name2counter++;
System.out.println( name1counter + name1);
System.out.println( name2counter + name2);
System.out.println( name3counter + name3);
}
}
A diagnostic tree is a classic example of nested if statements used to solve user problems step-by-step.
/* 2023-9-28 | Lab 2 - Wi-fi Diagnostic Tree
INCOMPLETE 10-18
*/
package MB.assignment2;
import java.util.Scanner;
public class wifiDiagnosticTreeMB {
public static void main(String[] args){
Scanner myKeyboard = new Scanner(System.in);
System.out.println("Reboot the computer and try to connect:");
System.out.println("Did that fix the problem?");
String userInput = myKeyboard.nextLine();
System.out.println("You answered " + userInput);
if(userInput.equals("n") || userInput.equals("N") ){
System.out.println("Reboot the router and try to connect.");
System.out.println("Did that fix the problem?");
userInput = myKeyboard.nextLine();
System.out.println("You answered " + userInput);
/* ... Code block continues with nested diagnostics ... */
if(userInput.equals("n") || userInput.equals("N") ){
System.out.println("Make sure the cables between the router & model are plugged in firmly.");
System.out.println("Did that fix the problem?");
userInput = myKeyboard.nextLine();
System.out.println("You answered " + userInput);
if(userInput.equals("n") || userInput.equals("N") ){
System.out.println("Move the router to a new location");
System.out.println("Did that fix the problem?");
userInput = myKeyboard.nextLine();
System.out.println("You answered " + userInput);
if(userInput.equals("n") || userInput.equals("N") ){
System.out.println("Get a new router");
}
}
}
}
/*
if(userInput == "y"){N
System.out.println("You answered " + userInput);
System.out.println("Problem solved.");
}
else
System.out.println("You answered " + userInput);
System.out.println("");
}
//answer = myKeyboard.nextLine();
System.out.println("Default: Get a new router");
//System.out.println(answer);
*/
}
}
This program uses a do-while loop to continuously collect integers until the user enters the "sentinel value" of 99. It demonstrates how to track minimum and maximum values dynamically during execution.
/* 2023-10-9 | Assignment 3 - Largest and Smallest*/
package JAVA.assignment3;
import java.util.Scanner;
public class LargestAndSmallest {
public static void main(String[] args){
Scanner myKeyboard = new Scanner(System.in);
int targetInt=99;//end condition
int low=99; /*init as 99 since all numbers must be lower than this.
The variable is intended to immediatley be set to another number,
but we cant init as 0, in case user enters a number lower than 0...*/
int high=0;//
int userInput;
System.out.println("Enter a series of integers... Enter 99 to end.");
do{
userInput = myKeyboard.nextInt();
if (userInput < low){//not <=
low=userInput;
}
if (userInput >high){ //not >=
high=userInput;
}
}
while (userInput != targetInt);
System.out.println("---Results---");
System.out.println("Low: "+ low);
System.out.println("High: " + high);
System.out.println("------------");
} //end main()
}
By combining a for loop with .charAt(), we can inspect every individual character in a string to count specific occurrences.
/* 2023-10-9 | Assignment 3 - Letter Counter*/
package MB.assignment3;
import java.util.Scanner;
public class LetterCounter {
public static void main(String[] args){
Scanner myKeyboard = new Scanner(System.in);
System.out.println("Enter a string to search.");
String fullString = myKeyboard.nextLine();
System.out.println("Enter a character to search for.");
String charString = myKeyboard.nextLine();
char targetChar = charString.charAt(0);
int matchQty=0; //init as 0 to allow increment within loop
for (int loop_iteration=1; loop_iteration < fullString.length(); loop_iteration++){
if (fullString.charAt(loop_iteration) == targetChar){
matchQty ++;
}
}
System.out.println("The character \"" + targetChar + "\" appears "
+ matchQty + " times in your string, " + fullString);
}
}
The "Accumulator" pattern is a staple of programming. Here, the accumulator variable is updated in every loop cycle to store the sum of all integers up to the user-defined ceiling.
/* 2023-10-9 | Assignment 3 - Sum of Numbers*/
package MB.assignment3;
import java.util.Scanner;
public class SumOfNumbers {
public static void main(String[] args){
Scanner myKeyboard = new Scanner(System.in);
System.out.println("Enter a positive nonzero integer (X) and the app will return sum of all integers from 1 to X.");
int userDefinedCeiling = myKeyboard.nextInt(); //user defines how high to count
int accumulator = 0; //to store running total
int increment = 1; // count from 1 to ceiling in increments of X.. use this to increment loop
for (int digit = 1; digit <= userDefinedCeiling; digit=digit+increment){
accumulator += digit; //Which iteration is this? -- That # goes into accumulator.
//accumulator = accumulator + digit
if (digit==userDefinedCeiling){
//check for final line of output, to refine user message
System.out.println("int: " + digit + " Grand Total: " + accumulator);
}
else
System.out.println("int: " + digit + " Total: " + accumulator);
}
}
}
Nested loops (a loop inside a loop) allow for the creation of grids or coordinate systems. The outer loop handles rows while the inner loop handles columns.
/* 2023-10-9 | Assignment 3 - Square Display*/
package MB.assignment3;
import java.util.Scanner;
public class SquareDisplay {
public static void main(String[] args){
Scanner myKeyboard = new Scanner(System.in);
System.out.println("Enter positive int no greater than 15");
int userChar = myKeyboard.nextInt();
for(int x=0; x <= userChar; x++){
System.out.println("x");
for(int y=0; y <= userChar; y++){
System.out.print("y");
}
}
}
}
This milestone moves beyond the console to interact with the file system. It introduces FileWriter and try-catch blocks to safely handle Input/Output (I/O) errors.
In Java, certain actions (like opening a file) are "risky." If the file is missing or locked, the program will crash. try-catch allows us to "catch" the error and handle it gracefully.
/* 2023-10-9 | Assignment 3 - Uppsercase File Converter*/
package MB.assignment3;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class UppercaseFileConverter {
public static void main(String[] args){
//Scanner myKeyboard = new Scanner(System.in);
String readFilename = "readFile.txt";
try{
File sourceFile = new File(readFilename);
Scanner sourceScan = new Scanner(sourceFile);
String writeFile = "test.txt";
while (sourceScan.hasNextLine()) {
String sourceLine = sourceScan.nextLine();//call it source line
System.out.println(sourceLine); //print it out
String $product = sourceLine.toUpperCase(); //convert to upper and store in new var
try {
FileWriter myWriter = new FileWriter(writeFile);
myWriter.write($product);
myWriter.close();
System.out.println("Converted to upper: " + $product);
}
catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}}
catch(FileNotFoundException x){
System.out.println("error" + x);
}
}//end main()
}
Also see: PHP demo →