Professional Documents
Culture Documents
Java Chap 2-6
Java Chap 2-6
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
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();
String[] monthNames = {
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
};
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;
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;
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;
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.*;
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.*;
Code:
import java.util.Scanner;
public class CMToFeetAndInches {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Output:
Code:
import java.util.Scanner;
public class CelsiusToFahrenheit {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Output:
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();
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);
Code:
import java.util.Scanner;
import java.time.LocalDate;
Code:
import java.util.Scanner;
public class BMIcalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
rate /= 100;
double amount = principal * Math.pow(1 + rate, years);
Code:
import java.util.Scanner;
public class SphereVolumeCalculator {
public static void main(String[] args) {
}
}
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 {
scanner.close();
}
Code:
import java.util.Scanner;
public class WeightCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
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);
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();
scanner.close();
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:
int prev = 1;
int curr = 1;
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;
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);
Code:
import java.util.Scanner;
public class CelsiusToFahrenheit {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Output:
Code:
import java.util.Scanner;
public class CalorieCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
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);
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;
Code:
import java.util.Scanner;
public class BMIcalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
rate /= 100;
double amount = principal * Math.pow(1 + rate, years);
}
}
Output:
Code:
import java.util.Scanner;
public class SatelliteVelocity {
scanner.close();
}
static double satelliteVelocity(double r) {
return Math.sqrt((G * ME) / r);
}
}
Output:
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);
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();
scanner.close();
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;
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");
Code:
import java.util.Random;
class java {
private int sides;
private Random random;
class RollDice {
public static void main(String[] args) {
java die = new java(6);
#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);
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);
scanner.close();
}
}
class Temperature {
private double temperature_fahrenheit;
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;
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();
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);
class Circle {
private double 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;
class Student {
private String 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;
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);
class Seat {
private String type;
private double 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;
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);
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;
}
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;
double totalPrice =
coffeeBag.computeTotalPrice(numberOfBagsSold, weightPerBag);
double totalPriceWithTax =
coffeeBag.computeTotalPriceWithTax(totalPrice);
class CoffeeBag {
public static final double PRICE_PER_POUND = 5.99;
public static final double TAX_RATE = 0.0725;
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;
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);
}
Code:
import java.util.Scanner;
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;
scanner.close();
// Constants
double hourlyWage = 7.25;
double overtimeRate = 1.5;
double commissionRate;
// 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;
Code:
import java.awt.*;
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;
scanner.close();
}
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;
scanner.close();
}
scanner.close();
}
scanner.close();
}
Code:
import java.util.Scanner;
scanner.close();
}
return rentalCharge;
}
}
import java.util.Scanner;
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();
}
return true;
}
}
while (true) {
int targetNumber = random.nextInt(100) + 1;
int guessCount = 0;
boolean guessedCorrectly = false;
if (!guessedCorrectly) {
System.out.println("Sorry, you didn't guess the number. The
correct number was: " + targetNumber);
}
scanner.close();
}
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;
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;
return count;
}
}
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;
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;
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;
}
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
scanner.close();
}
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);
}
}
}
import java.util.Scanner;
while (true) {
System.out.print("Enter an integer (negative to exit): ");
int input = scanner.nextInt();
if (input < 0) {
System.out.println("Exiting...");
break;
}
scanner.close();
}
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;
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;
System.out.println("\nYour order:");
for (Map.Entry<String, Integer> entry : order.entrySet()) {
System.out.println(entry.getValue() + " " + entry.getKey());
}
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;
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;
int f1 = 1;
int f2 = 1;
int fn = 0;
while (true) {
fn = f1 + f2;
if (fn > maxNumber) {
break;
}
System.out.print(fn + " ");
f1 = f2;
f2 = fn;
}
scanner.close();
}
}