Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 173

Assignment no: 01

Chapter: 2, 3, 4, 5, 6
Course Name : Object Oriented Programming (JAVA) Laboratory
Course Code : CSE 212

Submitted To :
Dr. Md. Ezharul Islam, Professor
Department of Computer Science and Engineering
Jahangirnagar University

Submitted By :
Zakia Binta Syeed
Roll : 402
Department of Computer Science and Engineering
Jahangirnagar University

Department of Computer Science and Engineering


Faculty of Mathematical and Physical Sciences
Jahangirnagar University
Savar, Dhaka
Submitted Date: 04.05.24
Chapter 02
Problem 17: Write a program that displays a frame window800pixels
wide and600pixels high. Set the title of the frame to Welcome to Java.

Code:
import javax.swing.*;
class Window {
public static void main(String[] args){
JFrame myWindow;
myWindow= new JFrame();
myWindow.setSize(800,600);
myWindow.setTitle("Welcome to Java");
myWindow.setVisible(true);

Output:
Problem 18: Input the user’s first and last name as two separate strings.
Then display a frame window with its title set to , , where and are the
input values. For example, if the input values are Johann and Strauss,
then the title would be Strauss, Johann.
Code:
import javax.swing.*;
import java.util.Scanner;
public class windowWithName {
public static void main(String[] args) {

Scanner scanner;
scanner= new Scanner(System.in);
System.out.println("Enter first name:");
String firstName= scanner.next();
System.out.println("Enter last name:");
String lastName= scanner.next();

JFrame frame = new JFrame();


frame.setTitle(lastName + ", " + firstName);
frame.setSize(800, 600);
frame.setVisible(true);
}
}
Output:
Problem 19. Input the user’s first, middle, and last name as three
separate strings and display the name in the order of the first name, the
middle initial, and the last name. Include the period after the middle
initial. If the input strings are Wolfgang, Amadeus, and Mozart, for
example, then the ouput would be Wolfgang A. Mozart. Use the console
window for output.
Code:
import java.util.Scanner;

public class NameFormat {


public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter your first name: ");


String firstName = scanner.nextLine();

System.out.print("Enter your middle name: ");


String middleName = scanner.nextLine();

System.out.print("Enter your last name: ");


String lastName = scanner.nextLine();
scanner.close();

String formattedName = firstName + " " + middleName.charAt(0) + ". " +


lastName;
System.out.println("Formatted Name: " + formattedName);
}
}
Output:
Problem 20. Write a program to display today’s date in this format: 10
December 2008. Use the console window for output. Refer to Table 2.1
for the necessary designator symbols.
Code:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class Main {


public static void main(String[] args) {

LocalDate today = LocalDate.now();

String[] monthNames = {
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
};

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d MMMM


yyyy");
String formattedDate = today.format(formatter);

System.out.println("Today's date is: " + formattedDate);


}
}

Output :
Problem 21. Repeat Exercise 20, but this time use this format: Monday
December 10, 2008.
Code:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.Locale;

public class day {


public static void main(String[] args) {
// Get today's date
LocalDate today = LocalDate.now();

// Format the date as required


DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEEE MMMM dd,
yyyy", Locale.ENGLISH);
String formattedDate = today.format(formatter);

// Display the formatted date


System.out.println(formattedDate);
}
}

Output:
Problem 22. Write a program that displays a frame window W pixels
wide and H pixels high. Use the Scanner to enter the values for W and
H. The title of the frame is also entered by the user.

Code:
import javax.swing.*;
import java.util.Scanner;

public class FrameWindow {


public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);


System.out.print("Enter the width of the frame (in pixels): ");
int width = scanner.nextInt();

System.out.print("Enter the height of the frame (in pixels): ");


int height = scanner.nextInt();

scanner.nextLine();
System.out.print("Enter the title of the frame: ");
String title = scanner.nextLine();
JFrame frame = new JFrame();
frame.setTitle(title);
frame.setSize(width, height);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Output:
Problem 23. Display the current time in the title of a frame window
using this format: 12:45:43 PM. Refer to Table 2.1 for the necessary
designator symbols
Code:
import javax.swing.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FrameWindowWithTime {


public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Timer timer = new Timer(1000, e -> {
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm:ss a");
String currentTime = dateFormat.format(new Date());
frame.setTitle(currentTime);
});
timer.start();
frame.setSize(600, 400);
frame.setVisible(true);
}
}
Output:

Problem 24. Write a Java program that displays a frame window 300
pixels wide and 200 pixels high with the title My First Frame. Place the
frame so that its top left corner is at a position 50 pixels from the top of
the screen and 100 pixels from the left of the screen. To position a
window at a specified location, you use the setLocation method, as in
//assume mainWindow is declared and created frame.setLocation( 50, 50
); Through experimentation, determine how the two arguments in the
setLocation method affect the positioning of the window.

Code:
import javax.swing.*;

public class PositionedFrame {


public static void main(String[] args) {

JFrame frame = new JFrame();


frame.setTitle("My First Frame");
frame.setSize(300, 200);
int xPosition = 100;
int yPosition = 50;
frame.setLocation(xPosition, yPosition);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Output :
Problem 25. Because today’s computers are very fast, you will probably
not notice any discernible difference on the screen between the code
JFrame myWindow; myWindow = new JFrame();
myWindow.setVisible( true ); and JFrame myWindow; myWindow =
new JFrame(); myWindow.setVisible( true );
myWindow.setVisible( false ); myWindow.setVisible( true ); One way to
see the disappearance and reappearance of the window is to put a delay
between the successive setVisible messages. Here’s the magic code that
puts a delay of 0.5 s: try {Thread.sleep(500);} catch(Exception e){ } The
argument we pass to the sleep method specifies the amount of delay in
milliseconds [note: 1000 milliseconds (ms)= 1 second (s)]. We will not
explain this magic code.

Code:
import javax.swing.*;

public class VisibilityDemo {


public static void main(String[] args) {

JFrame myWindow = new JFrame();


myWindow.setTitle("Visibility Demo");
myWindow.setSize(300, 200);
myWindow.setVisible(true);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
myWindow.setVisible(false);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
myWindow.setVisible(true);
}
}
Output:
Chapter-3

7. Write a program to convert centimeters (input) to feet and inches


(output). 1 in= 2.54cm.

Code:
import java.util.Scanner;
public class CMToFeetAndInches {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter length in centimeters: ");


double cm = scanner.nextDouble();

double inches = cm / 2.54;


int feet = (int) (inches / 12);
double remainingInches = inches % 12;

System.out.println("Length in feet and inches: " + feet + " feet " +


remainingInches + " inches");
}
}

Output:

8. Write a program that inputs temperature in degrees Celsius and prints


out the temperature in degrees Fahrenheit. The formula to convert
degrees Celsius to equivalent degrees Fahrenheit is
Fahrenheit=1.8*Celsius+32

Code:
import java.util.Scanner;
public class CelsiusToFahrenheit {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter temperature in Celsius: ");


double celsius = scanner.nextDouble();

double fahrenheit = (1.8 * celsius) + 32;


System.out.println("Temperature in Fahrenheit: " + fahrenheit);
}
}

Output:

9. Write a program that accepts a person’s weight and displays the


number of calories the person needs in one day. A person needs 19
calories per pound of body weight, so the formula expressed in Java is
calories = bodyWeight * 19; (Note: We are not distinguishing between
genders.)

Code:
import java.util.Scanner;
public class CalorieCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your weight in pounds: ");
double weight = scanner.nextDouble();

double calories = weight * 19;


System.out.println("You need " + calories + " calories per day.");
}
}
Output:

10. Write a program that does the reverse of Exercise 9, that is, input
degrees Fahrenheit and prints out the temperature in degrees Celsius.
The formula to convert degrees Fahrenheit to equivalent degrees Celsius
is Celsius=5/9*(Fahrenheit-32)
Code:
import java.util.Scanner;
public class FahrenheitToCelsius {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter temperature in Fahrenheit: ");


double fahrenheit = scanner.nextDouble();

double celsius = (5.0 / 9.0) * (fahrenheit - 32);

System.out.println("Temperature in Celsius: " + celsius + " Degree


C");
}
}
Output:
11. Write a program that inputs the year a person is born and outputs the
age of the person in the following format: You were born in 1990 and
will be (are) 18 this year.

Code:
import java.util.Scanner;
import java.time.LocalDate;

public class AgeCalculator {


public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);


System.out.print("Enter the year you were born: ");
int birthYear = scanner.nextInt();

int currentYear = LocalDate.now().getYear();

int age = currentYear - birthYear;


System.out.println("You were born in " + birthYear + " and will be
(are) " + age + " this year.");
}
}
Output:
12. Aquantity known as the body mass index (BMI) is used to calculate
the risk of weight-related health problems. BMI is computed by the
formula BMI=w/(h/100.0)^2. where w is weight in kilograms and h is
height in centimeters. A BMI of about 20 to 25 is considered “normal.”
Write an application that accepts weight and height (both integers) and
outputs the BMI.

Code:
import java.util.Scanner;
public class BMIcalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter your weight in kilograms: ");


int weight = scanner.nextInt();

System.out.print("Enter your height in centimeters: ");


int height = scanner.nextInt();

double bmi = calculateBMI(weight, height);


System.out.println("Your BMI is: " + bmi);
}
public static double calculateBMI(int weight, int height) {
double heightInMeters = height / 100.0;
return weight / (heightInMeters * heightInMeters);
}
}
Output:

13. If you invest P dollars at R percent interest rate compounded


annually, in N years, your investment will grow to P*(1+R/100)^N
dollars. Write an application that accepts P, R, and N and computes the
amount of money earned after N years.
Code:
import java.util.Scanner;
public class InterestCalculator {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the principal amount (P): ");


double principal = scanner.nextDouble();

System.out.print("Enter the annual interest rate (R) in percent: ");


double rate = scanner.nextDouble();

System.out.print("Enter the number of years (N): ");


int years = scanner.nextInt();

rate /= 100;
double amount = principal * Math.pow(1 + rate, years);

System.out.println("Amount earned after " + years + " years: $" +


amount);
}
}
Output:

14. The volume of a sphere is computed by the equation V=4/3*r^3


where V is the volume and r is the radius of the sphere. Write a program
that computes the volume of a sphere with a given radius r.

Code:
import java.util.Scanner;
public class SphereVolumeCalculator {
public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the radius of the sphere: ");

double radius = scanner.nextDouble();

double volume = (4.0 / 3.0) * Math.PI * Math.pow(radius, 3);

System.out.println("The volume of the sphere is: " + volume);

}
}
Output:
15. The velocity of a satellite circling around the Earth is computed by
the formula v=root(G*ME/r) where ME=5.98*10^24 kg is the mass of
the Earth, r the distance from the center of the Earth to the satellite in
meters, and G=6.67*10^11 m3/kg s2 the universal gravitational
constant. The unit of the velocity v is m/s. Write a program that inputs
the radius r and outputs the satellite’s velocity. Confirm that a satellite
that is closer to the Earth travels faster. Define symbolic constants for
ME and G. The distance to the Hubble Space Telescope from the center
of the Earth, for example, is approximately 6.98*10^6 m.

Code:
import java.util.Scanner;
public class SatelliteVelocity {

static final double ME = 5.98e24;


static final double G = 6.67e-11;

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the radius from the center of the Earth to


the satellite (in meters): ");
double r = scanner.nextDouble();

double velocity = satelliteVelocity(r);

System.out.println("The velocity of the satellite is: " + velocity + "


m/s");

scanner.close();
}

static double satelliteVelocity(double r) {


return Math.sqrt((G * ME) / r);
}
}
Output:

16. Your weight is actually the amount of gravitational attraction exerted


on you by the Earth. Since the Moon’s gravity is only one-sixth of the
Earth’s gravity, on the Moon you would weigh only one-sixth of what
you weigh on Earth. Write a program that inputs the user’s Earth weight
and outputs her or his weight on Mercury, Venus, Jupiter, and Saturn.
Use the values in this table.

Planet Multiply the Earth Weight by


_______________________________________________________
Mercury 0.4
Venus 0.9
Jupiter 2.5
Saturn 1.1

Code:
import java.util.Scanner;
public class WeightCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter your weight on Earth (in kg): ");


double earthWeight = scanner.nextDouble();

final double MERCURY_MULTIPLIER = 0.4;


final double VENUS_MULTIPLIER = 0.9;
final double JUPITER_MULTIPLIER = 2.5;
final double SATURN_MULTIPLIER = 1.1;

double weightOnMercury = earthWeight *


MERCURY_MULTIPLIER;
double weightOnVenus = earthWeight * VENUS_MULTIPLIER;
double weightOnJupiter = earthWeight * JUPITER_MULTIPLIER;
double weightOnSaturn = earthWeight * SATURN_MULTIPLIER;

System.out.println("Your weight on Mercury: " +


weightOnMercury + " kg");
System.out.println("Your weight on Venus: " + weightOnVenus + "
kg");
System.out.println("Your weight on Jupiter: " + weightOnJupiter +
" kg");
System.out.println("Your weight on Saturn: " + weightOnSaturn + "
kg");

scanner.close();
}
}
Output:

17. When you say you are 18 years old, you are really saying that the
Earth has circled the Sun 18 times. Since other planets take fewer or
more days than Earth to travel around the Sun, your age would be
different on other planets. You can compute how old you are on other
planets by the formula y=(x*365)/d where x is the age on Earth, y is the
age on planet Y, and d is the number of Earth days the planet Y takes to
travel around the Sun. Write an application that inputs the user’s Earth
age and print outs his or her age on Mercury, Venus, Jupiter, and Saturn.
The values for d are listed in the table.
Planet d=Approximate Earth Days for This Planet to
Travel around the Sun
Mercury _____________________________88
Venus ______________________________225
Jupiter_____________________________4380
Saturn____________________________10767

Code:
import java.util.Scanner;
public class AgeOnOtherPlanets {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter your age on Earth: ");


int earthAge = scanner.nextInt();

double mercuryAge = (earthAge * 365) / 88.0;


System.out.println("Your age on Mercury: " + mercuryAge + "
years");

double venusAge = (earthAge * 365) / 225.0;


System.out.println("Your age on Venus: " + venusAge + " years");

double jupiterAge = (earthAge * 365) / 4380.0;


System.out.println("Your age on Jupiter: " + jupiterAge + " years");

double saturnAge = (earthAge * 365) / 10767.0;


System.out.println("Your age on Saturn: " + saturnAge + " years");
}
}
Output:

19. Write a programthat determines the number of days in a given


semester. Input to the program is the year, month, and day information
of the first and the last days of a semester. Hint:Create
GregorianCalendarobjects for the start and end dates of a semester and
manipulate their DAY_OF_YEARdata.

Code:
import java.util.Scanner;
import java.util.GregorianCalendar;
public class SemesterDaysCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the start year of the semester:");
int startYear = scanner.nextInt();

System.out.println("Enter the start month of the semester:");


int startMonth = scanner.nextInt();

System.out.println("Enter the start day of the semester:");


int startDay = scanner.nextInt();

System.out.println("Enter the end year of the semester:");


int endYear = scanner.nextInt();

System.out.println("Enter the end month of the semester:");


int endMonth = scanner.nextInt();

System.out.println("Enter the end day of the semester:");


int endDay = scanner.nextInt();

scanner.close();

GregorianCalendar startDate = new GregorianCalendar(startYear,


startMonth - 1, startDay);
GregorianCalendar endDate = new GregorianCalendar(endYear,
endMonth - 1, endDay);

int daysInSemester = calculateDaysInSemester(startDate, endDate);

System.out.println("Number of days in the semester: " +


daysInSemester);
}

public static int calculateDaysInSemester(GregorianCalendar


startDate, GregorianCalendar endDate) {
int daysInSemester = 0;

daysInSemester =
endDate.get(GregorianCalendar.DAY_OF_YEAR) -
startDate.get(GregorianCalendar.DAY_OF_YEAR) + 1;

if (endDate.get(GregorianCalendar.YEAR) >
startDate.get(GregorianCalendar.YEAR)) {
daysInSemester +=
endDate.get(GregorianCalendar.DAY_OF_YEAR);
if
(startDate.isLeapYear(startDate.get(GregorianCalendar.YEAR)))
daysInSemester += 1;
}
return daysInSemester;
}
}
Output:

20. Modify the Ch3FindDayOfWeekprogram by accepting the date


information as a single string instead of accepting the year, month, and
day information separately. The input string must be in the MM/dd/yyyy
format. For example, July 4, 1776, is entered as 07/04/1776. There will
be exactly two digits for the month and day and four digits for the year.
Code:
import java.util.Scanner;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public class Ch3FindDayOfWeek {
public static String findDayOfWeek(String dateStr) {
try {
LocalDate date = LocalDate.parse(dateStr,
DateTimeFormatter.ofPattern("MM/dd/yyyy"));
return date.getDayOfWeek().toString();
} catch (DateTimeParseException e) {
return "Invalid date format. Please enter the date in MM/dd/yyyy
format.";
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the date (MM/dd/yyyy): ");


String dateInput = scanner.nextLine();

String dayOfWeek = findDayOfWeek(dateInput);


System.out.println("The day of the week is: " + dayOfWeek);
}
}
Output:

21. Leonardo Fibonacci of Pisa was one of the greatest mathematicians


of the Middle Ages. He is perhaps most famous for the Fibonacci
sequence, which can be applied to many diverse problems. One amusing
application of the Fibonacci sequence is in finding the growth rate of
rabbits. Suppose a pair of rabbits matures in 2 months and is capable of
reproducing another pair every month after maturity. If every new pair
has the same capability, how many pairs will there be after 1 year? (We
assume here that no pairs die.) The table below shows the sequence for
the first 7 months. Notice that at the end of the second month, the first
pair matures and bears its first offspring in the third month, making the
total two pairs. Write an application that accepts Nand displays FN. Note
that the result of computation using the Mathclass is double. You need to
display it as an integer.
Code:
import java.util.Scanner;

public class FibonacciRabbits {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of months (N): ");
int N = scanner.nextInt();

int result = calculatePairs(N);

System.out.println("Number of pairs after " + N + " months: " +


result);
}
public static int calculatePairs(int N) {
if (N <= 1)
return N;

int prev = 1;
int curr = 1;

for (int i = 2; i < N; i++) {


int next = prev + curr;
prev = curr;
curr = next;
}
return curr;
}
}
Output:

27. Ask the user to enter his or her birthday in the MM/DD/YYYY
format and output the number of days between the birthday and today.
This gives the person’s age in days.
Code:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Scanner;

public class AgeCalculator {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("MM/dd/yyyy");

System.out.print("Enter your birthday (MM/DD/YYYY): ");


String birthdayInput = scanner.nextLine();

LocalDate birthday = LocalDate.parse(birthdayInput, formatter);


LocalDate today = LocalDate.now();

long ageInDays = ChronoUnit.DAYS.between(birthday, today);

System.out.println("Your age in days is: " + ageInDays);


}
}
Output:

Chapter-3:
7. Write a program to convert centimeters (input) to feet and inches
(output). 1 in= 2.54cm.

Code:
import java.util.Scanner;
public class CMToFeetAndInches {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter length in centimeters: ");


double cm = scanner.nextDouble();

double inches = cm / 2.54;


int feet = (int) (inches / 12);
double remainingInches = inches % 12;

System.out.println("Length in feet and inches: " + feet + " feet " +


remainingInches + " inches");
}
}
Output:

8. Write a program that inputs temperature in degrees Celsius and prints


out the temperature in degrees Fahrenheit. The formula to convert
degrees Celsius to equivalent degrees Fahrenheit is
Fahrenheit=1.8*Celsius+32

Code:
import java.util.Scanner;
public class CelsiusToFahrenheit {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter temperature in Celsius: ");


double celsius = scanner.nextDouble();

double fahrenheit = (1.8 * celsius) + 32;

System.out.println("Temperature in Fahrenheit: " + fahrenheit);


}
}

Output:

9. Write a program that accepts a person’s weight and displays the


number of calories the person needs in one day. A person needs 19
calories per pound of body weight, so the formula expressed in Java is
calories = bodyWeight * 19; (Note: We are not distinguishing between
genders.)

Code:
import java.util.Scanner;
public class CalorieCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter your weight in pounds: ");


double weight = scanner.nextDouble();

double calories = weight * 19;


System.out.println("You need " + calories + " calories per day.");
}
}
Output:

10. Write a program that does the reverse of Exercise 9, that is, input
degrees Fahrenheit and prints out the temperature in degrees Celsius.
The formula to convert degrees Fahrenheit to equivalent degrees Celsius
is Celsius=5/9*(Fahrenheit-32)

Code:
import java.util.Scanner;
public class FahrenheitToCelsius {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter temperature in Fahrenheit: ");


double fahrenheit = scanner.nextDouble();

double celsius = (5.0 / 9.0) * (fahrenheit - 32);

System.out.println("Temperature in Celsius: " + celsius + " Degree


C");
}
}
Output:

11. Write a program that inputs the year a person is born and outputs the
age of the person in the following format: You were born in 1990 and
will be (are) 18 this year.
Code:
import java.util.Scanner;
import java.time.LocalDate;

public class AgeCalculator {


public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);


System.out.print("Enter the year you were born: ");
int birthYear = scanner.nextInt();

int currentYear = LocalDate.now().getYear();

int age = currentYear - birthYear;


System.out.println("You were born in " + birthYear + " and will be
(are) " + age + " this year.");
}
}
Output:
12. Aquantity known as the body mass index (BMI) is used to calculate
the risk of weight-related health problems. BMI is computed by the
formula BMI=w/(h/100.0)^2. where w is weight in kilograms and h is
height in centimeters. A BMI of about 20 to 25 is considered “normal.”
Write an application that accepts weight and height (both integers) and
outputs the BMI.

Code:
import java.util.Scanner;
public class BMIcalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter your weight in kilograms: ");


int weight = scanner.nextInt();

System.out.print("Enter your height in centimeters: ");


int height = scanner.nextInt();

double bmi = calculateBMI(weight, height);


System.out.println("Your BMI is: " + bmi);
}

public static double calculateBMI(int weight, int height) {


double heightInMeters = height / 100.0;
return weight / (heightInMeters * heightInMeters);
}
}
Output:

13. If you invest P dollars at R percent interest rate compounded


annually, in N years, your investment will grow to P*(1+R/100)^N
dollars. Write an application that accepts P, R, and N and computes the
amount of money earned after N years.
Code:
import java.util.Scanner;
public class InterestCalculator {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the principal amount (P): ");


double principal = scanner.nextDouble();
System.out.print("Enter the annual interest rate (R) in percent: ");
double rate = scanner.nextDouble();

System.out.print("Enter the number of years (N): ");


int years = scanner.nextInt();

rate /= 100;
double amount = principal * Math.pow(1 + rate, years);

System.out.println("Amount earned after " + years + " years: $" +


amount);
}
}
Output:

14. The volume of a sphere is computed by the equation V=4/3*r^3


where V is the volume and r is the radius of the sphere. Write a program
that computes the volume of a sphere with a given radius r.
Code:
import java.util.Scanner;
public class SphereVolumeCalculator {
public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the radius of the sphere: ");

double radius = scanner.nextDouble();

double volume = (4.0 / 3.0) * Math.PI * Math.pow(radius, 3);

System.out.println("The volume of the sphere is: " + volume);

}
}
Output:

15. The velocity of a satellite circling around the Earth is computed by


the formula v=root(G*ME/r) where ME=5.98*10^24 kg is the mass of
the Earth, r the distance from the center of the Earth to the satellite in
meters, and G=6.67*10^11 m3/kg s2 the universal gravitational
constant. The unit of the velocity v is m/s. Write a program that inputs
the radius r and outputs the satellite’s velocity. Confirm that a satellite
that is closer to the Earth travels faster. Define symbolic constants for
ME and G. The distance to the Hubble Space Telescope from the center
of the Earth, for example, is approximately 6.98*10^6 m.

Code:
import java.util.Scanner;
public class SatelliteVelocity {

static final double ME = 5.98e24;


static final double G = 6.67e-11;

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the radius from the center of the Earth to


the satellite (in meters): ");
double r = scanner.nextDouble();

double velocity = satelliteVelocity(r);

System.out.println("The velocity of the satellite is: " + velocity + "


m/s");

scanner.close();
}
static double satelliteVelocity(double r) {
return Math.sqrt((G * ME) / r);
}
}
Output:

16. Your weight is actually the amount of gravitational attraction exerted


on you by the Earth. Since the Moon’s gravity is only one-sixth of the
Earth’s gravity, on the Moon you would weigh only one-sixth of what
you weigh on Earth. Write a program that inputs the user’s Earth weight
and outputs her or his weight on Mercury, Venus, Jupiter, and Saturn.
Use the values in this table.

Planet Multiply the Earth Weight by


_______________________________________________________
Mercury 0.4
Venus 0.9
Jupiter 2.5
Saturn 1.1
Code:
import java.util.Scanner;
public class WeightCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter your weight on Earth (in kg): ");


double earthWeight = scanner.nextDouble();

final double MERCURY_MULTIPLIER = 0.4;


final double VENUS_MULTIPLIER = 0.9;
final double JUPITER_MULTIPLIER = 2.5;
final double SATURN_MULTIPLIER = 1.1;

double weightOnMercury = earthWeight *


MERCURY_MULTIPLIER;
double weightOnVenus = earthWeight * VENUS_MULTIPLIER;
double weightOnJupiter = earthWeight * JUPITER_MULTIPLIER;
double weightOnSaturn = earthWeight * SATURN_MULTIPLIER;

System.out.println("Your weight on Mercury: " +


weightOnMercury + " kg");
System.out.println("Your weight on Venus: " + weightOnVenus + "
kg");
System.out.println("Your weight on Jupiter: " + weightOnJupiter +
" kg");
System.out.println("Your weight on Saturn: " + weightOnSaturn + "
kg");

scanner.close();
}
}
Output:

17. When you say you are 18 years old, you are really saying that the
Earth has circled the Sun 18 times. Since other planets take fewer or
more days than Earth to travel around the Sun, your age would be
different on other planets. You can compute how old you are on other
planets by the formula y=(x*365)/d where x is the age on Earth, y is the
age on planet Y, and d is the number of Earth days the planet Y takes to
travel around the Sun. Write an application that inputs the user’s Earth
age and print outs his or her age on Mercury, Venus, Jupiter, and Saturn.
The values for d are listed in the table.
Planet d=Approximate Earth Days for This Planet to
Travel around the Sun
Mercury _____________________________88
Venus ______________________________225
Jupiter_____________________________4380
Saturn____________________________10767

Code:
import java.util.Scanner;
public class AgeOnOtherPlanets {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter your age on Earth: ");


int earthAge = scanner.nextInt();

double mercuryAge = (earthAge * 365) / 88.0;


System.out.println("Your age on Mercury: " + mercuryAge + "
years");

double venusAge = (earthAge * 365) / 225.0;


System.out.println("Your age on Venus: " + venusAge + " years");

double jupiterAge = (earthAge * 365) / 4380.0;


System.out.println("Your age on Jupiter: " + jupiterAge + " years");

double saturnAge = (earthAge * 365) / 10767.0;


System.out.println("Your age on Saturn: " + saturnAge + " years");
}
}
Output:

19. Write a programthat determines the number of days in a given


semester. Input to the program is the year, month, and day information
of the first and the last days of a semester. Hint:Create
GregorianCalendarobjects for the start and end dates of a semester and
manipulate their DAY_OF_YEARdata.

Code:
import java.util.Scanner;
import java.util.GregorianCalendar;
public class SemesterDaysCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the start year of the semester:");
int startYear = scanner.nextInt();

System.out.println("Enter the start month of the semester:");


int startMonth = scanner.nextInt();

System.out.println("Enter the start day of the semester:");


int startDay = scanner.nextInt();

System.out.println("Enter the end year of the semester:");


int endYear = scanner.nextInt();

System.out.println("Enter the end month of the semester:");


int endMonth = scanner.nextInt();

System.out.println("Enter the end day of the semester:");


int endDay = scanner.nextInt();

scanner.close();

GregorianCalendar startDate = new GregorianCalendar(startYear,


startMonth - 1, startDay);
GregorianCalendar endDate = new GregorianCalendar(endYear,
endMonth - 1, endDay);

int daysInSemester = calculateDaysInSemester(startDate, endDate);

System.out.println("Number of days in the semester: " +


daysInSemester);
}

public static int calculateDaysInSemester(GregorianCalendar


startDate, GregorianCalendar endDate) {
int daysInSemester = 0;
daysInSemester =
endDate.get(GregorianCalendar.DAY_OF_YEAR) -
startDate.get(GregorianCalendar.DAY_OF_YEAR) + 1;

if (endDate.get(GregorianCalendar.YEAR) >
startDate.get(GregorianCalendar.YEAR)) {
daysInSemester +=
endDate.get(GregorianCalendar.DAY_OF_YEAR);
if
(startDate.isLeapYear(startDate.get(GregorianCalendar.YEAR)))
daysInSemester += 1;
}
return daysInSemester;
}
}
Output:
20. Modify the Ch3FindDayOfWeekprogram by accepting the date
information as a single string instead of accepting the year, month, and
day information separately. The input string must be in the MM/dd/yyyy
format. For example, July 4, 1776, is entered as 07/04/1776. There will
be exactly two digits for the month and day and four digits for the year.
Code:
import java.util.Scanner;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

public class Ch3FindDayOfWeek {


public static String findDayOfWeek(String dateStr) {
try {
LocalDate date = LocalDate.parse(dateStr,
DateTimeFormatter.ofPattern("MM/dd/yyyy"));
return date.getDayOfWeek().toString();
} catch (DateTimeParseException e) {
return "Invalid date format. Please enter the date in MM/dd/yyyy
format.";
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the date (MM/dd/yyyy): ");


String dateInput = scanner.nextLine();

String dayOfWeek = findDayOfWeek(dateInput);


System.out.println("The day of the week is: " + dayOfWeek);
}
}
Output:

21. Leonardo Fibonacci of Pisa was one of the greatest mathematicians


of the Middle Ages. He is perhaps most famous for the Fibonacci
sequence, which can be applied to many diverse problems. One amusing
application of the Fibonacci sequence is in finding the growth rate of
rabbits. Suppose a pair of rabbits matures in 2 months and is capable of
reproducing another pair every month after maturity. If every new pair
has the same capability, how many pairs will there be after 1 year? (We
assume here that no pairs die.) The table below shows the sequence for
the first 7 months. Notice that at the end of the second month, the first
pair matures and bears its first offspring in the third month, making the
total two pairs. Write an application that accepts Nand displays FN. Note
that the result of computation using the Mathclass is double. You need to
display it as an integer.
Code:
import java.util.Scanner;

public class FibonacciRabbits {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of months (N): ");
int N = scanner.nextInt();

int result = calculatePairs(N);

System.out.println("Number of pairs after " + N + " months: " +


result);
}
public static int calculatePairs(int N) {
if (N <= 1)
return N;

int prev = 1;
int curr = 1;
for (int i = 2; i < N; i++) {
int next = prev + curr;
prev = curr;
curr = next;
}
return curr;
}
}
Output:

27. Ask the user to enter his or her birthday in the MM/DD/YYYY
format and output the number of days between the birthday and today.
This gives the person’s age in days.
Code:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Scanner;
public class AgeCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("MM/dd/yyyy");

System.out.print("Enter your birthday (MM/DD/YYYY): ");


String birthdayInput = scanner.nextLine();

LocalDate birthday = LocalDate.parse(birthdayInput, formatter);


LocalDate today = LocalDate.now();

long ageInDays = ChronoUnit.DAYS.between(birthday, today);

System.out.println("Your age in days is: " + ageInDays);


}
}
Output:
Chapter 4
#5.
In the RollDice program, we created three Die objects and rolled them
once.
Rewrite the program so you will create only one Die object and roll it
three
times.

Code:
import java.util.Random;

class java {
private int sides;
private Random random;

public java(int sides) {


this.sides = sides;
random = new Random();
}

public int roll() {


return random.nextInt(sides) + 1;
}
}

class RollDice {
public static void main(String[] args) {
java die = new java(6);

for (int i = 0; i < 3; i++) {


int result = die.roll();
System.out.println("Roll " + (i + 1) + ": " + result);
}
}
}
Output:

#6.

Write a program that computes the total ticket sales of a concert. There
are
three types of seatings: A, B, and C. The program accepts the number of
tickets sold and the price of a ticket for each of the three types of seats.
The
total sales are computed as follows:
totalSales = numberOfA_Seats * pricePerA_Seat +
numberOfB_Seats * pricePerB_Seat +
numberOfC_Seats * pricePerC_Seat;
Write this program, using only one class, the main class of the program.

Code:
import java.util.Scanner;

class java {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("Enter the number of tickets sold for seating type


A:");
int number_of_a_seats = scanner.nextInt();

System.out.println("Enter the number of tickets sold for seating type


B:");
int number_of_b_seats = scanner.nextInt();

System.out.println("Enter the number of tickets sold for seating type


C:");
int number_of_c_seats = scanner.nextInt();

System.out.println("Enter the price of a ticket for seating type A:");


double price_per_a_seat = scanner.nextDouble();

System.out.println("Enter the price of a ticket for seating type B:");


double price_per_b_seat = scanner.nextDouble();

System.out.println("Enter the price of a ticket for seating type C:");


double price_per_c_seat = scanner.nextDouble();

double total_sales = number_of_a_seats * price_per_a_seat +


number_of_b_seats * price_per_b_seat +
number_of_c_seats * price_per_c_seat;

System.out.println("Total ticket sales: $" + total_sales);

scanner.close();
}
}

Output:
#7.
Define a new class named Temperature. The class has two accessors—
to-
Fahrenheit and toCelsius—that return the temperature in the specified
unit
and two mutators—setFahrenheit and setCelsius—that assign the
temperature
in the specified unit. Maintain the temperature internally in degrees
Fahrenheit.
Using this class, write a program that inputs temperature in degrees
Fahrenheit and outputs the temperature in equivalent degrees Celsius.
Code:

import java.util.Scanner;

class java {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("Enter temperature in degrees Fahrenheit:");


double temperature_fahrenheit = scanner.nextDouble();

Temperature temp = new Temperature();


temp.set_fahrenheit(temperature_fahrenheit);

double temperature_celsius = temp.to_celsius();

System.out.println("Temperature in degrees Celsius: " +


temperature_celsius);

scanner.close();
}
}
class Temperature {
private double temperature_fahrenheit;

public void set_fahrenheit(double temperature_fahrenheit) {


this.temperature_fahrenheit = temperature_fahrenheit;
}

public void set_celsius(double temperature_celsius) {


this.temperature_fahrenheit = (temperature_celsius - 32) * 5 / 9;
}

public double to_fahrenheit() {


return temperature_fahrenheit;
}

public double to_celsius() {


return (temperature_fahrenheit - 32) * 5 / 9;
}
}

Output:
#8.
Using the Temperature class from Exercise 7, write a program that
inputs
temperature in degrees Celsius and outputs the temperature in equivalent
degrees Fahrenheit.

Code:

import java.util.Scanner;

class Temperature {
private double celsius;

public Temperature(double celsius) {


this.celsius = celsius;
}
public double toFahrenheit() {
return (celsius * 9 / 5) + 32;
}
}

class java {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter temperature in degrees Celsius: ");
double celsius = input.nextDouble();

Temperature temperature = new Temperature(celsius);


double fahrenheit = temperature.toFahrenheit();

System.out.println("Equivalent temperature in Fahrenheit: " +


fahrenheit);
}
}

Output:
#9.
Write a program that computes the area of a circular region (the shaded
area
in the diagram), given the radii of the inner and the outer circles, ri and
ro,
respectively.
ri ro
Exercises 217
private String getLetter(String str) {
temp = str.substring(idx, idx+1);
return temp;
}
}
We compute the area of the circular region by subtracting the area of the
inner circle from the area of the outer circle. Define a Circle class that
has
methods to compute the area and circumference. You set the circle’s
radius
with the setRadius method or via a constructor.

Code:

class circle_area_calculator {
public static void main(String[] args) {
Circle outerCircle = new Circle(5.0);
Circle innerCircle = new Circle(2.0);

double areaOfOuterCircle = outerCircle.calculateArea();


double areaOfInnerCircle = innerCircle.calculateArea();

double areaOfCircularRegion = areaOfOuterCircle -


areaOfInnerCircle;

System.out.println("Area of the circular region: " +


areaOfCircularRegion);
}
}

class Circle {
private double radius;

public Circle(double radius) {


this.radius = radius;
}

public void setRadius(double radius) {


this.radius = radius;
}

public double calculateArea() {


return Math.PI * Math.pow(radius, 2);
}

public double calculateCircumference() {


return 2 * Math.PI * radius;
}
}

Output:
#10.
Modify the Bicycle class so instead of assigning the name of an owner
(Student), you can assign the owner object itself. Model this new
Bicycle
class after the LibraryCard class.

Code:
public class Bicycle {
private Student owner;
private int bicycleID;

public Bicycle(Student owner, int bicycleID) {


this.owner = owner;
this.bicycleID = bicycleID;
}

public Student getOwner() {


return owner;
}

public void setOwner(Student owner) {


this.owner = owner;
}
public int getBicycleID() {
return bicycleID;
}

public void setBicycleID(int bicycleID) {


this.bicycleID = bicycleID;
}
}

class Student {
private String name;

public Student(String name) {


this.name = name;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}
}

12.
Write a program that displays the recommended weight (kg), given the
user’s age and height (cm). The formula for calculating the
recommended
weight is
recommendedWeight = (height - 100 + age / 10) * 0.90
Define a service class named Height and include an appropriate method
for
getting a recommended weight of a designated height.
Code:

class recommended_weight_calculator {
public static void main(String[] args) {
int age = 30;
int height = 180;

Height height_service = new Height();


double recommended_weight =
height_service.get_recommended_weight(age, height);

System.out.println("Recommended weight: " +


recommended_weight + " kg");
}
}

class Height {
public double get_recommended_weight(int age, int height) {
return (height - 100 + age / 10) * 0.90;
}
}

Output:

13.
Redo Exercise 9 by using a Seat class. An instance of the Seat class
keeps
track of the ticket price for a given type of seat (A, B, or C).

Code:

class seat_price_calculator {
public static void main(String[] args) {
Seat seatA = new Seat("A", 50.0);
Seat seatB = new Seat("B", 40.0);
Seat seatC = new Seat("C", 30.0);

System.out.println("Price for seat type A: $" + seatA.getPrice());


System.out.println("Price for seat type B: $" + seatB.getPrice());
System.out.println("Price for seat type C: $" + seatC.getPrice());
}
}

class Seat {
private String type;
private double price;

public Seat(String type, double price) {


this.type = type;
this.price = price;
}

public String getType() {


return type;
}
public void setType(String type) {
this.type = type;
}

public double getPrice() {


return price;
}

public void setPrice(double price) {


this.price = price;
}
}

Output:
#14:
Write a WeightConverter class. An instance of this class is created by
passing the gravity of an object relative to the Earth’s gravity (see
Exercise 16 on page 144). For example, the Moon’s gravity is
approximately 0.167 of the Earth’s gravity, so we create a
WeightConverter instance for the Moon as
WeightConverter moonWeight;
moonWeight = new WeightConverter( 0.167 );
To compute how much you weigh on the Moon, you pass your weight
on
Earth to the convert method as
yourMoonWeight = moonWeight.convert( 160 );
Use this class and redo Exercise 16 on page 144.

Code:
class weight_converter {
public static void main(String[] args) {
WeightConverter moonWeight = new WeightConverter(0.167);
double yourMoonWeight = moonWeight.convert(160);
System.out.println("Your weight on the Moon: " +
yourMoonWeight + " kg");
}
}
class WeightConverter {
private double gravityRatio;

public WeightConverter(double gravityRatio) {


this.gravityRatio = gravityRatio;
}

public double convert(double weightOnEarth) {


return weightOnEarth * gravityRatio;
}
}

Output:

#15.
Redo Exercise 30
on page 149, but this time define and use programmerdefined
classes.
Code:

class population_growth_simulator {
public static void main(String[] args) {
Country china = new Country("China", 1439, 0.004);
Country india = new Country("India", 1380, 0.008);

System.out.println("Year | China Population | India Population");


System.out.println("------------------------------------------");
for (int year = 2022; year <= 2027; year++) {
china.growPopulation();
india.growPopulation();
System.out.printf("%d | %d | %d%n", year, china.getPopulation(),
india.getPopulation());
}
}
}

class Country {
private String name;
private int population;
private double growthRate;
public Country(String name, int population, double growthRate) {
this.name = name;
this.population = population;
this.growthRate = growthRate;
}

public void growPopulation() {


population += (int) (population * growthRate);
}

public int getPopulation() {


return population;
}
}

Output:
#16:
Write a program that accepts the unit weight of a bag of coffee in pounds
and the number of bags sold and displays the total price of the sale,
computed as follows:
totalPrice = bagWeight * numberOfBags * pricePerLb;
totalPriceWithTax = totalPrice + totalPrice * taxrate;
Display the result in the following manner:
Number of bags sold: 32
Weight per bag: 5 lb
Price per pound: $5.99
Sales tax: 7.25%
Total price: $ 1027.88
Define and use a programmer-defined CoffeeBag class. Include class
constants for the price per pound and tax rate with the values $5.99 per
pound and 7.25 percent, respectively.

Code:
class coffee_sales {
public static void main(String[] args) {
int numberOfBagsSold = 32;
double weightPerBag = 5.0;

CoffeeBag coffeeBag = new CoffeeBag();

double totalPrice =
coffeeBag.computeTotalPrice(numberOfBagsSold, weightPerBag);
double totalPriceWithTax =
coffeeBag.computeTotalPriceWithTax(totalPrice);

System.out.println("Number of bags sold: " + numberOfBagsSold);


System.out.println("Weight per bag: " + weightPerBag + " lb");
System.out.println("Price per pound: $" +
CoffeeBag.PRICE_PER_POUND);
System.out.println("Sales tax: " + CoffeeBag.TAX_RATE * 100 +
"%");
System.out.printf("Total price: $ %.2f%n", totalPriceWithTax);
}
}

class CoffeeBag {
public static final double PRICE_PER_POUND = 5.99;
public static final double TAX_RATE = 0.0725;

public double computeTotalPrice(int numberOfBags, double


weightPerBag) {
return numberOfBags * weightPerBag * PRICE_PER_POUND;
}

public double computeTotalPriceWithTax(double totalPrice) {


return totalPrice + totalPrice * TAX_RATE;
}
}

Output:
#17.
In the Turtle exercises from the earlier chapters, we dealt with only one
Turtle (e.g., see Exercise 32 on page 150). It is possible, however, to let
multiple turtles draw on a single drawing window. To associate multiple
turtles to a single drawing, we create an instance of
TurtleDrawingWindow
and add turtles to it as follows:
TurtleDrawingWindow canvas = new TurtleDrawingWindow( );
Turtle winky, pinky, tinky;
//create turtles;
//pass Turtle.NO_DEFAULT_WINDOW as an argument so
//no default drawing window is attached to a turtle.
winky = new Turtle(Turtle.NO_DEFAULT_WINDOW);
pinky = new Turtle(Turtle.NO_DEFAULT_WINDOW);
tinky = new Turtle(Turtle.NO_DEFAULT_WINDOW);
//now add turtles to the drawing window
canvas.add( winky );
canvas.add( pinky );
canvas.add( tinky );
Exercises 219
Format to two
decimal places.
Ordinarily, when you start sending messages such as turn and move to a
Turtle, it will begin moving immediately. When you have only one
Turtle, this
is fine. However, if you have multiple turtles and want them to start
moving
at the same time, you have to first pause them, then give instructions,
and
finally command them to start moving. Here’s the basic idea:
winky.pause( );
pinky.pause( );
tinky.pause( );
//give instructions to turtles here,
//e.g., pinky.move(50); etc.
//now let the turtles start moving
winky.start( );
pinky.start( );
tinky.start( );
Using these Turtle objects, draw the following three triangles:
Use a different pen color for each triangle. Run the same program
without
pausing and describe what happens.

Code:
import stanford.turtle.TurtleDrawingWindow;
import java.awt.Color;

public class DrawTriangles {


public static void main(String[] args) {
TurtleDrawingWindow canvas = new TurtleDrawingWindow();
canvas.setSize(500, 500);

stanford.turtle.Turtle winky = new stanford.turtle.Turtle(canvas);


stanford.turtle.Turtle pinky = new stanford.turtle.Turtle(canvas);
stanford.turtle.Turtle tinky = new stanford.turtle.Turtle(canvas);

winky.setPenColor(Color.RED);
winky.penDown();
drawTriangle(winky, 100);

pinky.setPenColor(Color.GREEN);
pinky.penDown();
drawTriangle(pinky, 100);

tinky.setPenColor(Color.BLUE);
tinky.penDown();
drawTriangle(tinky, 100);
}

private static void drawTriangle(stanford.turtle.Turtle turtle, double


sideLength) {
for (int i = 0; i < 3; i++) {
turtle.forward(sideLength);
turtle.right(120);
}
}
}
Chapter -5
9. One million is 106 and 1 billion is 109 . Write a program that reads a
power of 10 (6, 9, 12, etc.) and displays how big the number is (Million,
Billion,etc.). Display an appropriate message for the input value that has
nocorresponding word. The table below shows the correspondence
between the power of 10 and the word for that number.
Power of 10 Number
6 Million
9 Billion
12 Trillion
15 Quadrillion
18 Quintillion
21 Sextillion
30 Nonillion
100 Googol
Code:
import java.util.Scanner;

public class NumberSize {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the power of 10: ");
int power = scanner.nextInt();
String size;
switch (power) {
case 6:
size = "Million";
break;
case 9:
size = "Billion";
break;
case 12:
size = "Trillion";
break;
case 15:
size = "Quadrillion";
break;
case 18:
size = "Quintillion";
break;
case 21:
size = "Sextillion";
break;
case 30:
size = "Nonillion";
break;
case 100:
size = "Googol";
break;
default:
size = "No corresponding word";
break;
}

System.out.println("The number is " + size);


}
}

10. Write a program RecommendedWeightWithTest by extending the


Recommended Weight (see Exercise 8 on page 209). The extended
program will include the following test:
if (the height is between 140cm and 230cm)
compute the recommended weight
else
display an error message
code:
import java.util.Scanner;

public class RecommendedWeightWithTest {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter your height in cm: ");


double height = scanner.nextDouble();

if (height >= 140 && height <= 230) {


double recommendedWeight =
calculateRecommendedWeight(height);
System.out.println("Your recommended weight is: " +
recommendedWeight + " kg");
} else {
System.out.println("Error: Height must be between 140cm and
230cm.");
}
}
public static double calculateRecommendedWeight(double height) {
return height - 100;
}
}

11. Extend the RecommendedWeightWithTest program in Exercise 12


by
allowing the user to enter his or her weight and printing out the message
You
should exercise more if the weight is more than 10 lb over the ideal
weight
and You need more nourishment if the weight is more than 20 lb under
the
recommended weight.
Code:
import java.util.Scanner;

public class RecommendedWeightWithTest {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter your height in cm: ");


double height = scanner.nextDouble();

if (height >= 140 && height <= 230) {


double recommendedWeight =
calculateRecommendedWeight(height);
System.out.println("Your recommended weight is: " +
recommendedWeight + " kg");

System.out.print("Enter your weight in kg: ");


double weight = scanner.nextDouble();

double weightDifference = weight - recommendedWeight;

if (weightDifference > 10) {


System.out.println("You should exercise more.");
} else if (weightDifference < -20) {
System.out.println("You need more nourishment.");
}
} else {
System.out.println("Error: Height must be between 140cm and
230cm.");
}
}

public static double calculateRecommendedWeight(double height) {


return height - 100;
}
}
Level 2 Programming Exercises ★★
12. Write a program that replies either Leap Year or Not a Leap Year,
given a
year. It is a leap year if the year is divisible by 4 but not by 100 (for
example, 1796 is a leap year because it is divisible by 4 but not by 100).
A
year that is divisible by both 4 and 100 is a leap year if it is also divisible
by
400 (for example, 2000 is a leap year, but 1800 is not).

Code:
import java.util.Scanner;

public class LeapYearChecker {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = scanner.nextInt();
scanner.close();

if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {


System.out.println("Leap Year");
} else {
System.out.println("Not a Leap Year");
}
}
}

13. Employees at MyJava Lo-Fat Burgers earn the basic hourly wage of
$7.25.
They will receive time-and-a-half of their basic rate for overtime hours.
In addition, they will receive a commission on the sales they generate
while tending the counter. The commission is based on the following
formula:
Exercises 297
Sales Volume Commission
$1.00 to $99.99 5% of total sales
$100.00 to $299.99 10% of total sales
$300.00 15% of total sales
Write a program that inputs the number of hours worked and the total
sales
and computes the wage.

Code:
import java.util.Scanner;

public class WageCalculator {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input the number of hours worked


System.out.print("Enter the number of hours worked: ");
double hoursWorked = scanner.nextDouble();

// Input the total sales


System.out.print("Enter the total sales: $");
double totalSales = scanner.nextDouble();

scanner.close();

// Constants
double hourlyWage = 7.25;
double overtimeRate = 1.5;
double commissionRate;

// Calculate regular pay


double regularPay = hoursWorked <= 40 ? hoursWorked *
hourlyWage : 40 * hourlyWage;

// Calculate overtime pay


double overtimeHours = Math.max(hoursWorked - 40, 0);
double overtimePay = overtimeHours * hourlyWage *
overtimeRate;

// Calculate commission
if (totalSales >= 1 && totalSales < 100) {
commissionRate = 0.05;
} else if (totalSales >= 100 && totalSales < 300) {
commissionRate = 0.10;
} else {
commissionRate = 0.15;
}
double commission = totalSales * commissionRate;

// Calculate total wage


double totalWage = regularPay + overtimePay + commission;
// Print the total wage
System.out.println("Regular pay: $" + regularPay);
System.out.println("Overtime pay: $" + overtimePay);
System.out.println("Commission: $" + commission);
System.out.println("Total wage: $" + totalWage);
}
}

14. Using the DrawingBoard class, write a screensaver that displays a


scrolling
text message. The text messages moves across the window, starting from
the
right edge toward the left edge. Set the motion type to stationary, so the
DrawingBoard does not adjust the position. You have to adjust the text’s
position inside your DrawableShape.

Code:
import java.awt.*;

public class ScrollingTextScreensaver {


public static void main(String[] args) {
DrawingBoard board = new DrawingBoard(800, 200);
board.setMotionType(DrawingBoard.STATIONARY); // Set
motion type to stationary

// Define text message


String text = "Welcome to the Screensaver!";

// Set initial position


int x = board.getWidth();
int y = board.getHeight() / 2; // Center vertically

// Set font and color


board.setFont(new Font("Arial", Font.BOLD, 24));
board.setForegroundColor(Color.BLUE);
// Loop for animation
while (true) {
board.clear(); // Clear previous frame
board.drawText(text, x, y); // Draw text at current position
board.repaint(); // Repaint the board

// Adjust x position for scrolling effect


x -= 5; // Adjust speed here

// Reset x position when text goes off the screen


if (x + board.getStringWidth(text) < 0) {
x = board.getWidth();
}

try {
Thread.sleep(50); // Adjust speed here
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
15. Define a class called Triangle that is capable of computing the
perimeter and
area of a triangle, given its three sides a, b, and c, as shown below.
Notice
that side b is the base of the triangle.

The design of this class is identical to that for the Ch5Circle class from
Section 5.1. Define a private method isValid to check the validity of
three
sides. If any one of them is invalid, the methods getArea and
getPerimeter
will return the constant INVALID_DIMENSION

Code:
public class Triangle {
private double a;
private double b;
private double c;

public Triangle(double sideA, double sideB, double sideC) {


this.a = sideA;
this.b = sideB;
this.c = sideC;
}

public double getPerimeter() {


return a + b + c;
}

public double getArea() {


double s = getPerimeter() / 2;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}

public static void main(String[] args) {


// Example usage
double sideA = 5.0;
double sideB = 6.0;
double sideC = 7.0;

Triangle triangle = new Triangle(sideA, sideB, sideC);


System.out.println("Perimeter: " + triangle.getPerimeter());
System.out.println("Area: " + triangle.getArea());
}
}
.
Level 3 Programming Exercises ★★★
17. At the end of movie credits you see the year movies are produced in
Roman
numerals, for example, MCMXCVII for 1997. To help the production
staff
determine the correct Roman numeral for the production year, write a
program that reads a year and displays the year in Roman numerals.
Roman Numeral Number
I1
V5
X 10
L 50
C 100
D 500
M 1000
Remember that certain numbers are expressed by using a “subtraction,”
for
example, IV for 4, CD for 400, and so forth.
Code:
import java.util.Scanner;
public class YearToRomanNumeral {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the year: ");


int year = scanner.nextInt();

if (year < 1 || year > 3999) {


System.out.println("Year must be between 1 and 3999.");
} else {
String romanNumeral = convertToRomanNumeral(year);
System.out.println("Roman numeral representation: " +
romanNumeral);
}

scanner.close();
}

public static String convertToRomanNumeral(int year) {


int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
String[] symbols = {"M", "CM", "D", "CD", "C", "XC", "L", "XL",
"X", "IX", "V", "IV", "I"};
StringBuilder sb = new StringBuilder();

for (int i = 0; i < values.length; i++) {


while (year >= values[i]) {
year -= values[i];
sb.append(symbols[i]);
}
}

return sb.toString();
}
}

Development Exercises
18. MyJava Coffee Outlet (see Exercise 29 from Chap. 3) decided to
give
discounts to volume buyers. The discount is based on the following
table:
Exercises 299
Order Volume Discount
25 bags 5% of total price
50 bags 10% of total price
100 bags 15% of total price
150 bags 20% of total price
200 bags 25% of total price
300 bags 30% of total price
Each bag of beans costs $5.50. Write an application that accepts the
number
of bags ordered and prints out the total cost of the order in the following
style:
Number of Bags Ordered: 173 - $ 951.50
Discount:
20% - $ 190.30
Your total charge is: $ 761.20

Code:
import java.util.Scanner;

public class MyJavaCoffeeOutlet {


public static final double BAG_PRICE = 5.50;

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of bags ordered: ");


int numBags = scanner.nextInt();

double totalPrice = calculateTotalPrice(numBags);


double discount = calculateDiscount(totalPrice);
double finalPrice = totalPrice - discount;

System.out.println("Number of Bags Ordered: " + numBags + " -


$" + String.format("%.2f", totalPrice));
System.out.println("Discount:");
System.out.println(discountPercentage(numBags) + "% - $" +
String.format("%.2f", discount));
System.out.println("Your total charge is: $" + String.format("%.2f",
finalPrice));

scanner.close();
}

public static double calculateTotalPrice(int numBags) {


return numBags * BAG_PRICE;
}

public static double calculateDiscount(double totalPrice) {


double discount = 0;
if (totalPrice >= 300) {
discount = 0.3 * totalPrice;
} else if (totalPrice >= 200) {
discount = 0.25 * totalPrice;
} else if (totalPrice >= 150) {
discount = 0.2 * totalPrice;
} else if (totalPrice >= 100) {
discount = 0.15 * totalPrice;
} else if (totalPrice >= 50) {
discount = 0.1 * totalPrice;
} else if (totalPrice >= 25) {
discount = 0.05 * totalPrice;
}
return discount;
}

public static int discountPercentage(int numBags) {


if (numBags >= 300) {
return 30;
} else if (numBags >= 200) {
return 25;
} else if (numBags >= 150) {
return 20;
} else if (numBags >= 100) {
return 15;
} else if (numBags >= 50) {
return 10;
} else if (numBags >= 25) {
return 5;
} else {
return 0;
}
}
}
19. Combine Exercises 18 and 25 of Chap. 3 to compute the total charge
including discount and shipping costs. The output should look like the
following:
Number of Bags Ordered: 43 - $ 236.50
Discount:
5% - $ 11.83
Boxes Used:
1 Large - $1.80
2 Medium - $2.00
Your total charge is: $ 228.47
Note: The discount applies to the cost of beans only.
Code:
import java.util.Scanner;

public class MyJavaCoffeeOutlet {

public static final double BAG_PRICE = 5.50;


public static final double SHIPPING_LARGE_BOX = 1.80;
public static final double SHIPPING_MEDIUM_BOX = 2.00;

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of bags ordered: ");
int numBags = scanner.nextInt();

double totalPrice = calculateTotalPrice(numBags);


double discount = calculateDiscount(totalPrice);
double finalPrice = totalPrice - discount;
double shippingCost = calculateShippingCost(numBags);

System.out.println("Number of Bags Ordered: " + numBags + " -


$" + String.format("%.2f", totalPrice));
System.out.println("Discount:");
System.out.println(discountPercentage(numBags) + "% - $" +
String.format("%.2f", discount));
System.out.println("Boxes Used:");
System.out.println(calculateShippingBoxes(numBags));
System.out.println("Your total charge is: $" + String.format("%.2f",
(finalPrice + shippingCost)));

scanner.close();
}

public static double calculateTotalPrice(int numBags) {


return numBags * BAG_PRICE;
}
public static double calculateDiscount(double totalPrice) {
double discount = 0;
if (totalPrice >= 300) {
discount = 0.3 * totalPrice;
} else if (totalPrice >= 200) {
discount = 0.25 * totalPrice;
} else if (totalPrice >= 150) {
discount = 0.2 * totalPrice;
} else if (totalPrice >= 100) {
discount = 0.15 * totalPrice;
} else if (totalPrice >= 50) {
discount = 0.1 * totalPrice;
} else if (totalPrice >= 25) {
discount = 0.05 * totalPrice;
}
return discount;
}

public static int discountPercentage(int numBags) {


if (numBags >= 300) {
return 30;
} else if (numBags >= 200) {
return 25;
} else if (numBags >= 150) {
return 20;
} else if (numBags >= 100) {
return 15;
} else if (numBags >= 50) {
return 10;
} else if (numBags >= 25) {
return 5;
} else {
return 0;
}
}

public static String calculateShippingBoxes(int numBags) {


int largeBoxes = numBags / 20;
int remainingBags = numBags % 20;
int mediumBoxes = remainingBags / 10;

StringBuilder sb = new StringBuilder();


if (largeBoxes > 0) {
sb.append(largeBoxes + " Large - $" + String.format("%.2f",
largeBoxes * SHIPPING_LARGE_BOX) + "\n");
}
if (mediumBoxes > 0) {
sb.append(mediumBoxes + " Medium - $" +
String.format("%.2f", mediumBoxes * SHIPPING_MEDIUM_BOX) +
"\n");
}
return sb.toString();
}

public static double calculateShippingCost(int numBags) {


int largeBoxes = numBags / 20;
int remainingBags = numBags % 20;
int mediumBoxes = remainingBags / 10;

double shippingCost = (largeBoxes * SHIPPING_LARGE_BOX) +


(mediumBoxes * SHIPPING_MEDIUM_BOX);
return shippingCost;
}
}
20. You are hired by Expressimo Delivery Service to develop an
application
that computes the delivery charge. The company allows two types of
packaging—letter and box—and three types of service—Next Day
Priority, wu2330Next Day Standard, and 2-Day. for each additional for
each additional for each additional pound over the first pound over the
first pound over the firstpound. pound. pound.The program will input
three values from the user: type of package, type of
service, and weight of the package.
import java.util.Scanner;

public class ExpressimoDeliveryService {

// Constants for base rates and additional charges per pound


public static final double LETTER_BASE_RATE = 5.00;
public static final double LETTER_ADDITIONAL_CHARGE =
0.50;
public static final double BOX_BASE_RATE = 10.00;
public static final double BOX_ADDITIONAL_CHARGE = 1.00;

public static final double NEXT_DAY_PRIORITY_RATE = 20.00;


public static final double NEXT_DAY_STANDARD_RATE = 15.00;
public static final double TWO_DAY_RATE = 10.00;

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Input type of package


System.out.print("Enter type of package (Letter or Box): ");
String packageType = scanner.nextLine().toLowerCase();

// Input type of service


System.out.print("Enter type of service (Next Day Priority, Next
Day Standard, or 2-Day): ");
String serviceType = scanner.nextLine().toLowerCase();

// Input weight of the package


System.out.print("Enter weight of the package (in pounds): ");
double weight = scanner.nextDouble();
// Calculate delivery charge based on package type, service type,
and weight
double deliveryCharge = calculateDeliveryCharge(packageType,
serviceType, weight);

// Print the delivery charge


System.out.println("Delivery charge: $" + String.format("%.2f",
deliveryCharge));

scanner.close();
}

public static double calculateDeliveryCharge(String packageType,


String serviceType, double weight) {
double baseRate = 0;
double additionalChargePerPound = 0;

// Determine base rate and additional charge per pound based on


package type
if (packageType.equals("letter")) {
baseRate = LETTER_BASE_RATE;
additionalChargePerPound =
LETTER_ADDITIONAL_CHARGE;
} else if (packageType.equals("box")) {
baseRate = BOX_BASE_RATE;
additionalChargePerPound = BOX_ADDITIONAL_CHARGE;
} else {
System.out.println("Invalid package type.");
return 0;
}

// Calculate delivery charge based on service type and weight


double deliveryCharge = baseRate;
if (serviceType.equals("next day priority")) {
deliveryCharge += NEXT_DAY_PRIORITY_RATE;
} else if (serviceType.equals("next day standard")) {
deliveryCharge += NEXT_DAY_STANDARD_RATE;
} else if (serviceType.equals("2-day")) {
deliveryCharge += TWO_DAY_RATE;
} else {
System.out.println("Invalid service type.");
return 0;
}

// Calculate additional charge for weight


if (weight > 1) {
deliveryCharge += additionalChargePerPound * (weight - 1);
}
return deliveryCharge;
}
}

21. Ms. Latte’s Mopeds ‘R Us rents mopeds at Monterey Beach


Boardwalk. To
promote business during the slow weekdays, the store gives a huge
discount.

Code:
import java.util.Scanner;

public class MopedsRUs {

// Constants for rental charges and rates


public static final double MOPETTE_WEEKDAY_FIRST_3H =
15.00;
public static final double MOPETTE_WEEKDAY_RATE = 2.50;
public static final double MOPETTE_WEEKEND_FIRST_3H =
30.00;
public static final double MOPETTE_WEEKEND_RATE = 7.50;

public static final double MOHAWK_WEEKDAY_FIRST_3H =


25.00;
public static final double MOHAWK_WEEKDAY_RATE = 3.50;
public static final double MOHAWK_WEEKEND_FIRST_3H =
35.00;
public static final double MOHAWK_WEEKEND_RATE = 8.50;

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Input moped type


System.out.print("Enter moped type (50cc Mopette or 250cc
Mohawk): ");
String mopedType = scanner.nextLine().toLowerCase();

// Input rental duration (weekday or weekend)


System.out.print("Enter rental duration (Weekday or Weekend): ");
String rentalDuration = scanner.nextLine().toLowerCase();

// Input rental duration in hours


System.out.print("Enter rental duration in hours: ");
int rentalHours = scanner.nextInt();

// Calculate rental charge based on moped type, rental duration, and


rental hours
double rentalCharge = calculateRentalCharge(mopedType,
rentalDuration, rentalHours);

// Print the rental charge


System.out.println("Rental charge: $" + String.format("%.2f",
rentalCharge));

scanner.close();
}

public static double calculateRentalCharge(String mopedType, String


rentalDuration, int rentalHours) {
double rentalCharge = 0;

// Determine rental charge based on moped type and rental duration


if (mopedType.equals("50cc mopette")) {
if (rentalDuration.equals("weekday")) {
if (rentalHours <= 3) {
rentalCharge = MOPETTE_WEEKDAY_FIRST_3H;
} else {
rentalCharge = MOPETTE_WEEKDAY_FIRST_3H +
(MOPETTE_WEEKDAY_RATE * (rentalHours - 3));
}
} else if (rentalDuration.equals("weekend")) {
if (rentalHours <= 3) {
rentalCharge = MOPETTE_WEEKEND_FIRST_3H;
} else {
rentalCharge = MOPETTE_WEEKEND_FIRST_3H +
(MOPETTE_WEEKEND_RATE * (rentalHours - 3));
}
} else {
System.out.println("Invalid rental duration.");
}
} else if (mopedType.equals("250cc mohawk")) {
if (rentalDuration.equals("weekday")) {
if (rentalHours <= 3) {
rentalCharge = MOHAWK_WEEKDAY_FIRST_3H;
} else {
rentalCharge = MOHAWK_WEEKDAY_FIRST_3H +
(MOHAWK_WEEKDAY_RATE * (rentalHours - 3));
}
} else if (rentalDuration.equals("weekend")) {
if (rentalHours <= 3) {
rentalCharge = MOHAWK_WEEKEND_FIRST_3H;
} else {
rentalCharge = MOHAWK_WEEKEND_FIRST_3H +
(MOHAWK_WEEKEND_RATE * (rentalHours - 3));
}
} else {
System.out.println("Invalid rental duration.");
}
} else {
System.out.println("Invalid moped type.");
}

return rentalCharge;
}
}

24. After starting a successful coffee beans outlet business, MyJava


Coffee Outlet is now venturing into the fast-food business. The first
thing the management decides is to eliminate the drive-through
intercom. MyJava Lo-Fat Burgers is the only fast-food establishment in
town that provides a computer screen and mouse for its drive-through
customers. You are hired as a freelance computer consultant. Write a
program that lists items for three menu categories: entree, side dish, and
drink. The following table lists the items available for each entry and
their prices. Choose appropriate methodsfor input and output.
Entree Side Dish Drink
Tofu Burger $3.49 Rice Cracker $0.79 Cafe Mocha $1.99
Cajun Chicken $4.59 No-Salt Fries $0.69 Cafe Latte $1.99
Buffalo Wings $3.99 Zucchini $1.09 Espresso $2.49
Rainbow Fillet $2.99 Brown Rice $0.59 Oolong Tea $0.99
import java.util.Scanner;

public class MyJavaLoFatBurgers {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Print menu categories


System.out.println("Menu Categories:");
System.out.println("1. Entree");
System.out.println("2. Side Dish");
System.out.println("3. Drink");
// Prompt user to select items from each category
System.out.println("Select items from each category by entering the
corresponding number:");
System.out.print("Entree: ");
int entreeChoice = scanner.nextInt();
System.out.print("Side Dish: ");
int sideDishChoice = scanner.nextInt();
System.out.print("Drink: ");
int drinkChoice = scanner.nextInt();

// Calculate total price based on selected items


double totalPrice = calculateTotalPrice(entreeChoice,
sideDishChoice, drinkChoice);

// Display selected items and total price


System.out.println("\nSelected Items:");
System.out.println("Entree: " + getEntreeName(entreeChoice) + " -
$" + getEntreePrice(entreeChoice));
System.out.println("Side Dish: " +
getSideDishName(sideDishChoice) + " - $" +
getSideDishPrice(sideDishChoice));
System.out.println("Drink: " + getDrinkName(drinkChoice) + " - $"
+ getDrinkPrice(drinkChoice));
System.out.println("Total Price: $" + totalPrice);
scanner.close();
}

public static double calculateTotalPrice(int entreeChoice, int


sideDishChoice, int drinkChoice) {
double totalPrice = getEntreePrice(entreeChoice) +
getSideDishPrice(sideDishChoice) + getDrinkPrice(drinkChoice);
return totalPrice;
}

public static String getEntreeName(int choice) {


switch (choice) {
case 1:
return "Tofu Burger";
case 2:
return "Cajun Chicken";
case 3:
return "Buffalo Wings";
case 4:
return "Rainbow Fillet";
default:
return "Invalid choice";
}
}
public static double getEntreePrice(int choice) {
switch (choice) {
case 1:
return 3.49;
case 2:
return 4.59;
case 3:
return 3.99;
case 4:
return 2.99;
default:
return 0.00;
}
}

public static String getSideDishName(int choice) {


switch (choice) {
case 1:
return "Rice Cracker";
case 2:
return "No-Salt Fries";
case 3:
return "Zucchini";
case 4:
return "Brown Rice";
default:
return "Invalid choice";
}
}

public static double getSideDishPrice(int choice) {


switch (choice) {
case 1:
return 0.79;
case 2:
return 0.69;
case 3:
return 1.09;
case 4:
return 0.59;
default:
return 0.00;
}
}
public static String getDrinkName(int choice) {
switch (choice) {
case 1:
return "Cafe Mocha";
case 2:
return "Cafe Latte";
case 3:
return "Espresso";
case 4:
return "Oolong Tea";
default:
return "Invalid choice";
}
}

public static double getDrinkPrice(int choice) {


switch (choice) {
case 1:
return 1.99;
case 2:
return 1.99;
case 3:
return 2.49;
case 4:
return 0.99;
default:
return 0.00;
}
}
}
Chapter-6

6. Write a program to print out the numbers 10 through 49 in the


following
manner:
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49

How would you do it? Here is an example of poorly written code:


for (int i = 10; i < 50; i++) {
switch (i) {
case 19:
case 29:
case 39: System.out.println(" " + i); //move to the
break; //next line
default: System.out.print(" " + i);
}
}
This code is not good because it works only for printing 10 through 49.
Try
to develop the code so that it can be extended easily to handle any range
of
values. You can do this coding in two ways: with a nested for statement
or
with modulo arithmetic. (If you divide a number by 10 and the
remainder is
9, then the number is 9, 19, 29, or 39, and so forth.)

public class NumberPrinting {


public static void main(String[] args) {
int start = 10;
int end = 49;
int numbersPerLine = 10;

for (int i = start; i <= end; i++) {


System.out.print(i + " ");
if (i % numbersPerLine == numbersPerLine - 1) {
System.out.println(); // Move to the next line after printing
'numbersPerLine' numbers
}
}
}
}
7. A prime number is an integer greater than 1 and divisible by only
itself and
1. The first seven prime numbers are 2, 3, 5, 7, 11, 13, and 17. Write a
method that returns true if its parameter is a prime number. Using this
method, write a program that repeatedly asks the user for input and
displays
Prime if the input is a prime number and Not Prime, otherwise. Stop the
repetition when the input is a negative number

// Online Java Compiler


// Use this editor to write, compile and run your Java code online

import java.util.Scanner;

public class PrimeChecker {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

while (true) {
System.out.print("Enter a number (negative to exit): ");
int num = scanner.nextInt();

if (num < 0) {
System.out.println("Exiting...");
break;
}

if (isPrime(num)) {
System.out.println("Prime");
} else {
System.out.println("Not Prime");
}
}

scanner.close();
}

public static boolean isPrime(int num) {


if (num <= 1) {
return false;
}

for (int i = 2; i <= Math.sqrt(num); i++) {


if (num % i == 0) {
return false;
}
}

return true;
}
}

8. Complete the loan table program discussed in Section 6.8


import java.text.DecimalFormat;

public class LoanTableGenerator {


private static final int BEGIN_YEAR = 5;
private static final int END_YEAR = 30;
private static final int YEAR_INCR = 5;
private static final double BEGIN_RATE = 6.0;
private static final double END_RATE = 10.0;
private static final double RATE_INCR = 0.25;
private static final double LOAN_AMOUNT_MIN = 100.0;
private static final double LOAN_AMOUNT_MAX = 500000.0;
private static final DecimalFormat df = new DecimalFormat("#.##");

public static void main(String[] args) {


generateLoanTable();
}

private static void generateLoanTable() {


for (double rate = BEGIN_RATE; rate <= END_RATE; rate +=
RATE_INCR) {
System.out.println("\nInterest Rate: " + rate + "%");
System.out.println("Years\tMonthly Payment");

for (int year = BEGIN_YEAR; year <= END_YEAR; year +=


YEAR_INCR) {
double monthlyPayment = calculateMonthlyPayment(rate /
100, year);
System.out.println(year + "\t$" +
df.format(monthlyPayment));
}
}
}
private static double calculateMonthlyPayment(double rate, int years)
{
double principal = LOAN_AMOUNT_MAX;
int n = years * 12; // Convert years to months
double r = rate / 12; // Monthly interest rate
double numerator = principal * r;
double denominator = 1 - Math.pow(1 + r, -n);
return numerator / denominator;
}
}
11. Implement the describeRules method of the Ch6HiLo class from
Section 6.9.
At the beginning of the program, ask the user whether or not to display
the
game rules
import java.util.Random;
import java.util.Scanner;

public class HiLoGame {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();

// Display game rules


describeRules();

while (true) {
int targetNumber = random.nextInt(100) + 1;
int guessCount = 0;
boolean guessedCorrectly = false;

System.out.println("\nI'm thinking of a number between 1 and


100.");
System.out.println("Can you guess what it is?");

while (!guessedCorrectly && guessCount < 6) {


System.out.print("Enter your guess: ");
int guess = scanner.nextInt();
guessCount++;

if (guess < targetNumber) {


System.out.println("Too low! Try again.");
} else if (guess > targetNumber) {
System.out.println("Too high! Try again.");
} else {
System.out.println("Congratulations! You guessed the
number in " + guessCount + " guesses.");
guessedCorrectly = true;
}
}

if (!guessedCorrectly) {
System.out.println("Sorry, you didn't guess the number. The
correct number was: " + targetNumber);
}

System.out.print("\nDo you want to play again? (yes/no): ");


String playAgain = scanner.next().toLowerCase();
if (!playAgain.equals("yes")) {
System.out.println("Thanks for playing! Goodbye.");
break;
}
}

scanner.close();
}

public static void describeRules() {


System.out.println("Welcome to the HiLo game!");
System.out.println("Try to guess the secret number.");
System.out.println("You have 6 guesses to find it.");
System.out.println("After each guess, I'll tell you if your guess is
too high or too low.");
}
}

3. There are 25 primes between 2 and 100, and there are 1229 primes
between
2 and 10,000. Write a program that inputs a positive integer N 2 and
displays the number of primes between 2 and N (inclusive). Use the
timing
technique explained in Section 6.9 to show the amount of time it took to
compute the result
import java.util.Scanner;

public class PrimeCounter {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer N (N >= 2): ");
int N = scanner.nextInt();

if (N < 2) {
System.out.println("Please enter a positive integer greater than or
equal to 2.");
} else {
long startTime = System.nanoTime();
int primeCount = countPrimes(N);
long endTime = System.nanoTime();
double elapsedTimeInSeconds = (endTime - startTime) / 1e9;

System.out.println("Number of prime numbers between 2 and "


+ N + ": " + primeCount);
System.out.println("Time taken to compute: " +
elapsedTimeInSeconds + " seconds");
}
scanner.close();
}

public static int countPrimes(int N) {


int count = 0;
boolean[] isPrime = new boolean[N + 1];
for (int i = 2; i <= N; i++) {
isPrime[i] = true;
}

for (int p = 2; p * p <= N; p++) {


if (isPrime[p]) {
for (int i = p * p; i <= N; i += p) {
isPrime[i] = false;
}
}
}

for (int i = 2; i <= N; i++) {


if (isPrime[i]) {
count++;
}
}

return count;
}
}

14. Instead of actually computing the number of primes between 2 and


N,
we can get an estimate by using the Prime Number Theorem, which
states that

where prime(N) is the number of primes between 2 and N (inclusive).


The
function ln is the natural logarithm. Extend the program for Exercise 13
by
printing the estimate along with the actual number. You should notice the
pattern that the estimate approaches the actual number as the value of N
gets larger .

import java.util.Scanner;
public class PrimeCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer N (N >= 2): ");
int N = scanner.nextInt();

if (N < 2) {
System.out.println("Please enter a positive integer greater than or
equal to 2.");
} else {
long startTime = System.nanoTime();
int primeCount = countPrimes(N);
long endTime = System.nanoTime();
double elapsedTimeInSeconds = (endTime - startTime) / 1e9;

double estimate = primeEstimate(N);


System.out.println("Actual number of primes between 2 and " +
N + ": " + primeCount);
System.out.println("Estimate using Prime Number Theorem: " +
estimate);
System.out.println("Time taken to compute: " +
elapsedTimeInSeconds + " seconds");
}
scanner.close();
}

public static int countPrimes(int N) {


int count = 0;
boolean[] isPrime = new boolean[N + 1];
for (int i = 2; i <= N; i++) {
isPrime[i] = true;
}

for (int p = 2; p * p <= N; p++) {


if (isPrime[p]) {
for (int i = p * p; i <= N; i += p) {
isPrime[i] = false;
}
}
}

for (int i = 2; i <= N; i++) {


if (isPrime[i]) {
count++;
}
}
return count;
}

public static double primeEstimate(int N) {


return N / (Math.log(N));
}
}

15. A perfect number is a positive integer that is equal to the sum of its
proper
divisors. A proper divisor is a positive integer other than the number
itself
that divides the number evenly (i.e., no remainder). For example, 6 is a
perfect number because the sum of its proper divisors 1, 2, and 3 is equal
to 6. Eight is not a perfect number because 1 2 4 8 . Write a
program that accepts a positive integer and determines whether the
number
is perfect. Also, display all proper divisors of the number. Try a number
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class PerfectNumberChecker {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int number = scanner.nextInt();

if (number <= 0) {
System.out.println("Please enter a positive integer.");
} else {
boolean isPerfect = isPerfectNumber(number);
if (isPerfect) {
System.out.println(number + " is a perfect number.");
} else {
System.out.println(number + " is not a perfect number.");
}
System.out.println("Proper divisors of " + number + ": " +
findProperDivisors(number));
}

scanner.close();
}
public static boolean isPerfectNumber(int number) {
int sum = 0;
for (int i = 1; i < number; i++) {
if (number % i == 0) {
sum += i;
}
}
return sum == number;
}

public static List<Integer> findProperDivisors(int number) {


List<Integer> divisors = new ArrayList<>();
for (int i = 1; i < number; i++) {
if (number % i == 0) {
divisors.add(i);
}
}
return divisors;
}
}
16. Write a program that lists all perfect numbers between 6 and N, an
upper
limit entered by the user. After you verify the program with a small
number
for N, gradually increase the value for N and see how long the program
takes
to generate the perfect numbers. Since there are only a few perfect
numbers,
you might want to display the numbers that are not perfect so you can
easily
tell that the program is still running

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class PerfectNumberLister {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the upper limit (N): ");
int N = scanner.nextInt();
System.out.println("Perfect numbers between 6 and " + N + ":");
for (int i = 6; i <= N; i++) {
if (isPerfectNumber(i)) {
System.out.println(i + " is a perfect number.");
} else {
System.out.println(i + " is not a perfect number.");
}
}

scanner.close();
}

public static boolean isPerfectNumber(int number) {


int sum = 1;
for (int i = 2; i * i <= number; i++) {
if (number % i == 0) {
sum += i;
if (i != number / i) {
sum += number / i;
}
}
}
return sum == number;
}
}

17. Write a program that displays all integers between low and high that
are the
sum of the cube of their digits. In other words, find all numbers xyz such
that
xyz x3 y3 z3
, for example, 153 13 53 33
. Try 100 for low and
1000 for high.
public class CubeDigitSum {
public static void main(String[] args) {
int low = 100;
int high = 1000;
System.out.println("Integers between " + low + " and " + high + "
that are the sum of the cube of their digits:");
for (int num = low; num <= high; num++) {
if (isCubeDigitSum(num)) {
System.out.println(num);
}
}
}

public static boolean isCubeDigitSum(int number) {


int sumOfCubes = 0;
int originalNumber = number;

while (number > 0) {


int digit = number % 10;
sumOfCubes += digit * digit * digit;
number /= 10;
}

return sumOfCubes == originalNumber;


}
}
18. Write a method that returns the number of digits in an integer
argument; for
example, 23,498 has five digits. Using this method, write a program that
repeatedly asks for input and displays the number of digits the input
integer
has. Stop the repetition when the input value is negative

import java.util.Scanner;

public class DigitCounter {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

while (true) {
System.out.print("Enter an integer (negative to exit): ");
int input = scanner.nextInt();

if (input < 0) {
System.out.println("Exiting...");
break;
}

int digitCount = countDigits(input);


System.out.println("Number of digits: " + digitCount);
}

scanner.close();
}

public static int countDigits(int number) {


if (number == 0) {
return 1; // Special case: single digit number
}

int count = 0;
while (number != 0) {
count++;
number /= 10;
}
return count;
}
}

19. Your freelance work with MyJava Lo-Fat Burgers was a success (see
Exercise 24 of Chap. 5). The management loved your new drive-through
ordering system because the customer had to order an item from each of
the
three menu categories. As part of a public relations campaign, however,
management decided to allow a customer to skip a menu category.
Modify
the program to handle this option. Before you list items from each
category,
use a confirmation dialog to ask the customer whether he or she wants to
order an item from that category

import java.util.Scanner;

public class DriveThroughOrdering {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("Welcome to MyJava Lo-Fat Burgers!");

System.out.print("Do you want to order a burger? (yes/no): ");


String orderBurger = scanner.nextLine().toLowerCase();
if (orderBurger.equals("yes")) {
displayBurgerMenu();
}

System.out.print("Do you want to order a side? (yes/no): ");


String orderSide = scanner.nextLine().toLowerCase();
if (orderSide.equals("yes")) {
displaySideMenu();
}

System.out.print("Do you want to order a drink? (yes/no): ");


String orderDrink = scanner.nextLine().toLowerCase();
if (orderDrink.equals("yes")) {
displayDrinkMenu();
}
System.out.println("Thank you for ordering from MyJava Lo-Fat
Burgers! Enjoy your meal!");
scanner.close();
}

public static void displayBurgerMenu() {


System.out.println("Burger Menu:");
System.out.println("1. Veggie Burger - $4.99");
System.out.println("2. Chicken Burger - $5.99");
System.out.println("3. Beef Burger - $6.99");
}

public static void displaySideMenu() {


System.out.println("Side Menu:");
System.out.println("1. French Fries - $1.99");
System.out.println("2. Onion Rings - $2.49");
System.out.println("3. Side Salad - $2.99");
}

public static void displayDrinkMenu() {


System.out.println("Drink Menu:");
System.out.println("1. Soda - $1.49");
System.out.println("2. Iced Tea - $1.99");
System.out.println("3. Lemonade - $2.29");
}
}

20. Extend the program in Exercise 15 so that customers can order more
than
one item from each menu category. For example, the customer can buy
two
orders of Tofu Burgers and three orders of Buffalo Wings from the
Entree
menu category.
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class DriveThroughOrdering {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to MyJava Lo-Fat Burgers!");

Map<String, Integer> order = new HashMap<>();

System.out.print("Do you want to order a burger? (yes/no): ");


String orderBurger = scanner.nextLine().toLowerCase();
if (orderBurger.equals("yes")) {
order = getOrder("Burger", order, scanner);
}

System.out.print("Do you want to order a side? (yes/no): ");


String orderSide = scanner.nextLine().toLowerCase();
if (orderSide.equals("yes")) {
order = getOrder("Side", order, scanner);
}

System.out.print("Do you want to order a drink? (yes/no): ");


String orderDrink = scanner.nextLine().toLowerCase();
if (orderDrink.equals("yes")) {
order = getOrder("Drink", order, scanner);
}

System.out.println("\nYour order:");
for (Map.Entry<String, Integer> entry : order.entrySet()) {
System.out.println(entry.getValue() + " " + entry.getKey());
}

System.out.println("Thank you for ordering from MyJava Lo-Fat


Burgers! Enjoy your meal!");
scanner.close();
}

public static Map<String, Integer> getOrder(String category,


Map<String, Integer> order, Scanner scanner) {
System.out.println(category + " Menu:");
if (category.equals("Burger")) {
System.out.println("1. Veggie Burger - $4.99");
System.out.println("2. Chicken Burger - $5.99");
System.out.println("3. Beef Burger - $6.99");
} else if (category.equals("Side")) {
System.out.println("1. French Fries - $1.99");
System.out.println("2. Onion Rings - $2.49");
System.out.println("3. Side Salad - $2.99");
} else if (category.equals("Drink")) {
System.out.println("1. Soda - $1.49");
System.out.println("2. Iced Tea - $1.99");
System.out.println("3. Lemonade - $2.29");
}

System.out.print("Enter the number of items you want to order


from " + category + ": ");
int itemCount = scanner.nextInt();
scanner.nextLine(); // Consume newline

for (int i = 0; i < itemCount; i++) {


System.out.print("Enter the name of item " + (i + 1) + ": ");
String itemName = scanner.nextLine();

order.put(itemName, order.getOrDefault(itemName, 0) + 1);


}

return order;
}
}
21. A formula to compute the Nth Fibonacci number was given in
Exercise 10 in
Chapter 3. The formula is useful in finding a number in the sequence,
but a
more efficient way to output a series of numbers in the sequence is to
use the
recurrence relation FN FN1 FN2, with the first two numbers in the
sequence F1 and F2 both defined as 1. Using this recurrence relation, we
can
compute the first 10 Fibonacci numbers as follows:
F1 = 1
F2 = 1
F3 = F2 + F1 = 1 + 1 = 2
F4 = F3 + F2 = 2 + 1 = 3
F5 = F4 + F3 = 3 + 2 = 5
F6 = F5 + F4 = 5 + 3 = 8
F7 = F6 + F5 = 8 + 5 = 13
F8 = F7 + F6 = 13 + 8 = 21
F9 = F8 + F7 = 21 + 13 = 34
F10 = F9 + F8 = 34 + 21 = 55
Write a program that accepts N, N
1, from the user and displays the first N
numbers in the Fibonacci sequence. Use appropriate formatting to
display
the output cleanly

import java.util.Scanner;

public class FibonacciSeries {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of Fibonacci numbers to
display: ");
int N = scanner.nextInt();

System.out.println("The first " + N + " numbers in the Fibonacci


sequence:");

int[] fibonacci = new int[N];


fibonacci[0] = 1;
fibonacci[1] = 1;

for (int i = 2; i < N; i++) {


fibonacci[i] = fibonacci[i - 1] + fibonacci[i - 2];
}

for (int i = 0; i < N; i++) {


System.out.print(fibonacci[i] + " ");
}

scanner.close();
}
}
22. Modify the program of Exercise 21 to generate and display all the
numbers
in the sequence until a number becomes larger than the value
maxNumber
entered by the user.
import java.util.Scanner;

public class FibonacciSeries {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the maximum number in the Fibonacci


sequence: ");
int maxNumber = scanner.nextInt();

System.out.println("The Fibonacci sequence up to " + maxNumber


+ ":");

int f1 = 1;
int f2 = 1;
int fn = 0;

System.out.print(f1 + " " + f2 + " ");

while (true) {
fn = f1 + f2;
if (fn > maxNumber) {
break;
}
System.out.print(fn + " ");
f1 = f2;
f2 = fn;
}

scanner.close();
}
}

You might also like