Chapter 1 PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

CHAPTER 1

1.2
Fill in the blanks in each of the following sentences about the Java
environment:
a) The JAVA command from the JDK executes a Java application.
b) The JAVAC command from the JDK compiles a Java program.
c) A Java program file must end with the JAVA file extension.
d) When a Java program is compiled, the file produced by the
compiler ends with the CLASS file extension.
e) The file produced by the Java compiler contains BYTECODES
that are executed by the Java Virtual Machine.

1.7
Explain the two compilation phases of Java programs.
Phase one: Source Code is translated into bytecodes
Phase Two: During execution the bytecodes are translated into
machine language for the actual computer on which the program
executes.

CHAPTER 2
2.5
Write declarations, statements or comments that accomplish each of
the following tasks:
a) State that a program will calculate the product of three integers.
// calculate the product of three integers
b) Create a Scanner called input that reads values from the standard
input.
Scanner input = new Scanner (System.in);
c) Declare the variables x, y, z and result to be of type int.
int x, y, z, result;
int x;
int y;
int z;
int result;
d) Prompt the user to enter the first integer.
System.out.print( "Enter first integer: " );
e) Read the first integer from the user and store it in the variable x.
x = input.nextInt();
f) Prompt the user to enter the second integer.
System.out.print( "Enter second integer: " );
g) Read the second integer from the user and store it in the variable
y.
y = input.nextInt();
h) Prompt the user to enter the third integer.
System.out.print( "Enter third integer: " );
i) Read the third integer from the user and store it in the variable z.
z = input.nextInt();
j) Compute the product of the three integers contained in variables
x, y and z, and assign the result to the variable result.
result = x * y * z;
k) Display the message "Product is" followed by the value of the
variable result.
System.out.printf( "Product is %d\n", result );

2.25
(Odd or Even) Write an application that reads an integer and
determines and prints whether its odd or even. [Hint: Use the
remainder operator. An even number is a multiple of 2. Any
multiple of 2 leaves a remainder of 0 when divided by 2.]
*/

import java.util.Scanner;

public class Ex02_25 {


public static void main (String [] args) {

Scanner numbers = new Scanner (System.in);

int num;
int check;

System.out.print ("Enter A Number: ");


num = numbers.nextInt();
check = num%2;

if (check == 0)
System.out.printf ("\nThe Number %d is
EVEN.\n", num);
if (check != 0)
System.out.printf ("\nThe Number %d is
ODD.\n", num);

}
}
2.26
(Multiples) Write an application that reads two integers, determines
whether the first is a multiple of the second and prints the result.
[Hint: Use the remainder operator.]
import java.util.Scanner;

public class Ex02_26 {


public static void main (String [] args) {

Scanner numbers = new Scanner (System.in);

int num1;
int num2;
int check;

System.out.print ("Enter First Number: ");


num1 = numbers.nextInt();
System.out.print ("Enter Second Number: ");
num2 = numbers.nextInt();
check = num2%num1;

System.out.println ();

if (check == 0)
System.out.printf ("The Number %d is a
multiple of %d", num1, num2);
else
System.out.printf ("The Number %d is
not a multiple of %d", num1, num2);

}
}
CHAPTER 3
3.4
Explain the purpose of a method parameter. What is the difference
between a parameter and an argument?
A parameter represents additional information that a method
requires to perform its task. Each parameter required by a method is
specified in the methods declaration. An argument is the actual
value for a method parameter. When a method is called, the
argument values are passed to the corresponding parameters of the
method so that it can perform its task.
3.9
(Using a Class without Importing It) Explain how a program could
use class Scanner without importing it.
You could use the fully qualified name of the class instead of just
"Scanner".
java.util.Scanner s = new Scanner(System.in);
The only reason for using the "import" statement is so that you don't
have to use the fully qualified name for commonly used classes.
3.15
(Date Class) Create a class called Date that includes three instance
variablesa month (type int), a day (type int) and a year (type int).
Provide a constructor that initializes the three instance variables and
assumes that the values provided are correct. Provide a set and a get
method for each instance variable. Provide a method displayDate
that displays the month, day and year separated by forward slashes
(/). Write a test application named DateTest that demonstrates class
Dates capabilities.
public class Date {
private int monthdate;
private int daydate;
private int yeardate;

public Date (int month, int day, int year) {


monthdate = month;
daydate = day;
yeardate = year;
}

public void setMonth (int month) {


monthdate = month;
}

public int getMonth() {


return monthdate;
}

public void setday (int day) {


daydate = day;
}

public int getDay() {


return daydate;
}

public void setYear (int year ) {


yeardate = year;
}

public int getYear() {


return yeardate;
}

public void displayDate () {


System.out.printf ("%d/%d/%d\n",
getMonth(), getDay(), getYear());
}
CHAPTER 4
4.5
Write a Java statement to accomplish each of the following tasks:
a) Declare variables sum and x to be of type int.
int sum;
int x;
b) Assign 1 to variable x.
x = 1;
c) Assign 0 to variable sum.
sum = 0;
d) Add variable x to variable sum, and assign the result to variable
sum.
sum += x; or sum = sum + x;
e) Print "The sum is: ", followed by the value of variable sum.
System.out.printf( "The sum is: %d\n", sum );
4.12
Describe the two ways in which control statements can be
combined.
Control statements can be attached (that is, stacked) to one
another by connecting the exit point of one to the entry point of the
next. Control statements also may be nested by placing one inside
another.
4.35
(Sides of a Triangle) Write an application that reads three nonzero
values entered by the user and determines and prints whether they
could represent the sides of a triangle.
import java.util.Scanner;

public class TriangleYN{

public static void main(String args[]) {


Scanner input = new Scanner(System.in);
double a;
double b;
double c;

System.out.print("Enter the size three sizes,


decimals acceptable, separated by space:");
a = input.nextDouble();
b = input.nextDouble();
c = input.nextDouble();

if((a+b) > c)
{
if((a+c) > b)
{
if((b+c) > a)
{
System.out.printf("A triangle
could measure %.2f%s, %.2f%s, by %.2f%s.", a, b,
c);
return;
}
}
}
System.out.printf("A triangle could not
measure %.2f%s, %.2f%s, by %.2f%s", a, b, c);
}
}
CHAPTER 5
5.3
(Write a Statement) Write a Java statement or a set of Java
statements to accomplish each of the following tasks:
a) Sum the odd integers between 1 and 99, using a for statement.
Assume that the integer variables sum and count have been
declared.
sum = 0;
for ( count = 1; count <= 99; count += 2 )
sum += count;
b) Calculate the value of 2.5 raised to the power of 3, using the pow
method.
double result = Math.pow( 2.5, 3 );
c) Print the integers from 1 to 20, using a while loop and the counter
variable i. Assume that the variable i has been declared, but not
initialized. Print only five integers per line.[Hint: Use the
calculation i % 5.When the value of this expression is 0, print a
newline character; otherwise, print a tab character. Assume that this
code is an application. Use the System.out.println() method to
output the newline character, and use the System.out.print( '\t' )
method to output the tab character.]
i = 1;
while ( i <= 20 )
{
System.out.print( i );
if ( i % 5 == 0 )
System.out.println();
else
System.out.print( '\t' );
++i;
}
d) Repeat part (c), using a for statement.
for ( i = 1; i <= 20; i++ )
{
System.out.print( i );
5.11
(Find the Smallest Value) Write an application that finds the
smallest of several integers. Assume that the first value read
specifies the number of values to input from the user.
Import.java.util.Scanner;
public class Smallest
{
private int values;
private int number;
private int smallest;
public void inputValues()
{
System.out.print( "Enter the
number of integer values to compare:
" );
Scanner input = new Scanner(
System.in );
values = input.nextInt();
for ( int i = 1; i <= values;
i++ )
{
System.out.printf( "Enter an
integer for value %d: ", i );
number = input.nextInt();
if ( i == 1 )
smallest = number;
else
if ( number < smallest )
smallest = number;
}
}
public void displaySmallest()
{
System.out.printf( "\nThe
smallest integer is %d\n\n", smallest
);
}
}
5.13
Factorials) Factorials are used frequently in probability problems.
The factorial of a positive integer n (written n! and pronounced n
factorial) is equal to the product of the positive integers from 1 to
n.Write an application that calculates the factorials of 1 through 20.
Use type long. Display the results in tabular format. What difficulty
might prevent you from calculating the factorial of 100?
import javax.swing.*;
public class Factorial {
// main method begins execution of Java program
public static void main( String args[] )
{
JTextArea outputArea = new JTextArea( 5, 10 );
String outputString = "X\tX!\n";
for ( int number = 1; number <= 5; number++ ) {
int factorial = 1;

for ( int smaller = 1; smaller <= number; smaller++ )


factorial *= smaller;

outputString += "\n" + number + "\t" + factorial;


}

outputArea.setText( outputString );
JOptionPane.showMessageDialog( null, outputArea,
"Factorial", JOptionPane.INFORMATION_MESSAGE );

System.exit( 0 );
}

} // end class Factorial

CHAPTER 6
6.6
Write a complete Java application to prompt the user for the double
radius of a sphere, and call method sphereVolume to calculate and
display the volume of the sphere. Use the following statement to
calculate the volume:
double volume = ( 4.0 / 3.0 ) * Math.PI * Math.pow( radius, 3 )
import java.util.Scanner;

public class Sphere


{
// obtain radius from user and display volume of sphere
public static void main( String[] args )
{
Scanner input = new Scanner( System.in );

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


double radius = input.nextDouble();

System.out.printf( "Volume is %f\n", sphereVolume( radius ) );


} // end method determineSphereVolume

// calculate and return sphere volume


public static double sphereVolume( double radius )
{
double volume = ( 4.0 / 3.0 ) * Math.PI * Math.pow( radius, 3 );
return volume;
} // end method sphereVolume
} // end class Sphere

6.23
(Find the Minimum) Write a method minimum3 that returns the
smallest of three floatingpoint numbers. Use the Math.min method
to implement minimum3. Incorporate the method into an application
that reads three values from the user, determines the smallest value
and displays the result.
import java.util.Scanner;
public class Min
{
// find the minimum of three numbers
public void findMinimum()
{
Scanner input = new Scanner( System.in );
double one; // first number
double two; // second number
double three; // third number
System.out.printf( "%s\n %s\n %s\n",
"Type the end-of-file indicator to terminate",
"On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
"On Windows type <ctrl> z then press Enter" );
System.out.print( "Or enter first number: " );
while ( input.hasNext() )
{
one = input.nextDouble();
/* Write code to get the remainder of the inputs and
convert them to double values */
/* Write code to display the minimum of the three floating-point
numbers */

System.out.printf( "\n%s\n %s\n %s\n",


"Type the end-of-file indicator to terminate",
"On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
"On Windows type <ctrl> z then press Enter" );
System.out.print( "Or enter first number: " );
} // end while
} // end method findMinimum

// determine the smallest of three numbers


/* write the header for the minimum3 method */
{
// determine the minimum value
return /* Write code to compute the minimum of the three numbers
using nested calls to Math.min */
} // end method minimum3
} // end class Min

6.32
(Distance Between Points) Write method distance to calculate the
distance between two points (x1, y1) and (x2, y2). All numbers and
return values should be of type double. Incorporate this method into
an application that enables the user to enter the coordinates of the
points.
import java.util.Scanner;

public class DistancePoints{


public void calculateDistance(){
Scanner input = new Scanner(System.in);
System.out.printf("%s\n %s\n %s\n");
System.out.print("Enter x-point #1: ");

while(input.hasNext()){
double x1 = input.nextDouble();
System.out.print("Enter y-point #1: ");
double y1 = input.nextDouble();
System.out.print("Enter x-point #2: ");
double x2 = input.nextDouble();
System.out.print("Enter y-point #2: ");
double y2 = input.nextDouble();
double distance = distance(x1, y1, x2, y2);
System.out.printf("The distance of both
points is %f\n\n, distance");

System.out.printf("%s\n %s\n %s\n");


System.out.print("Enter x-point #1: ");
}
}

public double distance(double x1, double y1,


double x2, double y2){
return Math.sqrt(Math.pow((x1-x2), 2) +
Math.pow((y1-y2), 2));
}
}

CHAPTER 7
7.3
Perform the following tasks for an array called fractions:
a) Declare a constant ARRAY_SIZE thats initialized to 10.
final int ARRAY_SIZE = 10;
b) Declare an arraywith ARRAY_SIZE elements of type double,
and initialize the elements to 0.
double[] fractions = new double[ ARRAY_SIZE ];
c) Refer to array element 4.
fractions[ 4 ]
d) Assign the value 1.667 to array element 9.
fractions[ 9 ] = 1.667;
e) Assign the value 3.333 to array element 6.
fractions[ 6 ] = 3.333;
f) Sum all the elements of the array, using a for statement. Declare
the integer variable x as a control variable for the loop.
double total = 0.0;
for ( int x = 0; x < fractions.length; x++ )
total += fractions[ x ];
7.11
Write statements that perform the following one-dimensional-array
operations:
a) Set the 10 elements of integer array counts to zero.
for ( i = 0; i <= 9; i++ )
counts[ i ] = 0;
b) Add one to each of the 15 elements of integer array bonus.
for ( i = 0; i <= 14; i++ )
++bonus[ i ];
c) Display the five values of integer array bestScores in column
format.
for ( i = 0; i <= 4; i++ ) {
printf( %d\n, bestScores[ i ] );
7.14
(Variable-Length Argument List) Write an application that
calculates the product of a series of integers that are passed to
method product using a variable-length argument list. Test your
method with several calls, each with a different number of
arguments.

// calculate average
public static double average( double... numbers )
{
double total = 0.0; // initialize total

// calculate total using the enhanced for


statement
for ( double d : numbers )
total += d;
return total / numbers.length;
} // end method average
public static void main( String args[] )
{
double d1 = 10.0;
double d2 = 20.0;
double d3 = 30.0;
double d4 = 40.0;

System.out.printf( "d1 = %.1f\nd2 = %.1f\nd3 =


%.1f\nd4 = %.1f\n\n",
d1, d2, d3, d4 );
System.out.printf( "Average of d1 and d2 is
%.1f\n",
average( d1, d2 ) );
System.out.printf( "Average of d1, d2 and d3 is
%.1f\n",
average( d1, d2, d3 ) );
System.out.printf( "Average of d1, d2, d3 and d4
is %.1f\n",
average( d1, d2, d3, d4 ) );
} // end main
} // end class VarargsTest

You might also like