Unit 0: Counting Systems

advertisement
AP Computer Science
Mr. Haytock
Unit 0: Counting Systems
Topics:
I. Introduction: definitions of computer science
II. Algorithms
III. Counting in binary
IV. Properties of binary
numbers
V. Binary arithmetic
VI. Octal and hexadecimal
systems
Materials:
I. Course Introduction
II. Pohl and Shaw chapter I
III. Pohl and Shaw ch. II
IV. Pohl and Shaw ch. III
V. Review Exercises
VI. Radix exercises #1
VII. Radix Conversion exercises #2
VIII. Radix Conversion exercises #3
IX. Challenge Questions
X. Project specifications
XI. Sample Driver Code
XII. Grading criteria
XIII. Review sheet and sample Free Response
XIV. ASCII table
1
AP Computer Science
Mr. Haytock (dhaytock@shadysideacademy.org)
Course Overview
Overview: This class is geared toward those students who have an interest in learning theoretical
concepts of computer science. Whereas the programming elective courses center on
teaching programming in Java, this course will strive toward using Java as a tool for
demonstrating computational concepts. The bulk of class time is spent on lecture and lab
work. While there is a Computer Science AP exam, students are not required to take it. The
general topics to be covered include:
 Computer logic fundamentals: binary math, Boolean algebra, computer languages
 Programming methodology: design, correctness, and refinement of methods and objects
 Algorithms: searching, sorting, recursion, analysis
 Data Structures: sets, lists, stacks, queues, graphs
Materials: The materials for the class are given as printed handouts. Students do not need to
purchase any software. Students will need their SSA user login—this is a required course
material. Students should bring to class every day: pen/pencil, paper, and notebook / binder.
Grading:
 Daily work: homework is usually given just a check or a zero (one point). Quizzes range
from one point (reading checks) to fifteen.
 Projects: 25 pts each. There will usually be 4 projects per term.
 Exams: 35 pts each. Usually there will be 2 exams per term.
Late Policies:
 Homework is always due at the beginning of the class period for which it is assigned. It
will not be accepted late (if you’re absent, get it to me when you return).
 Programming assignments will be accepted late up to one cycle (8 school days). There
is a penalty based on the number of (school) days late. After 8 days, I will not accept
it—if any project is not turned in, the student’s term grade will be an F, regardless of
other work completed.
 Tests can be made up if a student is absent, but be prompt (within one 8-day cycle).
Class Policies:
 Guiding principles: respect, responsibility, kindness, honesty, and safety
 Policies for responsible computing at SSA can be found in the student handbook.
 See the computer science department policy concerning plagiarism and academic fraud:
you are permitted to help others by asking meaningful questions, but are not permitted to copy
or give out your work
2
From: Pohl and Shaw, The Nature of Computation (Rockville, MD: 1981)
Chapter l:
COMPUTER SCIENCE
1.1 ORIGINS OF COMPUTER SCIENCE
Revolutionary advances in both science and engineering have changed the content and
methodology of almost all technical fields during the current century, including physics, biology,
medicine, electrical engineering, chemistry, transportation, communication, textiles, energy,
agriculture, and computing. Most of the advances and changes have been incorporated quite
naturally within traditional subject areas, and rarely has a major new discipline been created.
Computer science is one of these rarities.
While computer science is undoubtedly the youngest of the sciences, its origins can be traced
back many years. The most significant events of recent historical interest were the constructions
of the first digital computers during and immediately after World War II. In the sense that the
science of X is the study of X, computer science is devoted to the study of those devices called
computers; the field could not exist until the first machines were built in the 1940's. However,
hardware ideas about computers were expounded much earlier. The most prominent example is
the work of C. Babbage who derived the basic principles of computer organization and designed
a machine in the early 19th century.
Much of the theoretical foundations of computer science started with the research of A. Turing in
the 1930's. He developed a mathematical model of a universal computing device and proved
some remarkable properties of this abstract device. Turing's "machine" is still the accepted
theoretical model of a computer. In summary, the modern origins of the field are the construction
of the first computers and the independent formulation of an adequate mathematical model of
machines.
The subject was recognized as a separate academic discipline in the mid 1960's when computer
science departments were created at a number of universities in the U.S.A., and graduate
programs, usually leading to the Master of Science and Doctor of Philosophy degrees, were
introduced. In 1968, the Association for Computing Machinery, the largest professional
Computer Science and scientific organization of computer scientists, published a model
undergraduate curriculum; this became the basis for many college and university programs
throughout the world. It did not take long for computer science to become established, with all
the trappings of a traditional discipline such as many technical journals and conferences,
academic departments at most institutions of higher education, scientific and professional
associations, and thriving research laboratories in academia, industry, and government.
Why is computer science a separate major field? After all, a computer is just a grand calculating
device. Previous calculators, such as slide rules, were only considered as computing tools and
3
never seriously treated as a new basic area of knowledge. Other significant technical innovations
such as automobiles, television, and lasers have not led to separate disciplines; instead they just
became part of the existing fields of mechanical engineering, electrical engineering, and physics,
respectively. At one level, it is difficult to answer our question without assuming some
familiarity with this book. However, we can make two main points that should be
comprehensible now and can be profitably reread later.
Our first point is a technical one, dealing with the content of the field. Surprisingly, computers
are universal problem solving machines. Any procedure that is precisely formulated can be
implemented on a computer; such computational procedures are called algorithms. As a
consequence of this universality, the computer has permitted scientists to focus on all aspects of
technical problem solving. These include languages and notations for describing problems and
their solutions, the efficiency and optimality of various problem solving schemes, the classes of
computing devices required for different types of problems, the inherent complexity of specific
problems, the existence or non-existence of solutions to well-posed problems, and a host of other
related questions. Like mathematics, computer science provides the necessary tools for many
technical endeavors. Unlike mathematics and similar to engineering and the natural or social
sciences, computer science also has the very practical goals of understanding and applying real
world phenomena-those surrounding computers and algorithmic problem solving.
The second point that accounts for the creation of a computer science is social. The impact of
computers on society has been enormous but not well understood. It is evident that the computer
"revolution" is still in progress. The ultimate effects on our political, cultural, economic, and
moral lives are unpredictable, other than acknowledging that they will be substantial and
potentially range from very beneficial to very hazardous. Since much of our economy relies on
automatic information processing, there is a need for people who are technically trained in
computers. At a different level, it is recognized that a new computer ingredient has been
introduced in our societies, and that every well-educated person should have a basic
understanding of these machines and some of their implications.
1.2 ON DEFINING COMPUTER SCIENCE
The science of any subject is concerned with the accumulation and organization of information
about the subject and with the derivation and discovery of principles and methods. Most sciences
have a pure aspect that is devoted entirely to the expansion of knowledge for its own sake, and
an applied component that is oriented towards using this knowledge. The range covered by
computer science is very broad. At one end of the spectrum, we have theoretical, and sometimes
philosophical, investigations on the ultimate capabilities of machines and on the properties of
various general problems and algorithms; the more applied end deals with techniques for the
design and construction of computer systems, i.e. computer engineering, and with advanced
applications.
The computer scientist, in his applied role, has been characterized as a toolmaker. As such, he
develops methods and machines that others use in solving their problems. The theoretical
computer scientist, while also involved in toolmaking, studies the nature of the tool. In a natural
4
science, some part of the given natural or physical world is investigated. Computer science, by
contrast, is an artificial science since we are studying one of man's own creations. As a result, the
interest is not so much in observed facts and the discovery of laws, as it is in methods for the
analysis and design of these creations and the derivation of their properties.
Computer science has been defined in many different ways. Following are three definitions that
have been proposed.
1. Device-centered
This is the straightforward definition that was mentioned in the last section.
"Computer science is the study of computers."
Thus the science focuses on the device and on questions surrounding it, such as how to design,
analyze, construct, and use computers.
2. Information-centered
Information or data is considered the central notion here.
"Computer science is the study of information."
This leads to questions about the representation, storage, organization, transmission, and
processing of data.
3. Program-centered
A program is a set of computer instructions for solving a specific problem. Computer programs
are also referred to as software.
"Computer Science is the study of programming."
In this view, the emphasis is on programming issues such as appropriate languages for
expressing programs, the correctness and efficiency of programs, machines for executing
programs; and programming techniques.
All these definitions are "correct" in that most computer science topics are encompassed by any
of them. The first definition emphasizes real and abstract machines, the second the data that
machines work with, and the third the programs used to communicate with machines. Because
their emphases are different, they are subject to misinterpretation and can easily be construed as
too narrow or too broad.
What is desired is a definition that gracefully includes all of the above views without unduly
emphasizing any. The unifying notion of an algorithm, informally defined in the last section,
satisfies this requirement.
4. Algorithm-centered
"Computer science is the study of algorithms."
Computers are machines for implementing algorithms, information is the "stuff" that algorithms
manipulate and produce, and programming is the means for describing algorithms. The algorithm
concept also easily includes the theoretical parts of computer science.
Algorithms are the theme of this book and we shall see that all computer science questions can
be naturally formulated as questions about algorithms.
5
1.3 CORE TOPICS: TECHNICAL, APPLICATIONS, AND SOCIAL
The theory and practice of computer science covers technical, applications, and social issues.
The relations among these three aspects of the field are illustrated in Figure 1.1. Thus technical
advances lead to applications and social questions, and, in turn, the technical side of computing
is strongly influenced by applications and social pressures. Similarly, social problems feed back
to applications development and technical questions. While concerned primarily with scientific
or technical problems, the computer scientist must be aware of all three contexts of his work.
In this section, we introduce some of the main computer science topics in the above three areas.
A summary of the core topics is presented in Table 1.1. Our list should not be considered static
but one that is constantly expanding as the field progresses and new insights are made.
The technical component can be summarized as the design, implementation, analysis, and theory
of algorithms. A computer scientist attempts to answer some of the following questions:
1. What is an appropriate machine design for efficiently executing algorithms?
2. What is a good programming language for writing algorithms?
3. How can one design and implement good algorithms?
4. Is a particular algorithm correct for all possible cases?
5. How efficient is a particular algorithm?
6. What is the best possible algorithm for a given problem?
7. Does there exist an algorithm to solve a particular problem?
8. How does one define the syntax (form) and semantics (meaning) of a programming language?
Computer science research takes place within the framework of certain applications that are a
source of computing problems of general interest. Scientific computing, which deals with
algorithms for the numerical solution of mathematical equations, was the original application of
computers, with a history stretching far back to antiquity and the earliest calculating devices.
Another source of, usually numeric, algorithms is in problem solving by simulation; real world
predictions are attempted by creating and executing a computer model of the phenomenon being
studied. Investigations of nonnumeric algorithms, algorithms that manipulate symbols rather than
numbers, arise naturally in the fields of artificial intelligence and database systems. The goal of
artificial intelligence research is to produce computer systems that exhibit "intelligent" behavior;
this ambitious, and often controversial, goal has generated a rich set of problems in gameplaying, symbolic mathematics, theorem proving, and natural language understanding. The last
application in our list, database systems, refers to large information storage and retrieval
systems; examples are systems for libraries, airline reservations, automobile design, income tax,
credit, and banking.
At least four related social issues are direct and serious consequences of computer science
developments. The possibilities and implications of machine intelligence are the subject of
countless popular and scholarly discussions; these may stress, for example, the assault on man's
ego caused by intelligent machines, the benefits of a benevolent intellectual collaboration
6
between men and machines, or the horrors of being ruled by computers. As more and more tasks
become automated and delegated to computers, society must deal with the undesirable effects
such as possible widespread unemployment and the desirable aspects such as increased leisure
time. The existence of large database systems containing detailed personal data has already
caused great concern about the loss of privacy and potential for misuse; the prospects of "big
brother" keeping track of one's every movement and transaction appeal to few, yet these systems
also produce considerable economic and social benefits. The last issue stems from the increased
reliance on computer modelling for economic and social planning. Large computer models give
planning agencies much better information for intelligent decision-making. On the other hand,
some simulations and models are so complex that few understand the underlying assumptions in
the model and can interpret the results sensibly; the danger is that the computer output of such
models is accepted and used on faith alone.
The nuclear and biological sciences have painfully learned that science is not value free and that
the social implications of research directions and advances must be considered. Computer
science is also fundamentally tied to its societal context and the relationships between the science
and society cannot be ignored.
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
I. Review: Variables and Arithmetic Expressions
1 – 5. What is the result of the following expressions? Make sure to write the answer exactly
(i.e. use decimals when appropriate).
int n = 12, m = 5;
double d = 0.5;
1. n * m is
_________
2. n % m is
_________
3. n / (int) d is
_________
4. n * Math.round(d) is _________
5. Math.sqrt(m+4) is
_________
Given the following declarations, what is the output of the given statement?
int i1 = 3, i2 = 4, i3 = 5;
double d1 = -3.4, d2 = 4.8, d3 = 7.1;
6. System.out.print(i1 + i2 * i3);
7. System.out.print((int) d1 + d2);
8. System.out.print(Math.round(d1) + d2);
9. System.out.print((i1 – i2) * (i3 – i2) / (i2 – i1));
10.
System.out.print(i1 % i3);
11.
System.out.print(Math.round(-d3 + d1 * i1) / 4);
12.
i2 *= 3;
i3--;
System.out.print((i2 – i3) * (i2 + i3));
22
II. Review: Strings
1. What will be output when the program segment executes?
String s1 = “palindrome”;
String s2 = new String(“radar”);
String s3 = new String (“radar”);
if (s1.equals(s2))
System.out.print(“equals ”);
else System.out.print(“not equals ”);
if (s2.equals(s3))
System.out.print(“equals”);
else System.out.print(“not equals”);
a.
b.
c.
d.
e.
equals equals
equals not equals
not equals equals
not equals not equals
Some error message.
2 What string value is returned by the call question(“aardvark”)?
public static String question(String s)
{ // precondition: s is not null
String t = “”;
for (int k = 0; k < s.length(); k++)
t += s.charAt(k);
return t;
}
a. aardvark
b. varkaard
c. kkkkkkkk
d. kravdraa
e. None of the above.
3 - 5. Given the following expressions:
String s1 = new String(“problem solving”);
String s2 = new String(“java”);
String s3 = new String (“great work”);
a. s1.length() returns _______
b. s2. charAt(7) returns
_______
c. s3.compareTo(s2) returns _________________
23
III. Review: Classes and Objects:
For the next several questions, consider the following declarations:
public class Point2D
{
private double x, y;
public Point2D(double initX, double initY)
{
x = initX;
y = initY;
}
public double getX()
{
return x;
}
public double getY()
{
return y;
}
}
1. How many “points” are constructed in memory if the following statements are completed
(assume syntactical correctness)?
Point2D p1 = new Point2D(0.6, 0.75);
Point2D p2 = new Point2D(0.55, 0.22);
Point2D p3 = p1;
a. zero
b. one
c. two
d. three
2. Which of the following is a valid constructor statement?
a. Point2D p1 = new Point2D();
b. Point2D p2 = new Point2D(0.2);
c. Point2D p3 = new Point2D(0.65, 0.3);
d. None of the above are valid.
3. If p1 is correctly instantiated as a Point2D object, which of the following is an invalid
statement?
a. double n = p1.x;
b. double n = p1.getX();
c. double n = p1.getY();
d. All of the above are valid.
24
4. In a CyberAnimal class that represents the data and operations to be performed on a virtual
being, .getName() and .getEnergy() are examples of what type of method:
a. accessor
b. static
c. mutator
d. constructor
e. private
5. In a CyberAnimal class that represents the data and operations to be performed on a virtual
being, .play() and .feed() are examples of what type of method:
a. accessor
b. static
c. mutator
d. constructor
e. private
25
IV. Review: Arrays
1. Consider the following method.
public static int question(int n)
{
int temp[] = new int[n + 1];
temp[0] = 1;
temp [1] = 1;
for (int k = 2; k <= n; k++)
temp[k] = temp[k – 1] + temp[k – 2];
return temp[n];
}
What value is returned by the call question(10)?
a. 21
b. 34
c. 45
d. 55
e. 89
2. Consider the following method.
public static void question(int[] list)
{
int max = list.length – 1;
for (int k = 0; k < max; k++)
if (list[k] < list[k + 1])
{
int temp = list[k];
list[k] = list[k + 1];
list[k + 1] = temp;
}
}
Which statement describes the result of calling method question?
a. The smallest number is located in list [list.length-1].
b. The largest number is located in list [list.length-1].
c. The list array is sorted in ascending order.
d. The list array is sorted in descending order.
e. The elements in the list array are reversed.
26
3. Consider the following code segment.
int list[] = {5, 10, 15, 20, 25, 30, 35, 40, 45, 50};
int t = list[0];
for (int k = 0; k < list.length; k++)
list[k] = list[k] / t;
for (int k = 0; k < list.length; k++)
System.out.print(list[k] + “ “);
What will be output when the code segment executes?
a.
b.
c.
d.
e.
1 10 15 20 25 30 35 40 45 50
1 2 3 4 5 6 7 8 9 10
0000000000
1111111111
5 10 15 20 25 30 35 40 45 50
4 -5. Examine the following block of code:
double[] numbers = new double[6];
for (int j = 0; j < numbers.length; j++)
{
numbers[j] = j * 0.25;
}
int[] newNumbers = new int[6];
for(int j = 0; j < newNumbers.length; j++)
{
newNumbers [j] = (int)(numbers[j]+0.5);
}
After this code executes, what is the value of each of the following?
Indicate with “does not exist” answer if the expression cannot be evaluated.
a. numbers[3] is
________
b. newNumbers[3] is _________
27
Radix Conversion Exercises #1
1) What are the possible values of a bit?
2) How many bits are in a byte?
3) How many bytes are in a kilobyte?
Write each of these binary numbers in decimal.
1. 00010001
2. 00101001
3. 11010000
4. 01010101
Write each of these decimal numbers in binary.
1. 29
2. 66
3. 130
4. 200
Solve the addition formula.
1.
00001010
+ 00000111
3.
01001101
+ 00010010
2.
4.
00100100
+ 01110111
00101111
+ 11000101
1. How many numbers can be represented using 8 binary digits (“bits”)?
2. What is the largest number that can be represented using 8 binary digits?
28
Radix Conversion Exercises #2
Convert the decimal number to a binary number:
1. 49
2. 299
3. 311
4. 580
Convert each hexadecimal number to decimal:
a. 1A
b. FF
c. 41F
d. 10EC
e. 10000
Convert each decimal number to hexadecimal:
a. 23
b. 87
c. 115
d. 255
Octal is another commonly used numbering system, using eight symbols.
1. How is the number eight represented using octal?
2. How is the number sixty-four represented?
3. Convert these numbers from octal to decimal:
a. 77
b. 11
c. 111
d. 204
29
Radix Conversion Exercises #3
Compute the decimal value of each binary number:
a. 101
b. 1110
c. 110111
d. 1111111
Write each decimal number in binary
a. 23
b. 55
c. 85
d. 253
Convert the binary number to a hexadecimal number:
1. 000101011111
2. 101011001011
3. 1011010010001011
4. 1010101010101010
Convert the hexadecimal number to binary:
1. 18
2. A3
3. D9
4. C25
5. AF20
30
AP Computer Science
Mr. Haytock
Counting Systems Challenge Questions
1.
Simplify:
F16 + FF16 + … + FFFFFF16
2.
Solve for X2:
248 * X2 - AC16 = 1012 * X2 - 2358
3.
Solve for X16
3678 + 101112 = X16 – A1216
31
AP Computer Science
Mr. Haytock
Programming Assignment No. 0:
Radix Conversion
Specifications:
The binary number system is essential for computers, since computers can only compute using
thousands of tiny on-off switches. The hexadecimal and octal numbering systems are important
to computer scientists because they are easier to deal with than binary, but also easy to convert to
binary. For the ordinary human, however, we need to use the decimal, or base-ten, numbering
system. We’re going to become interpreters between the bizarre and twisted minds of computer
scientists and the outside world. We will write a Java program which will input a list of binary,
hexadecimal, or octal numbers and will change them into decimal.
Input: Your input will be in the form of two strings. The first will consist of a single character
representing the base. We will use ‘h’ for hexadecimal, ‘b’ for binary, and ‘o’ for octal, ‘q’ to
quit (all lower case). The second will be the list of digits representing the number. A few
sample input lines could be as follows:
h
b
b
o
h
o
o
b
h
q
A4
1010
1111
11
22
22
102
101
1F
Output: Your class must be able to produce the correct decimal version of the number given. For
instance, for the input given above, the output produced by a driver program would be:
Translating
Translating
Translating
Translating
Translating
Translating
Translating
Translating
Translating
quitting
the
the
the
the
the
the
the
the
the
hexadecimal number: A4 164
binary number: 1010 10
binary number: 1111 15
octal number: 11 9
hexadecimal number: 22 34
octal number: 22 18
octal number: 102 66
binary number: 101 5
hexadecimal number: 1F 31
Submission Format: Hand in to me a printout of your source code (the RadixConverter.java
file), and an electronic version with your source code file and a sample of your input and output
(screen captures or files). The project is due: _____________________. I’ll accept it up until 3
PM before I count it late. Be sure to document your work with appropriate and useful
comments!
32
Design:
You do not need to submit a formal design for your program, but you must follow good design
principles. Examine the provided sample code to get started. Your code must be properly
modularized for full credit. When using classes, look for constructor methods, mutator methods,
accessor methods, and over-ridden methods.
Implementation:
Your implementation of the code should be done on your own. You may consult the instructor
or textbooks if you get stuck or have questions. If you consult with other students, be sure that
you only do so in the form of asking / answering meaningful questions—you are not to copy
other students’ code.
The most critical part of your class is translating between bases in a character by character
stream. You may use either the “right-to-left” or “left-to-right” algorithm to accomplish this.
Here is a sample:
1. assign a temporary number (total) to be 0
2. loop from most significant digit to least:
a. if the radix is hexadecimal, you must change special characters into their
decimal value
b. for all other values, simply subtract 48 from the ASCII value to convert it to
decimal.
c. assign the temporary total its former value multiplied by radix plus the digit
3. Assign the decimal value of the converter (or return it).
Keep in mind that the symbols you read will not be of type integer but a string of characters. For
instance, if the octal number 16 is in our input file, we will read first the character ‘1’, then the
character ‘6’. It’s easy to change these into their actual decimal values, since we have the
ASCII chart. The character ‘0’ is represented by the number 48, ‘1’ is represented by the
number 49, and so forth. Subtracting 48 from each character will give us its actual decimal
value. E.g., to the computer, ‘1’ - 48 = 1. So in this instance, since we know that the octal
number will be 1*8 + 6*1, we can change the characters to decimal like so: (‘1’ - 48) * 8 + (‘6’ 48). Implicitly converting between character and integer data is called type coercion. If we use
a char space to hold ‘A’ (uppercase), the actual value that fills the space is 65 (or the binary
representation thereof).
Analysis, Testing, and Debugging
You must be sure to test your program before you hand it in. Start with correcting any syntax
errors. Compiler errors are sometimes difficult to find. I will help you if you get stuck, but not
before! Be sure that you check your textbook or some previous programs before asking for help.
Also, don’t assume that a program works simply because it compiles. Be sure to test all
possibilities! Run a “road test” (examining most normal situations) and a “crash test” (pushing
the limits of your program). With file I/O, you can write the input file once and run it multiple
33
times (whereas with console I/O, you must enter values each time you run it). The first step for
using an input file is to create the file. You can use any text editor to do this (be sure to save it as
text only). After you save and close the input file, you may use it again and again without
having to re-type it.
When you document your work, be analytical about both the process and the results. You must
answer the following questions:
- Did your program work as intended? Are there any circumstances that it does not work?
- What are its limitations? How did you come about solving the problem, and which parts
were challenging for you?
- What are the boundaries that represent integer overflow?
34
/*
Name:
Date:
Description:
*/
package radixconversion2014;
import cs.ssa.*;
public class RadixConversionProgram
{
static InFile myFile;
static OutFile outFile;
public static void main(String[] args)
{
char base;
myFile = new InFile("integers.txt");
outFile = new OutFile("integeroutput.txt");
displayWelcome();
do
{
base = (char)myFile.read();
outFile.print("Base: " + base);
if (base != 'q')
processLine(base);
}
while (base != 'q');
outFile.close();
inFile.close();
}
public static void displayWelcome()
/* */
{
}
public static void processLine(char base)
/* */
{
char input;
do
{
input = (char)(myFile.read());
outFile.print(input);
}
while (input != '\n');
outFile.println("EOL");
}
}
35
/*
IntegerConverterApplet.java
D. Haytock
Sept. 2014
This is a test program for the radix conversion class. The input
will will be given into the text fields. The base is followed by
a list of digits. Valid bases are 'b', 'o', and 'h'.
*/
package integersgui2014;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class IntegersGUI2014 extends JFrame implements ActionListener
{
private int WIDTH = 500;
private int HEIGHT = 300;
private JLabel message;
private JLabel digitPrompt;
private JLabel basePrompt;
private JButton convert;
private JTextField digitField;
private JTextField baseField;
private JPanel myPanel;
static public void main(String[] args)
{
new IntegersGUI2014();
}
public IntegersGUI2014()
// provide any actions to be performed when application is launched
{
super();
setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
convert = new JButton("Convert");
convert.addActionListener(this);
message = new JLabel("Welcome to the radix conversion program!");
digitPrompt = new JLabel("Enter digits: ");
basePrompt = new JLabel("Enter base ('b', 'o', 'h':) ");
digitField = new JTextField(20);
baseField = new JTextField(2);
Container contentPane = getContentPane();
myPanel = new JPanel();
contentPane.setBackground(Color.cyan);
contentPane.setLayout(new FlowLayout());
contentPane.add(convert);
contentPane.add(message);
myPanel.add(basePrompt);
myPanel.add(baseField);
myPanel.add(digitPrompt);
myPanel.add(digitField);
contentPane.add(myPanel);
setSize(WIDTH, HEIGHT);
36
}
public void actionPerformed(ActionEvent event)
// determines the action taken when the button is pressed
{
String label = "";
// use commands such as: baseField.getText());
label += "Converting from ";
label += baseField.getText()+ " ==> ";
message.setText(label);
}
}
37
Project Grading
To be acceptable, a programming project must be submitted on time and must be essentially
correct. Unacceptable projects receive 0 points. Acceptable projects are graded in five areas:
Correctness, Design, Efficiency, Documentation, and Style. Each item earns 0 . . 5 points
according to the criteria listed below.
Note that a late, but correct project often earns more points than an on-time, incorrect project.
For each school day late, you will lose 1/3 grade from your score (A+  A, A  A-, etc.). After
eight school days beyond the due date, I will not accept the project.
Correctness
Design
Efficiency
Documentation
Style
5. Solutions are correct according to the specifications
4. One or two minor problems (special cases or error conditions overlooked)
3. a number of minor problems
2. one major error (does not meet project specifications)
1. more than one major error
0. solution is not implemented
5. Solutions are constructed from small, reusable methods that naturally encapsulate one idea
4. one or two insufficiently justified violations (e.g. possible absorption)
3. several insufficiently justified violations
2. Poor structure in one area—method breaks are arbitrary or grossly long
1. Poor structure in more than one area
0. No object-oriented design used
5. Solutions are as efficient as possible in regards to both run-time and memory usage
4. one or two small inefficiencies (e.g. extra step or variable)
3. Several small inefficiencies
2. Major inefficiency in one area—double or more steps / memory taken
1. Major inefficiency in more than one area
0. Infinite loop or recursion
5. Solutions include problem descriptions, descriptive comments for each new method, and
concluding reflections.
4. Documentation in one or two areas is sparse or poorly done
3. Documentation in several areas is sparse or poorly done
2. Documentation is entirely missing in one area
1. Documentation is entirely missing in several areas
0. No documentation is included
5. Solutions and output are readable to the common programmer
4. One or two minor detractions, such as misaligned brackets or poorly chosen identifier
3. Several minor detractions
2. Difficult to read in one area: lack of indentations or linebreaks
1. Difficult to read in several areas
0. Unacceptable—poor readability.
Equivalent letter grades for a given program score are:
25
A+
24
A
23
A-
22
B+
21
B
20
B-
19
C+
38
18
C
17
C-
16
D+
15
D
14
D-
AP Computer Science
Mr. Haytock
Review Sheet for Test #0
I. Math: binary, hexadecimal, and octal conversions and operations
1. Convert from decimal to binary:
122
258
1023
2. Convert binary to decimal:
101110
1111011
100011111
3. Convert Hexadecimal to binary:
D9
8C1
EE0
4. Convert decimal to octal:
99
80
77
5. If you have n octal digits, what is the maximum number you can represent?
II. Programming: Study the concepts and details of the first project
III. Reading material: Review the following reading assignments
Handouts from Pohl and Shaw, chapters 1 – 3: Computer Science, Algorithms, Numbers
IV. Significant Terms:
Computer Science (include ways of
looking at it)
algorithm (include its characteristics)
bit / byte
radix positional notation
parity / parity bit
integer overflow
39
AP Computer Science
Practice Free Response
Counting
A. Part of the method for converting a decimal integer into binary involves finding the largest
power of two which is less than the given decimal number. Write a routine which finds the
largest power of 2 that is less than or equal to the given decimal number. For instance, for the
input number 17, the function will return 16. For the input number 86, the function will return
64. You may assume the preconditions are met. Write your answer in clear, correct java code.
Use the back side if necessary.
public int largestPower (int decimalNum)
/* PRE: DecimalNum is initialized to a positive integer number.
POST: The function will return the largest power of 2 which is less
than or equal to decimalNum.
*/
{
// your code goes here
B. Consider the Roman numbering system. What symbols are used to represent which numbers
(list as many as you know)? Write an algorithm that converts a string of Roman numerals to our
base-10 Arabic system. The following may serve as a method header:
public int toDecimal (String romanNum)
/* PRE: romanNum is initialized to a valid Roman numeral.
POST: The function will return the decimal equivalent.
*/
{
// your code goes here
40
ASCII Chart
41
Download