The way we approach a problem can often help or hinder us in our ability to solve it. Choosing an appropriate representation for a problem is often the key to solving it.
In order to evaluate complex expressions, it is necessary to understand the precedence order and associativity of the operators involved. Parentheses can always be used to override an operator’s built-in precedence.
Java provides several types of integer data, including the 8-bit byte, 16-bit short, 32-bit int, and 64-bit long types. Unless otherwise specified, integer literals are represented as int data in a Java program.
Java provides two types of floating-point data, the 32-bit float type and the 64-bit double type. Unless otherwise specified, floating-point literals are represented as double data.
In general, if a data type uses n bits in its representation, then it can represent \(2^n\) different values.
The fact that Java’s primitive types are defined in terms of a specific number of bits is one way that Java promotes platform independence.
It is necessary to distinguish integer operations from floating-point operations even though the same symbols are used. For example, (7/2) is 3, while (7.0/2) is 3.0.
In revising a class that is used by other classes it is important to preserve as much of the class’s interface as possible.
In Java, character data are based on the Unicode character set, which provides \(2^{16}\) = 65,536 different character codes. To provide backward compatibility with the ASCII code, the first 128 characters are the ASCII coded characters.
Java operators are evaluated according to the precedence hierarchy shown in the table below. The lower the precedence number, the earlier an operator is evaluated. So the operators at the top of the table are evaluated before operators that occur below them in the table. Operators at the same precedence level are evaluated according to their association, either left to right (L to R) or right to left (R to L).
Order
Operator
Operation
Association
0
( )
Parentheses
1
++ --
Postincrement, postdecrement
L to R
1
.
dot operator
L to R
2
++ --
Preincrement, predecrement
R to L
2
+ -
unary plus, unary minus
R to L
2
!
Boolean NOT
R to L
3
(type) new
Type cast, object instantiation
R to L
4
* / %
Multiplication, division, modulus
L to R
5
+ -
Addition, subtraction
L to R
5
+
String concatenation
L to R
6
< > <= >=
Relational operators
L to R
7
== !=
Equality operators
L to R
8
^
Boolean XOR
L to R
9
&&
Boolean AND
L to R
10
||
Boolean OR
L to R
11
= += -= *= /= %=
assignment operators
R to L
Solutions5.12.3Solutions to Self-Study Exercises
5.2Boolean Data and Operators 5.2.1Boolean (or Logical) Operations
Self-Study Exercises
5.2.1.1.&& Operator.
Solution.
true
5.2.1.2.|| Operator.
Solution.
true
5.2.1.3.! Operator.
Solution.
false
5.2.3Short-Circuit Evaluation
Self-Study Exercises
5.2.3.1.Expression 1.
Solution.
true
5.2.3.2.Expression 2.
Solution.
false
5.2.3.3.Expression 3.
Solution.
false
5.5Numeric Data and Operators 5.5.1Primitive Numeric Types
5.5.7.1.Evaluate Precedence with Increment Expressions.
Solution.
m = 5
m = 6
m = 15
m = 50
m = 70
5.7Numeric Processing Examples 5.7.2Example: Converting Fahrenheit to Celsius
Self-Study Exercises
5.7.2.1.TemperatureUI.
Solution.
public class TemperatureUI
{ private KeyboardReader reader; // Handles command line I/O
public TemperatureUI()
{ reader = new KeyboardReader(); // Create reader object
}
// Input-process-output algorithm to convert temperatures.
public void run()
{ reader.prompt("Converts Fahrenheit and Celsius.\n");
reader.prompt("Input a temperature in Fahrenheit > ");
double tempIn = reader.getKeyboardDouble();
double tempResult = Temperature.fahrToCels(tempIn);
reader.display(tempIn + " F = " + tempResult + " C\n");
reader.prompt("Input a temperature in Celsius > ");
tempIn = reader.getKeyboardDouble();
tempResult = Temperature.celsToFahr(tempIn);
reader.display(tempIn + " C = " + tempResult + " F\n ");
} // run()
public static void main(String args[])
{ TemperatureUI ui = new TemperatureUI(); // Create and
ui.run(); // run the user interface.
} // main()
} // TemperatureUI
5.7.2.2.Temperature GUI.
Solution.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
// Use this panel with a JApplet top-level window (as per Chapter 4)
public class TemperatureJPanel extends JPanel implements ActionListener
{ private JTextField inField = new JTextField(15); // GUI components
private JTextField resultField = new JTextField(15);
private JLabel prompt1 = new JLabel("Input Temperature >>");
private JLabel prompt2 = new JLabel("Conversion Result:");
private JButton celsToFahr = new JButton("C to F");
private JButton fahrToCels = new JButton("F to C");
private JPanel panelN = new JPanel(); // Panels
private JPanel panelC = new JPanel();
private JPanel panelS = new JPanel();
private Temperature temperature = new Temperature(); // Temperature object
public TemperatureJPanel() // Set up user interface
{ setLayout(new BorderLayout()); // Use BorderLayout
panelN.setLayout(new BorderLayout());
panelC.setLayout(new BorderLayout());
panelS.setLayout(new BorderLayout());
panelN.add("North", prompt1); // Input elements
panelN.add("South", inField);
panelC.add("West", celsToFahr); // Control buttons
panelC.add("East", fahrToCels);
panelS.add("North", prompt2); // Output elements
panelS.add("South", resultField);
add("North", panelN); // Input at the top
add("Center", panelC); // Buttons in the center
add("South", panelS); // Result at the bottom
celsToFahr.addActionListener(this); // Register with listeners
fahrToCels.addActionListener(this);
setSize(175,200);
} // TemperatureJPanel()
public void actionPerformed(ActionEvent e)
{ String inputStr = inField.getText(); // User's input
double userInput = Double.parseDouble(inputStr); // Convert to double
double result = 0;
if (e.getSource() == celsToFahr) { // Process and report
result = temperature.celsToFahr(userInput);
resultField.setText(inputStr + " C = " + result + " F");
} else {
result = temperature.fahrToCels(userInput);
resultField.setText(inputStr + " F = " + result + " C");
}
} // actionPerformed
} // TemperatureJPanel
5.7.3Example: Using Class Constants
Self-Study Exercises
5.7.3.1.OneRowNim with Constants.
Solution.
public static void main(String argv[])
{
OneRowNim game = new OneRowNim(MAX_STICKS);
while(game.gameOver() == false)
{
System.out.println(game.report());
int sticks = (int) (Math.random()*MAX_PICKUP) + 1;
System.out.println("Sticks picked up: " + sticks);
game.takeSticks(sticks);
} // while
System.out.println(game.report()); // The game is now over
System.out.print("Game won by player ");
System.out.println(game.getWinner());
} // main()
5.7.5Example: A Winning Algorithm for One Row Nim
Self-Study Exercises
5.7.5.1.NimPlayer.
Solution.
class NimPlayer
{ private OneRowNim nim;
public NimPlayer (OneRowNim game)
{ nim = game;
}
public int move()
{ int sticksLeft = nim.getSticks();
if (sticksLeft % (nim.MAX_PICKUP + 1) != 1)
return (sticksLeft - 1) % (nim.MAX_PICKUP +1);
else {
int maxPickup = Math.min(nim.MAX_PICKUP, sticksLeft);
return 1 + (int)(Math.random() * maxPickup);
}
}
} // NimPlayer
5.7.5.2.NimPlayer UI.
Solution.
public class KBComputerNim
{ public static void main(String argv[])
{
KeyboardReader kb = new KeyboardReader();
OneRowNim game = new OneRowNim(OneRowNim.MAX_STICKS);
NimPlayer computer = new NimPlayer(game);
System.out.println("Let's play One Row Nim");
while(game.gameOver() == false) {
if (game.getPlayer() == game.PLAYER_ONE)
{ kb.prompt("Sticks left = " + game.getSticks() +
" Your move. "); //Prompt
kb.prompt("You can pick up between 1 and " +
Math.min(game.MAX_PICKUP,game.getSticks()) +" :");
int sticks = kb.getKeyboardInteger(); // Get move
game.takeSticks(sticks); // Do move
} else
{ kb.prompt("Sticks left = " + game.getSticks() +
" My move. ");
int sticks = computer.move();
game.takeSticks(sticks);
System.out.println("I take " + sticks);
} // else
} // while
// The game is now over
kb.display("Sticks left = " + game.getSticks());
if (game.getWinner() == game.PLAYER_ONE)
System.out.println(" You win. Nice game!");
else
System.out.println(" I win. Nice game!");
} // main()
} // KBComputerNim
5.8From the Java Library java.text.NumberFormat
Self-Study Exercise
5.8.1.BankCD.
Solution.
public class BankCD
{ private double principal; // The CD's initial principal
private double rate; // CD's interest rate
private double years; // Number of years to maturity
public BankCD(double p, double r, double y)
{ principal = p;
rate = r;
years = y;
} // BandCD()
public double calcYearly()
{ return principal * Math.pow(1 + rate, years);
} // calcYearly()
public double calcDaily()
{ return principal * Math.pow(1 + rate/365, years*365);
} // calcDaily()
} // BankCD
5.8.2.BankCD UI.
Solution.
public class TestBankCD
{
private KeyboardReader reader = new KeyboardReader();
private NumberFormat dollars = NumberFormat.getCurrencyInstance();
private NumberFormat percent = NumberFormat.getPercentInstance();
private BankCD cd;
public void run()
{ reader.display("Compares daily and annual compounding for a CD.\n");
reader.prompt(" Input the CD's initial principal, e.g. 1000.55 > ");
double principal = reader.getKeyboardDouble();
reader.prompt(" Input the CD's interest rate, e.g. 6.5 > ");
double rate = reader.getKeyboardDouble() / 100.0;
reader.prompt(" Input the number of years to maturity, e.g., 10.5 > ");
double years = reader.getKeyboardDouble();
cd = new BankCD(principal, rate, years);
percent.setMaximumFractionDigits(2);
System.out.println("For Principal = " + dollars.format(principal) +
" Rate= " + percent.format(rate) +
" Years= " + years);
double cdAnnual = cd.calcYearly(); // Compounded yearly
double cdDaily = cd.calcDaily(); // Compounded annually
System.out.println(" The maturity value compounded yearly is " +
dollars.format(cdAnnual));
System.out.println(" The maturity value compounded daily is: " +
dollars.format(cdDaily));
} // run()
public static void main( String args[] )
{ TestBankCD cd = new TestBankCD();
cd.run();
} // main()
}// TestBankCD
5.9Character Data and Operators 5.9.1Character to Integer Conversions