Skip to content

Commit 825b9d5

Browse files
committed
New stuff from ch18 and exercise 17
1 parent a03f08d commit 825b9d5

File tree

16 files changed

+389
-7
lines changed

16 files changed

+389
-7
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import java.math.BigInteger;
2+
3+
/**
4+
* Recursive fibonacci method.
5+
*/
6+
public class FibonacciCalculator
7+
{
8+
private static BigInteger TWO = BigInteger.valueOf(2);
9+
10+
// recursive declaration of method fibonacci
11+
public static BigInteger fibonacci(BigInteger number)
12+
{
13+
if ( number.equals(BigInteger.ZERO) ||
14+
number.equals(BigInteger.ONE) ) // base cases
15+
return number;
16+
else // recursion step
17+
{
18+
return fibonacci(number.subtract(BigInteger.ONE)).add(fibonacci(number.subtract(TWO)));
19+
}
20+
} // end method fibonacci
21+
22+
// displays the fibonacci values from 0-40
23+
public static void main(String[] args)
24+
{
25+
for (int counter = 0; counter <= 40; counter++)
26+
{
27+
System.out.printf("Fibonacci of %d is: %d\n", counter,
28+
fibonacci(BigInteger.valueOf(counter)));
29+
} // end main
30+
} // end class FibonacciCalculator
31+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* Iterative factorial method.
3+
*/
4+
public class FactorialCalculator
5+
{
6+
// recursive declaration of method factorial
7+
public static long factorial(long number)
8+
{
9+
long result = 1;
10+
11+
// iterative declaration of method factorial
12+
for (long i = number; i >= 1; i--)
13+
{
14+
result *=i;
15+
}
16+
17+
return result;
18+
} // end method factorial
19+
20+
// output factorials for values 0-10
21+
public static void main(String[] args)
22+
{
23+
// calculate the factorials of 0 through 10
24+
for (int counter = 0; counter <= 10; counter++)
25+
System.out.printf("%d! = %d\n", counter, factorial(counter));
26+
}
27+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* Towers of Hanoi solution with a recursive method
3+
*/
4+
public class TowersOfHanoi
5+
{
6+
// recursively move disks between towers
7+
public static void solveTowers( int disks, int sourcePeg, int destinationPeg, int tempPeg)
8+
{
9+
// base case -- only one disk to move
10+
if (disks == 1)
11+
{
12+
System.out.printf("\n%d --> %d",sourcePeg, destinationPeg);
13+
return;
14+
} // end if
15+
16+
// recursion step -- move (disk - 1) disks from sourcePeg
17+
// to tempPeg using destinationPeg
18+
solveTowers(disks - 1, sourcePeg, tempPeg, destinationPeg);
19+
20+
// move last disk from sourcePeg to destinationPeg
21+
System.out.printf("\n%d --> %d", sourcePeg, destinationPeg);
22+
23+
// move (disks - 1) disks from tempPeg to destinationPeg
24+
solveTowers(disks - 1, tempPeg, destinationPeg, sourcePeg);
25+
} // end method solveTowers
26+
27+
public static void main(String[] args)
28+
{
29+
int startPeg = 1; // value 1 used to indicate startPeg in output
30+
int endPeg = 3; // value 3 used to indicate endPeg in output
31+
int tempPeg = 2; // value 2 used to indicate tempPeg in output
32+
int totalDisks = 3; // number of disks
33+
34+
// initial non recursive call: move all disks.
35+
solveTowers(totalDisks, startPeg, endPeg, tempPeg);
36+
}
37+
}

18.8 Fractals/18.8 Fractals.iml

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<module type="JAVA_MODULE" version="4">
3+
<component name="NewModuleRootManager" inherit-compiler-output="true">
4+
<exclude-output />
5+
<content url="file://$MODULE_DIR$">
6+
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
7+
</content>
8+
<orderEntry type="inheritedJdk" />
9+
<orderEntry type="sourceFolder" forTests="false" />
10+
</component>
11+
</module>

18.8 Fractals/src/Fractal.java

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
import javax.swing.*;
2+
import java.awt.*;
3+
import java.awt.event.ActionEvent;
4+
import java.awt.event.ActionListener;
5+
6+
/**
7+
* Fig. 18.18: Fractal.java
8+
* Fractal user interface
9+
*/
10+
11+
public class Fractal extends JFrame
12+
{
13+
private static final int WIDTH = 400; // define width of GUI
14+
private static final int HEIGHT = 480; // define height of GUI
15+
private static final int MIN_LEVEL = 0, MAX_LEVEL = 15;
16+
17+
private JButton changeColorJButton, increaseLevelJButton, decreaseLevelJButton;
18+
private JLabel levelJLabel;
19+
private FractalJPanel drawSpace;
20+
private JPanel mainJPanel, controlJPanel;
21+
22+
// set up GUI
23+
public Fractal()
24+
{
25+
super("Fractal");
26+
27+
// set up control panel
28+
controlJPanel = new JPanel();
29+
controlJPanel.setLayout(new FlowLayout());
30+
31+
// set up color button and register listener
32+
changeColorJButton = new JButton("Color");
33+
controlJPanel.add(changeColorJButton);
34+
changeColorJButton.addActionListener(
35+
new ActionListener() // anonymous listener
36+
{
37+
// process changeColorJButton event
38+
public void actionPerformed(ActionEvent event)
39+
{
40+
Color color = JColorChooser.showDialog(
41+
Fractal.this, "Choose a color", Color.BLUE);
42+
43+
// set default color, if no color is returned
44+
if (color == null)
45+
color = Color.BLUE;
46+
47+
drawSpace.setColor(color);
48+
} // end method actionPerformed
49+
} // end anonymous inner class
50+
); // end addActionListener
51+
52+
// set up decrease level button to add to control panel and
53+
// register listener
54+
decreaseLevelJButton = new JButton("Decrease Level");
55+
controlJPanel.add(decreaseLevelJButton);
56+
decreaseLevelJButton.addActionListener(
57+
new ActionListener() // anonymous inner class
58+
{
59+
public void actionPerformed(ActionEvent event)
60+
{
61+
int level = drawSpace.getLevel();
62+
--level; // decrease level by one
63+
64+
// modify level if possible
65+
if ((level >= MIN_LEVEL) && (level <= MAX_LEVEL))
66+
{
67+
levelJLabel.setText("Level: " + level );
68+
drawSpace.setLevel(level);
69+
repaint();
70+
} // end if
71+
} // end method actionPerformed
72+
} // end anonymous inner class
73+
); // end addActionListener
74+
75+
// set up increase level button to add to control panel
76+
// and register listener
77+
increaseLevelJButton = new JButton("Increase Level");
78+
controlJPanel.add(increaseLevelJButton);
79+
increaseLevelJButton.addActionListener(
80+
new ActionListener() // anonymous inner class
81+
{
82+
// process increaseLevelJButton event
83+
public void actionPerformed(ActionEvent event)
84+
{
85+
int level = drawSpace.getLevel();
86+
++level; // increase level by one
87+
88+
// modify level if possible
89+
if ( ( level >= MIN_LEVEL) && (level <= MAX_LEVEL ) )
90+
{
91+
levelJLabel.setText("Level: " + level );
92+
drawSpace.setLevel(level);
93+
repaint();
94+
} // end if
95+
} // end method actionPerformed
96+
} // end anonymous inner class
97+
); // end addActionListener
98+
99+
// set up levelJLabel to add to controlJPanel
100+
levelJLabel = new JLabel("Level: 0");
101+
controlJPanel.add(levelJLabel);
102+
103+
drawSpace = new FractalJPanel(0);
104+
105+
// create mainJPanel to contain controlJPanel and drawSpace
106+
mainJPanel = new JPanel();
107+
mainJPanel.add(controlJPanel);
108+
mainJPanel.add(drawSpace);
109+
110+
add(mainJPanel); // add JPanel to JFrame
111+
112+
setSize(WIDTH, HEIGHT); // set size of JFrame
113+
setVisible(true); // display JFrame
114+
} // end Fractal Constructor
115+
116+
public static void main(String[] args)
117+
{
118+
Fractal demo = new Fractal();
119+
demo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
120+
} // end main
121+
} // end class Fractal

18.8 Fractals/src/FractalPanel.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import javax.swing.*;
2+
import java.awt.*;
3+
4+
/**
5+
* Fig. 18.19: FractalJPanel.java
6+
* Drawing the "Lo fractal" using recursion.
7+
*/
8+
public class FractalPanel extends JPanel
9+
{
10+
private Color color; // stores color used to draw fractal
11+
private int level; // stores current level of fractal
12+
private static final int WIDTH = 400; // define width fo JPanel
13+
private static final int HEIGHT = 400; // defines height of JPanel
14+
15+
// set the initial fractal level to the value specified
16+
// and set up JPanel specifications
17+
public FractalPanel(int currentLevel)
18+
{
19+
color = Color.BLUE; // initialize drawing color to blue
20+
level = currentLevel; // set initial fractal level
21+
setBackground(Color.WHITE);
22+
setPreferredSize(new Dimension(WIDTH, HEIGHT));
23+
} // end FractalJPanel constructor
24+
25+
// draw fractal recursively
26+
public void drawFractal(int level, int xA, int yA, int xB, int yB, Graphics g)
27+
{
28+
// base case: draw a line connecting two given points
29+
if (level == 0)
30+
{
31+
32+
}
33+
}
34+
}

Exercise 17.2/Exercise 17.2.iml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
<component name="NewModuleRootManager" inherit-compiler-output="true">
44
<exclude-output />
55
<content url="file://$MODULE_DIR$">
6-
<sourceFolder url="file://$MODULE_DIR$" isTestSource="false" />
76
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
87
</content>
98
<orderEntry type="inheritedJdk" />

Exercise 17.2/src/AccountRecord.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,4 +72,11 @@ public double getBalance()
7272
{
7373
return balance;
7474
} // end method getBalance
75+
76+
// combine method that takes a TransactionRecord object and combines the balance of the AccountRecord object
77+
// and the amount value of the TransactionRecord object
78+
public void combine(TransactionRecord tr)
79+
{
80+
setBalance(getBalance() + tr.getAmount());
81+
}
7582
} // end class SequentialFile.AccountRecord

Exercise 17.2/src/ExerciseTest.java

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,10 @@ public class ExerciseTest
55
{
66
public static void main(String[] args)
77
{
8-
AccountReader application = new AccountReader();
9-
application.openOldMaster();
10-
//application.openNewMaster();
11-
application.outputNewMaster();
8+
FileMatch fileMatch = new FileMatch();
9+
fileMatch.openOldMaster();
10+
fileMatch.openTrans();
11+
fileMatch.processTrans();
12+
fileMatch.outputNewMaster();
1213
}
1314
}

Exercise 17.2/src/TestDataWriter.java

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
import java.io.FileNotFoundException;
2+
import java.util.Formatter;
3+
import java.util.FormatterClosedException;
4+
import java.util.NoSuchElementException;
5+
6+
/**
7+
* Created by P Trang on 9/6/2015.
8+
*/
9+
public class TestDataWriter
10+
{
11+
private Formatter oldMasterTestFile; // used to output text into oldmast.txt
12+
private Formatter transTestFile; // used to output text into trans.txt
13+
14+
public TestDataWriter()
15+
{
16+
oldMasterTestFile = null;
17+
transTestFile = null;
18+
}
19+
// create the two test files
20+
public void openFile()
21+
{
22+
try
23+
{
24+
oldMasterTestFile = new Formatter("C:\\Users\\P Trang\\git\\Deitel\\Deitel\\Exercise 17.2\\src\\oldmast.txt"); // open the oldmast.txt file
25+
transTestFile = new Formatter("C:\\Users\\P Trang\\git\\Deitel\\Deitel\\Exercise 17.2\\src\\trans.txt"); // open the trans.txt file
26+
}
27+
catch (FileNotFoundException fnfe)
28+
{
29+
System.err.println("Error opening or creating the file.");
30+
System.exit(1); // terminate the program
31+
} // end catch
32+
catch (SecurityException securityException)
33+
{
34+
System.err.println("You do not have write access to this file.");
35+
System.exit(1); // terminate the program
36+
} // end catch
37+
} // end method openFile
38+
39+
public void writeOldMaster()
40+
{
41+
try
42+
{
43+
oldMasterTestFile.format(
44+
"%d %s %s %.2f\n" +
45+
"%d %s %s %.2f\n" +
46+
"%d %s %s %.2f\n" +
47+
"%d %s %s %.2f\n",
48+
100, "Alan", "Jones", 348.17,
49+
300, "Mary", "Smith", 27.19,
50+
500, "Sam", "Sharp", 0.00,
51+
700, "Suzy", "Green", -14.22);
52+
}
53+
catch (FormatterClosedException fce)
54+
{
55+
System.err.println("Error writing to file.");
56+
}
57+
catch (NoSuchElementException elementException)
58+
{
59+
System.err.println("Invalid input.");
60+
} // end catch
61+
finally
62+
{
63+
oldMasterTestFile.close();
64+
}
65+
}
66+
public void writeTrans()
67+
{
68+
try
69+
{
70+
transTestFile.format(
71+
"%d %.2f\n" +
72+
"%d %.2f\n" +
73+
"%d %.2f\n",
74+
300, 83.89,
75+
700, 80.78,
76+
700, 1.53);
77+
}
78+
catch (FormatterClosedException fce)
79+
{
80+
System.err.println("Error writing to file.");
81+
}
82+
catch (NoSuchElementException elementException)
83+
{
84+
System.err.println("Invalid input.");
85+
} // end catch
86+
finally
87+
{
88+
transTestFile.close();
89+
}
90+
}
91+
}

0 commit comments

Comments
 (0)