CIT 130* - 801, Beginning Java, Fall 2009

Instructor:  Brian Bourgon

Course Syllabus

 

Instructor Information:

   Phone: (702)651-4819

Fax:   (702)651-4561

E-Mail:  brian.bourgon@csn.edu

Office Hours: By Appointment

Office: Cheyenne Campus CY-2104D

 

Course Information:

 

Course Description: This course is an introduction to the Java programming language.  It includes the use of the Java programming language for problem formulation and solution, Java languageÕs control structures, applets, graphics, Swing components, and File I/O.  Object Oriented concepts and related material will be emphasized.

 

Course Content:

Course Goals:

  1.     To understand the activity of programming, learn about the architecture of computers, learn about machine code and high-level languages.  Become familiar with the computing environment, and recognize syntax and logic errors in programs.

2.     To understand the fundamentals of the Java programming language including Java syntax, keywords, variables, literals, primitive data types, constants, arithmetic and logical operators,  and Strings.  To understand the difference between integer and floating-point numbers and recognize the arithmetic expressions in Java, as well as manipulate String data as well as char data.

3.     Learn how to read program input, understand the copy behavior of primitive types and object references.  Learn to utilize the Java Application Program Interface (API) including the use of an Interactive Development Environment (IDE).

4.     To understand the concepts of classes and objects.  Realize the difference between objects and instances.  Understand the differences between classes, fields, and methods.  Understand the use of constructors.  Understand how to access instance fields and local variables.  Be able to pass values between objects and understand variable scope and the use of packages.  Learn about Overloading, Aggregation, Garbage Collection and Inheritance.

5.     To learn to appreciate the importance of documentation comments and good programming style.

6.     To be able to implement decisions using if-then-else statements, and understand how to group statements into blocks.  Learn how to compare integers, floating-point numbers, Strings, and objects.  Recognize the correct ordering of decisions in multiple branches, and to program conditions using Boolean operators and variables.

7.     To be able to program loops with do-while statements and for statements.  Avoid infinite loops and off-by-one errors, as well as understand nested loops.

8.     To understand the concepts and use of Arrays and other Data Structures for solving various algorithmic problems.

9.     To be able to handle unexpected program data through Exception Handling

10.  To be able to design and implement Graphical User Interfaces (GUIs) within Java programs including buttons, boxes, windows, check boxes, combo boxes, and labels.

  Course Outcomes:

  Upon completion of this course, the student will be able to:

1.     List the steps needed to write, compile, and run a Java program including a description of how the Java Virtual Machine is used in the process.  Define and explain the difference between logical and syntactical errors.  Design and code a program that processes user input and produces output.

2.     Develop algorithms in terms of pseudo codes and process flow charts and translate a pseudo code block into syntactically correct Java code.

3.     Explain the differences between classes, instances, fields, and methods.  Analyze a problem statement to determine a class that could be used to solve the problem that lists the classÕ responsibilities of attributes and methods.

4.     Design and code a program that uses basic arithmetic operations (assignment, addition, subtraction, multiplication, division, modulus, and increment/decrement).  This program will include the use of literals, primitive variable types, constants, and Strings.

5.     Design and code a program using comparison operations, decision structures like if and switch, both do-while and for loops.

6.     Design and code a program using arrays, implements methods to perform searching and sorting on arrays, and multi-dimensional arrays.

7.     Design and code a program using static class members, overloaded methods, and constructors.  Write programs that implement toString, equals, and copy methods.  Utilize the Java API in an IDE to identify and use predefined Java classes such as Math, String, and DecimalFormat.

8.     Design and code a program that illustrates GUI applications, including the use of dialog boxes, windows, layout managers, buttons, boxes, and borders.  Describe the differences between the Swing and AWT packages, and use each in a program.  Design and code a program that illustrates the use of event handlers and timer objects.

9.     Demonstrate good structured programming practices and object oriented design.

 

Prerequisites:

 IS 115 or Instructor Approval based on the ability of the student to program in a high level language.

  Required Textbook:

 Gaddis, Tony:  Starting out with Java:  Early Objects, 3rd Edition.  2008, Pearson Education, Inc.  ISBN 978-0-321-49768-0

  Required Software:

 Sun Java SDK Version 6 Update 11, available at http://java.sun.com/javase/downloads/index.jsp .

Note:  Configuring the JDK installation and configuring the disk access path is fairly straight forward, but may prove challenging for beginners.  Instructions will be provided in class, but make sure you give yourself plenty of time to set up your own computer so that you wonÕt fall behind with programs in class.

  Angel Site:

While all of the material necessary to successfully complete this class is available by attending the class and taking notes, there is an Angel online learning site by logging in at http://onlinecampus.csn.edu/default.asp .  This site includes helpful links to online resources to assist you in the class, useful examples for new or difficult concepts, and guides to help facilitate the setup and use of the SDK and IDE environments used in this class.

  Grading Scale:

 

Grade

Percentage

A

92.1% and above

A-

90% to 92%

B+

88.1% to 89.9%

B

82.1% to 88%

B-

80% to 82%

C+

78.1% to 79.9%

C

72.1% to 78%

C-

70% to 72%

D+

68.1% to 69.9%

D

62.1% to 68%

D-

60% to 62%

F

Under 60%

 

Grading Structure:

 

                  Mid Term Exam:                10%

                  Final Exam:                         20%

                  Homework:                         70%

 

Class Policy:

 Attendance is not required, but is recommended as ALL material covered in the Exams and Homework will come from the lecture material.  While most, if not all, of the material is also contained in the textbook, there may be occasional ideas covered in class that are not in the text.

 Assignments may be turned in via email, Angel, or on a portable USB drive, and are expected to be submitted on or before the due date by midnight.

 Make-up Exams and Assignments will be scheduled and/or accepted at the discretion of the instructor based on his schedule and on the ability to maintain the class pace.  It is the responsibility of each student to contact the instructor to get any missed work either before class, after class, via email, or a phone call.

 The best method for contacting the instructor is email.  While I welcome all phone calls, due to my busy day job schedule, I often get behind in returning voicemail, so if you do not reach me when calling, please send an email in addition to leaving a voicemail to ensure the quickest return of you message.  Additionally, if you let me know the best time to reach you, we will have the best success at keeping in contact with each other.

 The accompanying Course Schedule is only an estimate, and may be modified if facilitated by the pace of the class as a whole.  There should be no problem getting through all of the material in the schedule, and if in any single class session, all of the material intended to be covered is completed, class will end early.

 The use of cell phones and pagers in class is prohibited as they distract other students.  Please be respectful and put all communication devices on vibrate while in the classroom.  If you must take or make a phone call, please temporarily step outside of the classroom to do so.

  Policy on Cheating:

 Scholastic dishonesty will not be tolerated and will be prosecuted to the fullest extent of college policy. You are expected to have read and understood the current issue of the student handbook (published by Student Services) regarding student responsibilities and rights, and the intellectual property policy, for information about procedures and about what constitutes acceptable on-campus behavior.

 Students are expected to be above reproach in all scholastic activities.

 Students who engage in scholastic dishonesty are subject to disciplinary penalties, including the possibility of failure in the course and dismissal from CSN.

 Regents Rules and Regulations ,Part One, Chapter VI, Section 3, Subsection 3.2,Subdivision 3.22:

  Scholastic dishonesty includes but is not limited to cheating, plagiarism, collusion, and the submission for credit of any work or materials that are attributable in whole or in part to another person, taking an examination for another person, any act designed to give unfair advantage to a student or the attempt to commit such acts.

 Since scholastic dishonesty harms the individual, all students, and the integrity of CCSN, policies on scholastic dishonesty will be strictly enforced

 CSN Resources:

 Library:  The CSN Library has online resources that are available to all students enrolled in CSN courses including, but not limited to online journals and databases, manuals, books, interlibrary loan, digital reserves, dictionaries, encyclopedias, maps, and librarian expertise in research.

 Computer Labs:  24 hours after signing up for any class, but no sooner than two weeks before the semester, all students enrolled in CSN courses can validate an Active Directory account which give them access to free computer usage in the CSN computer labs located at each major campus and tech center.  See the CSN web page (http://www.csn.edu/pages/444.asp), at the labs themselves, or by calling the OTS Central Help desk at (702)651-4357 or (800)630-7563 24 hours a day.

 Technical Support:  If you are having trouble with any CSN computer or web based service including Active Directory accounts, online learning, online Library services, or Student Email you may get Technical Support by calling the OTS Central Help desk at (702)651-4357 or (800)630-7563 24 hours a day.

Disability Resource Center:  The College of Southern Nevada makes every effort to make its campuses fully accessible to students with disabilities. The college's Disability Resource Center offers accommodations to help students with documented disabilities with their academic pursuits. In addition, the DRC offers Disability Specialists and DHHS Coordinator to answer any questions or help solve any problems that may arise due to a documented disability. The office also offers adaptive equipment to those who qualify to ensure equal access to all CSN sponsored activities.  For more information, visit the CSN web page (http://www.csn.edu/pages/544.asp) or call at (702)651-4045.

Tutoring:  Students can receive up to four hours of free tutoring for each credit of class that they are enrolled.  These hours are only good for the semester enrolled in; you cannot carry them over to another semester.  Tutoring can only be used for courses in which the student is enrolled.  Unfortunately, there may be not be tutoring available for every course for which a student may be enrolled in.

 

--------------------------------------------------------------------------------------------------

Java CIT130

1.1 Why is the computer used by so many different people, in so many different profession ?

Because of versatility - They are programmable and so do what ever job the
programs or software tell them to do.

1.2 List the five major hardware components of a computer system.

The central processing unit
Main memory
Secondary memory
Input devices
Output devices

1.3 Internally, the CPU consists of what two units?

Control Unit and the Arithmetic and logic unit.

1.4 Describe the steps in the fetch/decode/execute cycle.

Fetch- The CPU's control unit fetchs, from main memory , the next instruction
in the sequence of program instructions.

Decode- The instruction is encoded in the form of a number. The control unit
decodes the instrucion and generates an electronic signal.

Execute- The signal is routed to the appropriate component of the computer
(such as the ALU, a disk drive, or some other device). The signal causes the
component to perform an operation.

1.5 What is a memory address? What is its purpose?

Like a post office box it routes information to a certain location.

1.6 Explain why computers have both main memory and secondary storage.

Main memory is temporary for a task, devices for long periods of time.

1.7 What does the tem "multitasking" mean?

Capable of running or running multiple programs at one time.

----------------------------------------------------------------------------------------------------

1.8 Describe the difference between a key word and a programmer- defined symbol.

Key words cannot be changed the are reserved and do only one function,
Programmer defined not part of the Java system.

1.9 Describe the difference between operators and punctutation symbols.

Operators do something, punctuation ends something.

1.10 Describe the difference between a program line and a statement.

A line is just that -format or placement, a statement is a complete instruction.
It may be one line, or spread out.

1.11 Why are variables called "variable"?

They may change value.

1.12 What happens to a variable's current contents what a new value is stored there?

It is replaced.

1.13 What is a compiler?

A compiler is a program that translates source code into an executable form.

1.14 What is a syntax error?

Mistakes that violate the rules of the proramming language.

1.15 What is byte code?

Not machine language but code that can be executed by the JVM.

1.16 What is the JVM?

Java Virtual Machine.

-----------------------------------------------------------------------------------------------------

1.17 What four items should you identify when defining what a program is to do?

Purpose, Input, Process, Output

1.18 What does it mean to "visualize a program running"? What is the value of such
an activity? Imagine what it looks like or does, the value is it let's you see from the
users veiwpoint.

1.19 What is pseudocode? Mid or intermediate step between English and computer code.

1.20 Describe what a compiler does with a program's source code.

Changes into an executable form, check for syntax errors.

1.21 What is a runtime error?

Errors that occur while program is running - ususally mathematical.

1.22 Is a syntax error (such as misspelling a key word) found by the compiler or
when the program is running? Compiler

1.23 What is the purpose of testing a program with sample data or input?

To see if the purpose has been met - does it do the job, solves the original problem.

-----------------------------------------------------------------------------------------------------

1.24 In prodecural programming, what two parts of a program are typically separted?

Data and procedures.

1.25 What are an object's attribute?

Data

1.26 What are an object's methods?

Behaviors or performed functions.

1.27 What is encapsulation? Combining data and code into a single object.

1.28 What is data hiding? Only the object may access the data directly, it's restricted.

PROGRAMMING CHALLENGE

// This is my first Java program.

public class MyFirstProgram
{ public static void main (String[]args)
{System.out.println("Hello World!");
}
}

 

Microsoft Windows [Version 6.0.6001]
Copyright (c) 2006 Microsoft Corporation. All rights reserved.

C:\Users\jessew>cd C:\Users\jessew\JesseWebPages\CSN

C:\Users\jessew\JesseWebPages\CSN> javac MyFirstProgram.java

C:\Users\jessew\JesseWebPages\CSN>java MyFirstProgram
Hello World!

 

-------------------------------------------------------------------------------------------------------

2.1 The following program will not compile because the lines have been mixed up.

public static void main (String[ ] args)
}
// A crazy mixed up program
public class Columbus
{
System.out.println("In 1492 Columbus sailed the ocean blue.");
{
}

When the lines are properly arranged the program should display the following on the screen:

In 1492 Columbus sailed the ocean blue.

Rearrange the lines in the correct order. Test the program by entering it on the computer,
compiling it, and running it.

// A crazy mixed up program

public class Columbus
{public static void main (String[ ] args)
{System.out.println("In 1492 Columbus sailed the ocean blue.");
}
}

C:\Users\jessew\JesseWebPages\CSN> javac Columbus.java

C:\Users\jessew\JesseWebPages\CSN>java Columbus
In 1492 Columbus sailed the ocean blue.

2.2 When the file in Question 2.1 is saved to a file, what should the file be named?

Columbus.java

2.3 Complete the following program skeleton so it displays the message " Hello World" on the screen.

public class Hello
{
public static void main (String[ ] args)
{

// Insert code here to complete the program

}
}

public class Hello
{
public static void main (String[ ] args)
{

System.out.println("Hello");

}
}

C:\Users\jessew\JesseWebPages\CSN>javac Hello.java

C:\Users\jessew\JesseWebPages\CSN>java Hello
Hello

2.4 On paper, write a program that will display your name on the screen. Place a comment with
today's date at the top of the program. Test your program by entering, compiling, and running it.

// Today's date

public class Jesse
{
public static void main (String[ ] args)
{

System.out.println("Jesse Wilkinson");

}
}

C:\Users\jessew\JesseWebPages\CSN>javac Jesse.java

C:\Users\jessew\JesseWebPages\CSN>java Jesse
Jesse Wilkinson

2.5 All java source code filenames must end with c. java

2.6 Every Java application program must have a) a method called main.

2.7 The following program will not compile because the lines have been mixed up.

System.out.print("Success\n");
}
public class Success
{
System.out.print ("Success\n");
public static void main (String[ ] args)
System.out.print("Success ");
}
// It's a mad, mad program.
System.out.println("\nSuccess");
{
When the lines are arranged properly the program should display the following output to '
the screen:

Program Output:
Success
Success Success

Success

Rearrange the lines in the correct order. Test the program by entering it on the computer,
compiling it, and running it.

// It's a mad, mad program.
public class Success
{ public static void main (String[ ] args)
{
System.out.print ("Success\n");
System.out.print("Success ");
System.out.print("Success\n");
System.out.println("\nSuccess");
}
}

C:\Users\jessew\JesseWebPages\CSN>javac Success.java

C:\Users\jessew\JesseWebPages\CSN>java Success
Success
Success Success

Success

2.8 Study the following program and show what it will print on the screen.

// The Works of Wolfgang
public class Wolfgang
{
public static void main(String[ ] args)
{ System.out.print(" The works of Wolfgang\ninclude ");
System.out.print("the following");
System.out.print("\nThe Turkish March ");
System.out.print("and Sympony No. 40 ");
System.out.println("in G minor.");
}
}

C:\Users\jessew\JesseWebPages\CSN>java Wolfgang
The works of Wolfgang
include the following
The Turkish March and Sympony No. 40 in G minor.

2.9 On paper, write a program that will display your name on the first line;
your street address on the second line; your city, state and ZIP code on the third line;
and your telephone on the fourth line. Place a comment with today's date at the top
of the program. Test your program by entering, compiling, and running it.

// Today's Date
public class JesseAddress
{
public static void main(String[ ] args)
{ System.out.println(" JesseWilkinson ");
System.out.println("5201 South Torrey Pines #1296");
System.out.println("Las Vegas, Nevada 89118");
System.out.println("702-257-8238");
}
}

C:\Users\jessew\JesseWebPages\CSN>javac JesseAddress.java

C:\Users\jessew\JesseWebPages\CSN>java JesseAddress
JesseWilkinson
5201 South Torrey Pines #1296
Las Vegas, Nevada 89118
702-257-8238

2.12 Which of the following are illegal variable names and why?

Yes x
No 99bottles - the first char is not a letter
Yes july97
Yes theSalesFigureForFiscalYear98
No r&d - & is no a letter,number,_ or $
Yes grade_report

2.13 Is the variable name Sales the same as sales? Why or why not?

No Case Sensitive

2.14 Refer to the Java primitive data types Listed in Table 2-5 for this question.

a) If a variable needs to hold whole numbers in the range 32 to 6,000, what primitive
data type would be best? short
b) If a variable needs to hold whole numbers in the range -40,000 to + 40,000.
What primitive data type would be best? int
c) Which of the following literals use more memory? 22.1 or 22.1F 22.1F

2.15 How would the number 6.31 X 10E17 be represented in E notation? 6.31E17

2.16 A program declares a float variable named number, and the following statement
causes an error. What can be done to fix the error?

number = 7.4; number =7.4F

2.17 What values can a boolean variables hold? True or False

2.18 Write statements that do the following:
a) Declare a char variable named letter. char letter
b) Assign the letter A to the letter variable. letter = A ;
c) Display the contents of the letter variable. System.out.println(letter);

2.19 What are the Unicode codes for the characters 'C', 'F', and 'W'?
(You may need to refer to Appendix B.)
C = 67, F= 70, W = 87

2.20 Which is a character literal, 'B' or "B"? 'B' Character literals are single quotes.

2.21 What is wrong with the following statement?

char letter = "Z"; Single quote.

2.22 Complete the following table by writing the value of each expression in the Value Column.

Expression Value
6+3*5 21
12/2 -4 2
9+14*2-6 31
5+19%3-1 5
(6+2)*3 24
14/ (11-4) 2
9+12*(8-3) 69

2.23 Is the division statement in the following code an example of integer division or
floating-point division? What value will be stored in portion?

double portion;
portion = 70/3;

Double 23.333333333333333

2.24 Write the statements using combined assignment operators to perform the following:

a) Add 6 to x x +=6;
b) Subtract 4 from amount amount -= 4;
c) Multiply y by 4 y *= 4;
d) Divide total by 27 total /=27;
e) Store in x the remainder of x divided by 7. x %= 7;

2.25 The following declaration appears in a program:

short totalPay, basePay = 500, bonus =1000;

The following statement appears in the same program:

totalPay = basePay + bonus;

a) Will the statement compile properly or cause an error?

// Checkpoint2.25
public class C225
{
public static void main(String[ ] args)

{ short totalPay, basePay = 500, bonus =1000;
totalPay = basePay + bonus;
System.out.println(totalPay);
}
}


C:\Users\jessew\JesseWebPages\CSN>javac C225.java
C225.java:7: possible loss of precision
found : int
required: short
totalPay = basePay + bonus;
^
1 error

b) If the statement causes an error, why? How can you fix it? Change short to int

// Checkpoint2.25
public class C225
{
public static void main(String[ ] args)

{ int totalPay, basePay = 500, bonus =1000;
totalPay = basePay + bonus;
System.out.println(totalPay);
}
}

2.26 The variable a is a float and the variable b is a double. Write a statement that will
assign the value of b to a without causing an error when the program is compiled.

// Checkpoint2.26
public class C226
{
public static void main(String[ ] args)

{ float a =500;
double b=600;
a=(float)b;
System.out.println("a="+a);
System.out.println("b="+b);
}
}

2.27 Write a statement that declares a String variable named city. The variable should be initialized so it references an object with the string "San Francisco".

2.28 Assume that stringLength is an int variable. Write a statement that stores the length of the string referenced by the city variable (declared in Checkpoint 2.27) in stringLength.

2.29 Assume that oneChar is a char variable. Write a statement that stores the first character in the string reference by the city variable (decleared in Checkpoint 2.27) in oneChar.

2.30 Assume the upperCity is a String reference variable. Write a statement that stores the uppercase equivalent of the string referenced by the city variable (declared in Checkpoint 2.27) in upperCity.

2.31 Assume that lowerCity is a String reference variable. Write a statement that stores the lowercase equivalent of the string referenced by the city variable (declared in Checkpoint 2.27) in lowerCity.

// Checkpoint2.27 - 2.31
public class C227
{
public static void main(String[ ] args)

{ String city = "San Francisco";
int stringLength; // Checkpoint C 2.28
char oneChar; // Checkpoint C 2.29
String upperCity; // Checkpoint C 2.30
String lowerCity; // Checkpoint C 2.30

stringLength =city.length( );
oneChar = city.charAt(0);
upperCity = city.toUpperCase( );
lowerCity = city.toLowerCase( );
System.out.println(city + " has " + stringLength + " Its first char is ="+ oneChar +" Upper Case =" +upperCity);
System.out.println(" Lower Case = " +lowerCity);

}
}

2.34 What is the purpose of the following types of dailog boxes?
Message dialog - Duh a message
Input dialog - Duh to get input.

2.35 Write Code that will display each of the dialog boxed shown in Figure 2-19.

import javax.swing.JOptionPane;

/** Checkpoint 2.35 Example of Message and Import

*/

public class C235

{ public static void main(String[ ] args)
{ JOptionPane.showMessageDialog(null, "Greetings Earthling");

//Get a number, even though it is a string.
JOptionPane.showInputDialog("Enter a number.");

}
}

2.36 Write code that displays an input dialog asking the user to enter his or her age. Convert the input value to an int and store it in an int variable named age.

import javax.swing.JOptionPane;

/** Checkpoint 2.36 Example of Message and Import

*/

public class C236

{ public static void main(String[ ] args)
{
String inputString; // for reading input

int age; //Get age, even though it is a string.

inputString=JOptionPane.showInputDialog("Enter your age.");

// Convert the input to an integer.

age=Integer.parseInt(inputString);

System.out.println("Your age is "+age);

}
}

2.37 What import statement do you write in a program that uses the JOptionPane class?
import javax.swing.JOptionPane;

 

-------------------------------------------------------------------------------------------------------

Programming Challenges

Ch. 2

2.1 Name, Age, and Annual Income

Write a program that declares the following:

a String variable named name

an int variable named age

a double variable named annualPay

Store your age, name, and desired annual income as literals in these variables.
The program should display these values on the screen in a manner similar to the following:

My name is Joe Mahoney, my age is 26 and I hope to earn $100000.0 per year.

// Program Challenge 2.1

public class PC21
{
public static void main(String[ ] args)

{ String name = "Jesse Wilkinson";
int age = 48;
double annualPay = 1000000;


System.out.println(" My name is " + name + ", my age is "+ age +" and " );
System.out.println(" I hope to earn $" +annualPay+" per year.");

}
}

2.2 Write a program that has the following String Variables: firstName, middleName, and lastName. Initialize these with your first,middle,

and last names. The program should also have the following char variables: firstInitial, middleInitial, and lastInitial. Store your first, middle

and last initials in these variables. The program should display the contents of these variables on the screen.

// Program Challenge 2.2

public class PC22
{
public static void main(String[ ] args)

{ String firstName = "Jesse", middleName = "John",lastName = "Wilkinson";
char firstInitial = 'J', middleInitial = 'J', lastInitial = 'W';


System.out.println(" My name is " + firstName + " "+middleName+" "+lastName );
System.out.println(" My initials are " +firstInitial+" " +middleInitial+" "+lastInitial);

}
}

2.3 Personal Information

Write a program that displays the following information, each on a seperate line:
Your name
Your address, with city, state and ZIP
Your telephone number
Your college major

Although these items should be displayed on separate output lines, use only a single println statement in your program.

// Program Challenge 2.3

public class PC23
{
public static void main(String[ ] args)

/** \n Newline Advances the cursor to the next line for subsequent printing p.42*/

{

System.out.println("Jesse John Wilkinson\n"+ "5201 SouthTorrey Pines, LV,NV, 89118\n"+"702-257-8238\n"+"Mathematics");


}
}

2.4 Star Pattern

Write a program that displays the following pattern:


*
***
*****
*******
*****
***
*

// Program Challenge 2.4

public class PC24
{
public static void main(String[ ] args)

/** \n Newline Advances the cursor to the next line for subsequent printing p.42*/

{

System.out.println(" *\n"+ " ***\n"+" *****\n"+"*******\n"+ " *****\n"+" ***\n"+" *\n");


}
}

2.5 Sum of Two Numbers

Write a program that stores the integers 62 and 99 in variables, and stores their sum in a variable named total.

// Program Challenge 2.5

public class PC25
{
public static void main(String[ ] args)

{
int a = 62, b=99;
int total = a+b;


System.out.println(" a= " + a+ "\n b= "+b +"\n Total a+b="+total);

}
}

2.6 Sales Prediction

The East Coast sales division of a company generates 62 percent of total sales. Based on that percentage, write a program that will predict

how much the East Coast division will generate if the company has $4.6 million in sales this year. Hint: Use the value of 0.62 to represent

62 percent.

// Program Challenge 2.6

public class PC26
{
public static void main(String[ ] args)

{
double a, totalSales, prediction; // East Coast percentage of Sales

a=0.62;
totalSales=4600000;
prediction=a*totalSales;

System.out.println( a+ "of Sales for next year of $"+totalSales +"\nEast Coast Prediction="+prediction);

}
}

2.7 Land Calculation

One acre of land is equivalent to 43,560 square feet. Write a program that calculates the number of acres in a tract of land with 389,767

square feet. Hint: Divide the size of the tract of land by the size of an acre to get the number of acres.

// Program Challenge 2.7

public class PC27
{
public static void main(String[ ] args)

{
double acreFeet, tractFeet, tractAcres; // Converting Feet to Acres

acreFeet=43560;
tractFeet=389767;
tractAcres=tractFeet/acreFeet;

System.out.println( tractFeet+ "square feet of land is "+tractAcres +" in Acres");

}
}

2.8 Sales Tax

Write a program that will ask the user to enter the amount of a purchase. The program should then compute the state and county sales tax.

Assume the state sales tas is 4 percent and the county sales tax is 2 percent. The program should display the amount of the purchase, the

state sales tax, the county sales tax, the total sales tax, the total of the sale ( which is the sum of the amount of purchase plus the total sales

tax.) Hint: Use the value 0.02 to represent 2 percent, and 0.04 to represent 4 percent.

import java.util.Scanner; // Needed for the Scanner class

// Program Challenge 2.8

public class PC28
{
public static void main(String[ ] args)

{
double purchaseAmount, stateSalesTax, countySalesTax,totalSalesTax, totalSale; //Assign variables

// Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);

// Get the Purchase Amount
System.out.print(" What is the Purchase Amount?");
purchaseAmount=keyboard.nextDouble( );

stateSalesTax=0.04*purchaseAmount;
countySalesTax=0.02*purchaseAmount;
totalSalesTax=stateSalesTax+countySalesTax;
totalSale=totalSalesTax+purchaseAmount;


System.out.println( " Purchase " + purchaseAmount);
System.out.println( " State Tax " + stateSalesTax);
System.out.println( " County Tax " + countySalesTax );
System.out.println( " Total Tax " + totalSalesTax +"\n_________");
System.out.println( " Total Sale " + totalSale);

}
}

2.9 Miles-per-Gallon

A car's miles-per gallon (MPG) can be calculated with the following formula:

MPG = Miles driven/ Gallons of gas used

Write a program that asks the user fro the number of miles driven and the gallons of gas used.
It should calcualte the car's MPG and dispaly the result on the screen.

import java.util.Scanner; // Needed for the Scanner class

// Program Challenge 2.9

public class PC29
{
public static void main(String[ ] args)

{
double milesDriven, gallonsUsed, mPG; //Assign variables

// Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);

// Get the Miles
System.out.print(" Number of miles Driven?");
milesDriven=keyboard.nextDouble( );

// Get the Gallons of Gas used
System.out.print(" Gallons of gas used ?");
gallonsUsed=keyboard.nextDouble( );

 

mPG=milesDriven/gallonsUsed;

System.out.println( " Miles Driven " + milesDriven);
System.out.println( " Gallons Used " + gallonsUsed +"\n_________");
System.out.println( " MPG " + mPG);

}
}

2.10 Write a program that asks the user to enter three test scores. The program should display each test score, as well as the average.

import java.util.Scanner; // Needed for the Scanner class

// Program Challenge 2.10

public class PC210
{
public static void main(String[ ] args)

{
double test1, test2, test3, testAvg; //Assign variables

// Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);

// Get test first score
System.out.print(" What was the first test score?");
test1=keyboard.nextDouble( );

// Get test first score
System.out.print(" What was the second test score?");
test2=keyboard.nextDouble( );

// Get test first score
System.out.print(" What was the third test score?");
test3=keyboard.nextDouble( );

testAvg=(test1+test2+test3)/3;

System.out.println( " Test Score1 " + test1);
System.out.println( " Test Score2 " + test2);
System.out.println( " Test Score3 " + test3 +"\n_________");
System.out.println( " Average Test Score " + testAvg);

}
}

2.11 Circuit Board Profit

An electronics company sells circuti boards at a 40 percent profit. If you know the retail price of a circuit board, you can calculate its profit

with the following formula:

Profit= Retail price X 0.4

Write a program that asks the user for the retail price of a circuit board, calculates the amount of profit earned for that product, and displays

the results on the screen.

import java.util.Scanner; // Needed for the Scanner class

// Program Challenge 2.11

public class PC211
{
public static void main(String[ ] args)

{
double retailPrice, profit; //Assign variables

// Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);

// Get the retail price
System.out.print(" What was the retail price?");
retailPrice=keyboard.nextDouble( );

profit=(retailPrice * 0.4);

System.out.println( " Retail price on this item " + retailPrice);
System.out.println( " Profit on this item " + profit +"\n_________");


}
}

2.12 String Manipulator

Write a program that asks the user to enter the name of his or her favorite city. Use a String variable to store the input. The program

should display the following:

The number of characters in the city name
The name of the city in all uppercase letters
The name of the city in all lowercase letters
The first character in the name of the city

import java.util.Scanner; // Needed for the Scanner class

// Program Challenge 2.12

public class PC212
{
public static void main(String[ ] args)

{
String city; //Assign variables

// Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);

// Get the favorite city
System.out.print("Enter the name of your favorite City.");
city=keyboard.nextLine( );

int stringSize = city.length( );
String upper= city.toUpperCase( );
String lower= city.toLowerCase( );
char letter = city.charAt(0);

System.out.println( " Your favorite City " + city);
System.out.println( " Number of Char " + stringSize);
System.out.println( " Uppercase " + upper);
System.out.println( " Lowercase " + lower);
System.out.println( " 1 st Character " + letter);

}
}

2.13 Word Game

Write a program that plays a word game with the user. The program should ask the ue to enter the following;

His or her name
His or her age
The name of a city
The name of a college
A profession
A type of animal
A pet's name

After the user has entered these items, the program should display the following story, inserting the user's input into the
appropriate locations:

There once was a person named NAME who lived in CITY. At the age of AGE, NAME went to college a COLLEGE. NAME graduated and

went to work as a PROFESSION. Then, NAME adopted a(n) ANIMAL named PETNAME. They both lived happily ever after!

import java.util.Scanner; // Needed for the Scanner class

// Program Challenge 2.13

public class PC213
{
public static void main(String[ ] args)

{
String name,age,city,college,profession,animal,petName; //Assign variables

// Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);

// Get name
System.out.print("Enter your name .");
name=keyboard.nextLine( );

// Get age
System.out.print("Enter your age .");
age=keyboard.nextLine( );

// Get city
System.out.print("Enter a City.");
city=keyboard.nextLine( );

// Get college
System.out.print("Enter a college .");
college=keyboard.nextLine( );

// Get profession
System.out.print("Enter a profession .");
profession=keyboard.nextLine( );

// Get animal
System.out.print("Enter an animal .");
animal=keyboard.nextLine( );

// Get pet's name
System.out.print("Enter an animal name .");
petName=keyboard.nextLine( );

System.out.println("There once was a person named "+name +" who lived in "+city+". ");
System.out.println("At the age of "+age+","+ name+" went to college a "+college+". ");
System.out.println(name+ " graduated and went to work as a "+profession+". " ); System.out.println("Then, "+name+ "

adopted a(n) "+animal +" named "+petName+". They both lived happily ever after! ");


}
}

2.14 Stock Transaction Program

Last month Joe purchased some stock in Acme Software, Inc. Here are the details of the purchase;

The number of shares that Joe purchased was 1,000.
When Joe purchsed the stock, the paid $32.87 per share.
Joe paid his stockbroker a commission that amounted to 2% of the amount he paid for the stock.

Two weeks later Joe sold the stock. Here are the details of the sale:
The number of shares that Joe sold was 1,000.
He sold the stock for $33.92 per share.
He paid his stockbroker another commission that amounted to 2% of the amount he received for the stock.

Write a program that displays the following information:

The amount of money Joe paid for the stock.
The amount of commission Joe paid his broker when he bought the stock.
The amount that Joe sold the stock for.
The amount of commission Joe paid his broker when he sold the stock.
Did Joe make money of lose money? Display the amount of profit or loss after Joe sold the stock and paid his broker (both times).

// Program Challenge 2.14

public class PC214
{
public static void main(String[ ] args)

{
double purShares,purPirce,purCost,purComm,soldShares,soldPrice, soldCommision; // StockBroker items

purShares=1000;
purPrice=32.87;
purCost=purShares*purPrice;
purComm=-purCost*.02;

soldShares=1000;
soldPrice=33.92;
soldCost=soldShares*soldPrice;
soldComm=-soldCost*.02;

System.out.println( purCost);
System.out.println( purComm);
System.out.println( soldCost);
System.out.println( soldComm +"\n___________");

}
}

Shares bought32870.0
Com to broker -657.4
Shares Sold 33920.0
Com to broker -678.4
___________
Profit or Loss-285.79999999999995

 

-------------------------------------------------------------


Java CIT130
Chapter 3 Checkpoints

3.1 In this chapter, we use the metaphor of a blueprint and houses that are createdfrom the blueprint to describe classes and objects.
In this metaphor, are classes the blueprint or the houses? The blueprints.

3.2 We also use the metaphor of a cookie cutter and cookies that are made from the cookie cutter to describe classes and objects.
In this metaphor, are objects the cookie cutter, or the cookies? The cookies.

3.3 When a variable is said to reference an object, what is actually stored in the variable? Data.

3.4 A string literal, such as "Joe", causes what type of object to be created ? String

3.5 Look at the UML diagram in Figure 3-15 and answer the following questions.

a) What is the name of the class? Car
b) What are the attribures? make, model
c) What are the methods? setMake,setYearModel, getMake, getYearModel
d) What are the private members? - negatives are private, so make and year Model
e) What are the public members? +'s are public.

Figure 3-15
_______________________
| Car |
|_______________________|
| - make |
| - year Model |
|_______________________|
| + setMake( ) |
| + setYearModel() |
| + getMake () |
| + getYearModel() |
|_______________________|

3.6 Assume that limo is a variable that references an instance of the class depicted in Figure 3-15.
Write a statement that calls setMake and passes the argument "Cadillac".

**************** Help, I'm confused by this one.

3.7 What does the key word new do? p121 creates an object in memory.

3.8 What is a parameter variable? input of a certain type - whatever the parameter says.

3.9 What is a accessor? What is a mutator? A method that gets a value form a class's field but does not change it is an accesor.
A method that stores a value in a field or in some other way changes the value of a field is a mutator.

3.10 What is a stale data item? Calculation left over from previous run.

------------------------------------------------------------------------------------------------------------------------

3.12 How is a constructor named? It has the same name as the class

3.13 What is a constructor's return type? It doesn't have one.

3.14 Assume that the following is a constructor, which appears in a class.

ClassAct(int number)
{
item=number;
}

a) What is the name of the class that this constructor appears in? ClassAct

b) Write a statement that creates an object from the class and passes the value 25 as an
argument to the constructor.

I'm still lost!!!!!!!!!!!!!!!!!!!!!!

------------------------------------------------------------------------------------------------------------------------

3.15 What is the problem domain? The set of real-world objects, parties, and major events related to the problem.

3.16 When designing an object-oriented application, who should write a description of the problem domain description?

If the problem is adequately understood {simple} by the programmer then they can, otherwise, you may need an expert.

3.17 How do you identify the potential classes in a problem domain description?

From the description, narrow down the nouns to those necessary to solve the problem.

3.18 What are a class's responsibilities? The things that the class is responsible for knowing, (attributes)
The things that the class is responsible for doing ( methods)

3.19 What two questions should you ask to determine a class's responsibilities?

What must the class know?
What must the class do?

3.20 Will all of a class's actions always be directly mentioned in the problem domain description?

No, it's iterative. The process should uncover what's needed.

---------------------------------------------------------------------------------------------------

Programming Challenges

Ch. 3

3.1 Employee Class

Write a class named Employee that has the following fields:

name. The name field is a String object that holds the employee's name.

idNumber. The idNumber is an int variable that holds the employee's ID number.

department. The department field is a String object that holds the name of the department where the employee works.

position. The position field is a String object that holds the employee's job title.

Write appropriate mutator methods that store values in these fields and accesor methods that return the values in these fields.
Once you have the written the class, write a separate program that creates three Employee objects to hold the following data.

 

Name ID Number Department Position
----------------------------------------------------------------------------------------------------------

Susan Marks 47899 Accounting Vice President

Mark Jones 39119 IT Programmer

Joy Rogers 81744 Manufacturing Engineer

The program should store this data in the three objects and then display the data for each employee on the screen.

------------------------------------

/**
* Employee Class
*
*/

public class Employee
{
private String name,department, position;
private double idNumber;

/**
* The setName method accepts an argument
* that is stored in the name field
*/

public void setName (String nam)
{
name = nam;
}

public void setidNumber (double id)
{
idNumber = id;
}
public void setDepartment (String dep)
{
department = dep;
}

public void setPosition (String pos)
{
position = pos;
}

 

/**
* The getName method accepts an argument
* that is stored in the name field
*/

public String getName ( )
{
return name;
}

public double getidNumber ( )
{
return idNumber;
}

public String getDepartment ( )
{
return department;
}

public String getPosition ( )
{
return position;
}

}

-------------------------------------------------------------

import java.util.*; // Needed for Scanner class

/**
* Demonstration of Employee Class
*
*/

public class EmployeeDemo
{
public static void main(String[ ] args)
{

String name, department,position;
double number;

// Create a Scanner object for keyboard input.

Scanner keyboard = new Scanner(System.in);

// Create a Employee object.
Employee emp1 = new Employee( );
Employee emp2 = new Employee( );
Employee emp3 = new Employee( );

/** Set the employee name.
emp1.setName("Susan Marks");
emp1.setidNumber(47899);
emp1.setDepartment("Accounting");
emp1.setPosition("Vice President");*/

//Get and store the attributes for Employee #1.

System.out.println("What is the Employee's name?");
name=keyboard.nextLine( );
emp1.setName(name);

System.out.println("What is the Employee's ID?");
number=keyboard.nextDouble( );
emp1.setidNumber(number);


position=keyboard.nextLine( );

System.out.println("What is the Employees Department?");
department=keyboard.nextLine( );
emp1.setDepartment(department);

System.out.println("What is the Employee's Position?");
position=keyboard.nextLine( );
emp1.setPosition(position);

emp2.setName("Mark Jones");
emp2.setidNumber(39119);
emp2.setDepartment("IT");
emp2.setPosition("Programmer");
emp3.setName("Joy Rogers");
emp3.setidNumber(81744);
emp3.setDepartment("Manufacturing");
emp3.setPosition("Engineer");





//

//Display the name, IDnumber, dept, position
System.out.println("\nName" +"\t\t\tId Number"+"\tDepartment"+ "\tPosition\n" );
System.out.println(emp1.getName( )+"\t\t"+emp1.getidNumber( )+"\t\t"+emp1.getDepartment( )+"\t"+emp1.getPosition( ) );
System.out.println(emp2.getName( )+"\t\t"+emp2.getidNumber( )+"\t\t"+emp2.getDepartment( )+"\t\t"+emp2.getPosition( ) );
System.out.println(emp3.getName( )+"\t\t"+emp3.getidNumber( )+"\t\t"+emp3.getDepartment( )+"\t"+emp3.getPosition( ) );
}
}

----------------------------------------------------------------------------------------------------

C:\Users\jessew\JesseWebPages\CSN>java EmployeeDemo
What is the Employee's name?
Susan Meyers
What is the Employee's ID?
47899
What is the Employees Department?
Accounting
What is the Employee's Position?
Vice President

Name Id Number Department Position

Susan Meyers 47899.0 Accounting Vice President
Mark Jones 39119.0 IT Programmer
Joy Rogers 81744.0 Manufacturing Engineer

 

--------------------------------------------------------------------------

Java CIT130
Chapter 4 Checkpoints

4.1 Write an if statment that assigns 0 to x when y is equal to 20.

if y=20
x=0;

4.2 Write an if statement that multiplies payRate by 1.5 if hours is greater than 40.

if (hours >40)
payRate = payrate*1.5;

4.3 Write an if statement that assigns 0.2 to commision if sales is greater than or
equal to 10000.

if (sales>= 10000)
commision = 0.2;

4.4 Write an if statement that set the variable fees to 50 if the boolean variable max is true.

if (max = true)
fees =50;

4.5 Write an if statement that assigns 20 to the variable y and assigns 1 to the variable
c if the variable x is greater that 100.

if (x >100)
{ y=20:
c=1; }

4.6 Write an if statement that assigns 0 to the variable b and assigns 1 to the variable
c if the variable a is less than 10.

if (a<10)
{ b =0;
c =1;}

4.7 Write an if statement that displays "Goodbye" if the variable myCharacter contains the character 'D'.

if (myCharacter =D)
System.out.println("Goodbye");

4.8 Write an if-else statement that assigns 20 to the variable y if the variable x is greater than 100.
Otherwise, it should assign 0 to the variable y.

if (x>100)
y=20;
else
y=0;

4.9 Write an if-else statement that assigns 1 to x when y is equal to 100. Otherwise it should assign 0 to x.

if (y==0)
x=1;
else
x=0;

4.10 Write an if-else statement that assigns 0.1 to commission unless sales is greater than or equal to 50000.0,
in which case it assigns 0.2 to commission.

if (Sales >= 50000.0)
commission = 0.1;
else
commission = 0.2;

4.11 Write an if-else statement that assigns 0 to the variable b and assigns 1 to the variable c if the variable a is less
than 10. Otherwise, it should assign -99 to the variable b and assign 0 to the variable c.

if (a < 10)
{ b =0;
c =1;}
else
{ b = -99;
c = 0;}

4.12 What will the following program display?

public class CheckPoint
{
public static void main (String [ ] args)

{
int funny = 7, serious = 15;

funny = serious % 2; // 15%2 = 1 so funny =1

if (funny !=1)
{ funny =0;
serious = 0;
}

else if (funny ==2)
{funny = 10;
serious = 10;
}
else
{
funny =1; // yes
serious = 1: // yes
}

System.out.println(funny + " " + serious);
}
}

4.13 The following program is used to determine how many discount coupons a customer gets.
Complete the table that appears after the program.

if (books <1 )
coupons = 0;
else if ( books < 3)
coupons = 1;
else if (books < 5)
coupons = 2;
else
coupons = 3;

If the customer purchases books this many coupons
1 1
2 1
3 2
4 2
5 3
10 3

4.14 Write nested if statements that perform the following test: If amount is greater than 10
and amount2 is less than 100, display the greater of the the two.

if (amount >10)

{ if (amount2 <100)
if (amount >amount2)
{ System.out.println( amount);
else
System.out.println( amount2);
}
else

System.out.println(" ");
}
else
System.out.println(" ");

4.15 Modify the program in Code Listing 4-7 so it also asks for yearly income. In addtion to
employed and recentGrad being 'y', the yearly income must be less than $25,000 to qualify for the loan.
( This will require another nested if statement.)

if (income < 25,000)

4.16 The following truth table shows various combinations of the values true and false connected by a logical
operator. Complete the table by indicating if the result of such a combination is true or false.

Logical Expression Result (true or false)
________________________________________

true && false false

true && true true

false && true false

false && false false

true || true true

true || true true

false || true false

false || false false

!true false

!false true

4.17 Assume the variables a =2, b=4, and c=6. Indicate by circling T or F if each of the following conditions is true or false.

a==4 || b>2 true

6 <= c && a >3 false

1 != b && c! =3 true

a >= -1 || a <=b true

! ( a >2) true

4.18 Write an if statement that prints the message " The number is valid " if the variable speed is within the range 0 through 200.

if ( speed >=0 && speed <= 200)
System.out.println("The number is valid");

4.19 Write an if statement that prints the message "The number is not valid" if the variable speed is outside the range of 0 through 200.

if ( speed <0 || speed > 200)
System.out.println("The number is not valid");

4.20 Assume the variable name references a String object. Write an if statement that displays " Do I know you?" if the string object
contains " Timothy".

if (name .equals("Timothy"))
System.out.println("Do I know you?");

4.21 Assume the variables name1 and name2 reference two different String objects, containing different strings. Write code that
displays the strings referenced by these variables in alphabetical order.

if (name1.compareToIgnoreCase(name2) < 0)
System.out.println(name1 +name2);
else
System.out.println(name2 + name1);

4.23 Rewrite the following if-else statements as condtional expressions.

a) if (x>y) ? z=1: z=20;
b) if (temp >45) ? population = base*10: base *2;
c) if (hours>40) ? wages*=1.5 : wages *= 1;
d) if ( result>=0)? System.out.println("The result is positive') : System.out.println("The result is negative');

4.24 Complete the followig program skeleton by writing a switch statement that displays "one: if the user entered 1,
"two" if the user has entered 2, and "three" if the user has entered 3. If a number other than 1,2,or 3 is entered, the program
should display an error message.

// Ask the user to enter 1,2,or 3

number = keyboard.next double( );

switch(number)
{ case '1':
System.out.println("one");
break;
case '2':
System.out.println("two");
break;
case '3':
case '1';
System.out.println("one");
break;
default:
System.out.println("error");
break;
}

4.29 Assume that the double variable number holds the value 459.6239. What format pattern would you use to display the as
00459.633 #00000.000

DecimalFormat formatter = new DecimalFormat("#00000.000");

4.30 Assume that the double variable number holds the value 0.179 what format pattern would you use to display the number
as .18 0.00

DecimalFormat formatter = new DecimalFormat("0.00");

4.31 Assume that the double variable number holds the value 7634869.1. What format pattern would you use to display the
number as 7,634,869.10

DecimalFormat formatter = new DecimalFormat("0,000,000.00");

Java CIT130
Chapter 5 Checkpoints

5.1 What will the following program segments display?

a) x=2;
y=x++
System.out.println(y); --> 2

b) x=2;
System.out.println(x++); --> 2

c) x=2;
System.out.println(--x); --> 1

d) x=8;
y=x--
System.out.println(y); --> 7

5.2 How many times will "Hello World" be printed in the following program segment?

int count = 10;
while (count < 1)

{
System.out.println("Hello World"):
count++;
}

Never
5.3 How many times will " I love Java programming!" be printed in the following program segment?

int count =0
while (count <10)
System.out.println.("Hello World");
System.out.println("I love Java programming!");

Once, no braces.

5.4 Write an input validation loop that asks the user to enter a number in the range of 10 though 25.

int number;

// get the number.

System.out.println ("Input a number between 10 and 25.");
number = keyboard.nextInt( );

// Validate
while ( number <10 || number>25)
{ System.out.println ("Input a number between 10 and 25.");
number = keyboard.nextInt( );
}

5.7 Name the three experessions that appear inside the parentheses in the for loop's header.

for (Initialization, test; update)

5.8 You want to write a for loop that displays "I love to program" 50 times.
Assume that you will use a control variable named count.

a) What initialization expression wil you use. count =1
b) What test expression will you use? count<=50;
c) What update expression will you use? count++
d) Write the loop.

for ( count=1; count<=50, count++)
System.out.println(" I love to program");

5.9 What will the following program segements display?

a) for (int count =0, count <6, count++)
System.out.println( count+count);
0
2
4
6
8
10
b) for (int value =-5; value<5; value++)
System.out.println(value);

-5
-4
-3
-2
-1
0
1
2
3
4

c) for (int x=5; x<=14; x +=3)
System.out.println(x);
System.out.println(x):

5
5
8
8
11
11

5.10 Write a for loop that displays your name 10 times.

for (int x=1; x<=11; x +=)
System.out.println(Jesse);

5.11 Write a for loop that displays all of the odd numbers 1 through 49.
for (int x=1; x<=50; x +=2)
System.out.println(x);

5.12 Write a for loop that displays every fifth number zero though 100.
for (int x=0; x<=101; x +=5)
System.out.println(x);


Homework #1
Create a simple program using Java for a wage calculator with the following requirements:
 This program will have a header block comment with your name, the course and section, as well as a brief description of what the program does including a list of input(s) and output(s) of the program.
 A constant with value of the standard employee hourly wage (must be floating point).
 Takes the user’s name and employee id (as Strings) as well as their hours worked (must be an integer) as keyboard input.
 The program will calculate the employee’s wage for the week and output that to the screen.
 The program will use good coding conventions for readability including line comments describing at least two of the operations within the program.
 The program will be partially graded on your ability to provide a good interface to users (i.e. nicely formatted output and clear instructions for input).
This assignment is intended to get you to demonstrate basic knowledge of the concepts learned so far, as well as motivate you to get the JDK installed and configured properly for use for all further assignments.

 


Homework #2
1) Create a simple Java class for an Employee with the following requirements:
 This class will have a header block comment with your name, the course and section, as well as a brief description of what the class does.
 Private attributes for Employee Name (String), ID Number (int), Department (String), and position (String).
 Public methods for setting the Employee Name, ID Number, Department, and Position, as well as methods for returning the values of those attributes.
 The class will use good coding conventions for readability including comments describing what each method does with input(s) and output(s) described, and each attribute described by line comments.
 There will need to be a main program as well that creates and uses three instances of your Employee in ways that demonstrate that each method and attribute works as anticipated, and that shows that each instance has different values for its attributes (i.e. shows the concept of instance variables).
2) Create a simple Java class for a piggy bank with the following requirements:
 This class will have a header block comment with your name, the course and section, as well as a brief description of what the class does.
 Private attributes for the number of pennies, nickels, dimes, and quarters in the bank.
 Public methods for adding pennies, nickels, dimes, and quarters, as well as to see the number of each coin type.
 The class will need to report the bank’s balance at any given time.
 The class will use good coding conventions for readability including comments describing what each method does with input(s) and output(s) described, and each attribute described by line comments.
 There will need to be a main program as well that creates and uses an instance of your piggy bank in a way that demonstrates that each method and attribute works as anticipated.


This assignment is intended to get you comfortable with creating classes, and is intentionally repetitive within each problem to get you used to some common class design ideas like constructors, accessor and mutator methods, and private attributes.

 

 

Homework #3
1) Create a simple Java class for a bank account with the following requirements:
“Your bank account can have money put into the bank in the form of a deposit, and removed from the bank in the form of withdrawals. A customer needs to be able to put money into their account, withdraw money from their account, and see their current balance at any given time.”
Take the above problem description, and create an appropriate class with whatever attribute(s) and methods necessary to accomplish the written goal. Please include one or more constructors, and the standard comments we have used in the other homework for this class. Also provide a main program that uses the created class.


This assignment is intended to get you comfortable with designing classes given just a description.

Homework #4
Create a simple Java class for a Month object with the following requirements:
 This program will have a header block comment with your name, the course and section, as well as a brief description of what the class does.
 A static constant with value of the number of Month objects instantiated.
 One property: monthNumber (1-12) where 1 is January, 2 is February, etc.
 Three constructors: one with no arguments that sets the default monthNumber to 1, one that takes an integer input to use as the monthNumber, and one that takes a month object and creates a copy of it as a new instance.
 A setMonth() method that takes an integer.
 A getMonth() method that returns the monthNumber as an integer.
 A toString() that returns the String name of the month (e.g. January).
 An equls() method that takes a month object and returns a boolean based on the values of each object’s monthNumber.
Create a simple program using Java that demonstrates the month object with the following requirements:
 That creates three month objects: One with the no argument constructor, one using the integer input constructor, and one that uses the second object to copy it.
 The program will display the month names for the first and second object using the toString() methods, as well as compare the first and second objects for equality and display the result.
 The program will display the month number for the second and third object using the getMonth() methods, as well as compare the second and third object for equality and display the result.
 The program will display the value of the static integer variable of how many month objects were created.


This assignment is intended to get you to demonstrate knowledge of creating a variety of common class methods as well as overloading constructors. Additionally, the use of a static variable is used reinforce the static modifier as learned in class.

 

 

 

My Notes CIT130 * - 801 Fall 2009

2nd Class 9.8.9 Notes

Programming Process Section 1.6

Variables
Literals
Primitive Types
Constants -
Arithmetic { +,-,*,/, % % means modulus}
Type Conversions
Scope
Comments -none executed lines used to give information to the programmer.


// line comments, bllock comments /* to */, document comments /**

Input from AB
Common Errors
Clearly Define the Problem to be Solved
Visualize the program running
Diagrams/ Models
Check for Logic Errors ( Division by Zero, weird inputs, ..........)


Then your ready to Code
Test/Debug (Repeat 5&6)
Compile & Test In-house testing (Alpha Testing), End User (Beta Testing)

Validate

Patching and revisions
String - a series of characters with a specific meaning. Not a primitive type. aclass: String a= "Hello"

'a' is a char, "a" is a string.

System.out println (a +b); object-refers to our computer screen. System.in refers to our keyboard. Scanner is an object.

import java.util.scanner;

Scanner Kbd=new Scanner( );

CONSTANTS- are all caps. Variables start with lower Case = firstName,last Name, streetAddress. Class start with Caps.

Eclipse

3rd Class 9.15.09 Notes
Class - a descriptor for a set of objects.

Circle think concentric: circles.

attributes or prpperties- describe the object & its state.
methods-act on the attributes.
Object- an instance of a class

Reusability.

Inheritance. - how it works is for instance.
A real world object, if we had an animal object. Kinds of animals, mammals, birds, fish.

--------------------------------------------------------------------------------------------------------

Class Circle: for this use Radius <- Attribute.Ø

Get Radius( )
Set Radius(int r)
area( )
If one descriptor can be devised or calculated from another descripton.
Mutator and accessor Set Methods and Get Methods.

Instantiate - an object.

Circle C = new Circle( );

int x=7.

C set Radius (x)

public void set Radius (int r); <-- Argument

each input to a mehtod is an argument;

Rectangle needs H X W or { two integer h, integer w}

4th Class 09.22.09

REVIEW OF LAST LECTURE.

Class - A description of a set of objects

Attributes:-Varibles that describe the object and /or the object state.

Methods- procedures or functions which act on or through the object to modify attributes or report attributes.

Object- is an instance of a class.

Example: Circle which can essentially be described by just using radius. Radius <-- Private.

Methods/ Report get radius, modify set radius.

For every attribute we have one get & one set.

Piggy Bank Homework

Pennies
Nickels
Dimes
Quarters
Balance Method that calculates on the fly, dependent on previous data.

JAVA API

Classes: System.out, String, Scanner

API - Set of Libraries Application, Program, Interface.

Java. util.scanner Utilithy is the library. scanner is the class, Java I/O Input and Output.

Javac. http;//java.sun.com java.util.*, can be put into program. Math Math.PI <-- Constant=3.14.159, Math (pow (dbl,

dbl), Math.log, Math.sqrt.

Constructors Scanner kbd = new Scanner (System.in): String name = new String ("Brian")

STring ("Brian"), Constructor: A method that creates a new object.

Default constructor no argument constructor.

Piggy p= new Piggy ( ); p=0,n=0,d=0 q=0.

public Circle ( ) <- Constructors always, have the same name as the class.

{

radius= 0:

}

Public Circle (int r) radius=rr)

}

OVERLOADING - when we have multiple mehods of the same neame with different arguments.

Ex. public Piggy ( int p, int n, ind d, int q)

{ pemmies = p: nickles =n, dimes =d, quarters =q: }

Psuedo Code: I wan a program that takes in all o my test scores and gives me the students frinal grade.

Indentify the nouns: I , Program, test scores, me, final grade. --> Test Sciores, Final Grade. Final Grade is the Object, Test Scores

are attributes.

private int test1,

private int test2,

private int test t:

What do we need? Constructor get and set for each attribute, 0 or more calculations.

Public ing get Test1( )

return test 1;

public vouid set Test 1 ( int score)

test1= score;}

Public int calcGrade

{ int grade;

grade= test1+test2+test3+....

grade= grade= grade/ I0:

return=grade:

}

SCOPE - only valid after its declared.

- only valid in the block in which it is declared.

SHadowing

Notes 09.27.09
- DECISION STATEMENT Chapter 4
IF THEN- ELSE
IF ( true) whatever the operation system.out.println.

Comparitve operators - >,< , =, /=. Assignment and equivalence

Int x = 3, if ((x=3) doesn't work use double operator if (x==3) or (x != 3).

!= explanation point is not as in not equals.

SCOPE
Within the curly brackets { },

Movie Ticket Price Example

If (age > 55)

{ system.out .printly( "Senior Citizen" -$7)

} else if (age>18 && AGE<=55 ) Logical Operators &&, || the Pipe two pipes is an "OR", != NOT EQUAL

{ system.out.println(Regular)

else if ( age >12) }

} else if age <12) ELSE means otherwise it ignores other statements. Example: Age is -375.

When both statements are correct only on case. I'm a man. I'm 6'0.

&& "AND" Statement.

T F
T T F
F F F

|| "OR" Statement

T F
T T T
T T F

! Not is a Unairy Operator. I am not tweleve years old. True.

EFFICIENCY
IF (age > 55 || age <=12 )

IF (age >18 && age <=55)

&& And takes precedence over OR || or NOT !

Nested,

Strings are Objects - String S= "Brian". String S= new String "Brian". It will complie

Comparing Strings = Comparison Left to Right.

CONDITIONAL Operator
y=x>=55? 's': ''a',

Different way of doing the same thing. If )x.= 55)

y='s'

else y="a",

--------------------------------------------------------------------------

SWITCH Statement
can be called CASE statements IF a , else if b, else if c, else if d, else

Switch only works with char, byte, short, int. char grade.

Switch (grade)

{ case 'a"

systen,out.println('Algebra Honors), break

case 'b'

system.out.println{'Algebra 1), break

case 'c'

system.out.println{'PREAlgebra 1),break

case 'd'

system.out.println{'PREAlgebra Honors),break

case 'e'

system.out.println{'Remdial math ),break

case 'f'

system.out.println{'Err'),break

}

----------------------------------------------------------------------------------------------

Scanner, string, math, system Decimal Format
Import java.text.Decimal Format:

Your Balancee is: 10.300000000000001 instead of 10.30

Decimal Format actually is a string.

Deciumal Format d1=new Decimal Format ( " #0.00 " )<- Mask = String.

Another Version ( #,##0.00"), % "#0.00%"
-----------------------------------------------------------------------------------------------------------

6th Lecture 10.06.09

Class Loop
Attributes

Methods

-while
while (condition) ,-true

{ assuming something can happen to change the condition to "FALSE"

} For instance, char cont = 'Y"

while (cont =='Y")

{ system.out.println (Do you want to continue?")<

s=kbd.nextline( ),

cont= s.charA+(0)

-do
{

system.out.println (contiue""),

s=kbd.nextline( ):

cpmt= s.char A=(0);

} while ( cont=='Y'), Difference from while is DO will run at least one time.

-for
for ( int x=1, x<=10, x ++ ) initial, counter, increment operator Increment and/or Decrement x - - 1

{ sum = sum =X,

}

system.out.println(sum)

However, you solve the problem.

x= kbdnext(int( );

Lecture 10.13.09

INPUT/OUTPUT

inport java.io.*
import java.util.scanner
Scanner KBD-newScanner (System.in);
string s= kbd.nextLine( );
int x= Kbd nexttInt ( );
Double y = kbd.next double( ):

FILE


FILE PrintWriter <- output
Scanner === Input Pipe

1 Create a File Object ~= Call it inputFile = new File('Text.test");
Input Pipe ~= Scanner FileReader=new Scanner(inputFile),
string s = file Reader.nextln( ),
int X = File Reader:next int( ),
double y = file Reader.nextDouble( ),
Exception
The simplest way to deal with it
Public static void main (String { } argsm) THROWS IO Exception.
File output File = new File {"Test.txt"),-
PrintWriter fileWriter = new Print Writer ( outputFile,true); <---------- (writer Type);
PrintWrite fileWriter = new PrintWriter (write Type):
--------> FileWriterwrite type = new File Writer (output File);
FileWriter println(S);
FileWriter println(X);
FileWriter println(y);


Test 2 Weeks from Today.
From Chapter 3)
CLASS - A set of ogjects of specific type
Attribures descriptiove of object & Object state (Private)
Metho's act on atrributes.
Sets & Gets
Calxculations
Constructor public Class A
{ private int a: A newA = new A( ); <------- Const.
private double b;
public A( )
{
a=0:
b= 0.0;
public A( int of double b1)
{ a =a1,
b=b1;
} }

Chapter 6 Beyond the Basics
Static members
Overloaded methods
Passing Objects as Arguments
Returning Objects from mehods.
To String
Equals Mehtods
Copy Mehtods
Aggreagation, Inner Classes, Garbage Collection
Enumerated types.


What is magic Key Word Static

Static- Part of the class, but not part of objects of the type class.

Pivate int x;

Private Static object Count,

Public A( )

{ x=0 object Count #:

}Using something from Class not in an Object.

atributes common across all instances.

members

Lecture 8 Notes 10.20.09

OVERLOADING
PASSING OBJECTS TO METHODS
Passing by value
Passing by Reference
Returning Objects from Methods

Overloading -Creating more than one method of the same name.

Constructors
public Circle ( )
{
radius=0,
}

public Circle (int r)
{
radius = r;
}

public Circle (double r)
{
radius = r;
}
Method Signature
Circle ( )
Circle(int)
Circle(double)
Circle c1.=new Cicle( );
Circle c2.=new Circle(7);
Circle c3=new Circle(3.0);

Methods must be distinguishable.
Example: Rectangle Class

Constructors
Class 1 c1=new Class 1( );

PASSING Objects as Arguments to Methods inputs have been primitive types

Calculate Balance ( double income, double payout)
Car (Class) one of the attributes is color,
paint( car c, staring color)
c.setColor(color);

double x = 7.3;

Circle c1=new Circle(7.3)

x --> 7.3

c1--> Objecct(radius=7.3)

Main

String s = new string {"Brian");

x.char (s)

system.out.println(s);

Class

public void change (string x)

x="JOe";

return;

immutable Classes

Mid Term Exam
-API Sheet

java.lang String

to Upper

Covering Ch.2-5

Chapter 2

main prograam
print(printlln
primitive types
operators * / % +-
how to mame variables
keyboard input

Chapter 3

Class
priviate attibutes
public methods - gets, sets, calc construction
Chapter 4

if( ) -&&,||
compare strings s== s2. s eqials (s2)
Chapter 5

While loop waiting for condition to change
do........while loop always fun
for loop - fixed number of times.
which one to use.

Lectuture 11 11.03.09

Question #2 on Exam

public Class Register

{

private double subtotal=0.0;

private final double tax=0.075,

public void add (double deposti)

{

subtotal += deposti;

]

public dougle get Sub ( )

{ return subtotal;

}

public register ( )

{ public double total ( )

return subtotal * (1+tax),

}

}

public class use reg

public static void main (String [ ] ags)

scanner

{ double next price,

do

{ System..out.println (enter price," ");

next price= k.next Double( );;

r.add (next Price);

while ( next price !=0.00:

s.o.p ( r.get Subtotal( ));

s.o.p ( r. total( ):)

}

}

From previous class:

STATIC

OVERLOADING - signature Name (inputs)

passing Objects pass by value, pass by reference,

returning Objects

6.6 The to String Method

get,
set,
calculations,
constructors
equals( )
to String( )
copy( )
String s1="Brian";

String s2="Brian";

boolean ++ = (S3==S2); WHEN Stting s3=s2;

System.out.println( ' Hello," =s1=", How are you?}';

to debug

Register r= new Register( );

System.out.println( ' Hello," + r +", How are you?}';

r1 ---------> subtotal 10.0

Register r2 = r1; so now r2--------------> subtotal 10.0 r1== r2 true.

Methods that COPY objects copy ( )

for each attribute a , the equals method returns true if a1 == a2 for objects 1 & 2

----------------------------------------------------------------------------------------------

public boolean equals ( Register r)

{ if (this.subtotal == r.get subtotal( ) )

{ return true;

}

else

{ returne false;

}

}

----------------------------------------------------------------------------------------------

rectangle object

public boolean equals ( Redtangle r)

{

if ( this. width == r.getwidth( ))

&& ( this. height == r.het Height ( ))

{

return true;

}

else

{

return false;

}

}

--------------------------------------------------------------------------------------------------------------

public String toString ( )

{

return " width =" + w + "\n"

+ "height =" +h + "\n"; \ n means next or return

}

--------------------------------------------------------------------------------------------------------------

public Rectangle copy ( )

{

Rectangle new Rectangle = new Rectangle ( );

new Rectangle. set Width ( this.w);

new Rectangle. set Height( this.h);

return new Rectangle;

}

-------------------------------------------------------------------------------------------------------------

Rectangle

private int height;

{

public void set Height ( int height)

{

this. height - height;

}


-----------------------------------------------------------------------------------------------------------

public class Rectangle

{

private int height;

private int width

public void set Height( int h)

{

height = h;}

}

public void set Width( int w)

{

widtht = w;}

}

public void get Height( int h)

{

return height

}

public void get Width( int w)

{

return width

}

public int area ( )

{ return width * height,}


Lecture12 11.10.09
Chapter 6

Aggegation

Aggregation
Enumerated Types
Garbage
Arrays Next

passing objects to methods

returning objects from methods

- pass by reference

- pass by value

Aggregation - Class ex Rectangle

public Class Rectangle

private in height,

private int width,

private Color color;

Color class -> intensity, hue like ( pastel blue) Rectangle has an aggreagte relation to color.

Rectangle has a color.

public class Color,

public class Rectangle

public class use Rectangle

public void setWidth(int as) Rectangle r= new Rectangle

{ -} r.setWidth (-3)

width = w,

Enumerated Types - black, white, blue, red, yellow, green, purple, orange

public class Color

{ private string name;

public Color( String n)

{ if ( n.equals (" black",................} or

enum Color { BLACK, WHITE, BLUE, RED, YELLOW,GREEN, PURPLE, ORANGE

}

Color blue= Color.BLUE;

Cadence - if you said MEAN, they are not STRINGS, it could be REAL, it could be FACT, one two three FOUR.

GARBAGE Collection

Easy in JAVA,

public void finalize( )

{

system.out.println("I'm gone").

}

ARRAYS or Tables

int x=7; Rectrangle int [ ] = new int [ 7]; int [ ] x= int [7]

BLUE
RED
GREEN
ORANGE
BLACK


Lecture 11.24.09

ARRAY'S TODAY ----------->

10
11
3
407
6

INT [ ] int ARRAY = new int [6]

int [ ] int Array = { 10,11,3, 407,6}

int Array.length = 5,

Delving deeper into arrays. Operations with arrays, Algorithim analysis.

Similar to Conditional operator - enhanced for loop.

for (int x: int Array)

{

system. out.println(x);

}

Which is the same as,

for ( int x=0, x< int Array lenght; x+1)

{ System.out.println( intArray[x]);

int sum = 0;

for ( int X; int Array)

{ sum + =x;

}

System.out,println (sum);

int [ ] grades = { 75,83,81,97,85}

GB gradebook = new GB (grades)

GB { private int [ ] gradeset;

public GB int [3 g]

{ grades =g;

}

int [ ] a = { 6,7,1,4,3}

int [ ] b= { 6,7,1,4,4}

// compare 2 arrays

if (a.length ! = b.length) System.next.pringln{" Not");

for ( int x=0; x< a.length, x++)

{ if a [x] != b[x]

s.o.p ( "Not")

}

Biggest or lowest number in an array.

// find max value

= int max=a[0];

for (x=0. x< a.length; x++)

{ if ( a[x] > max)

max = a [x}

}

s.o.p (max)

INT [ ] prices = new int [ 100],

int last index = 0;

prices [ last.index ] = kbd.next.INT()

}

string [ ] roster = {'Brian"," Wai','Karen", "Ireland'}

s.o.p [1] ./b upper()),

w.a.i = .

Developing Algorithms - Comparison

p441

Sequential Search

int valueTo Find = 17;

int [ ] values = { 7,12,34,111,17,64,32];

for ( int x=0; x< values.lenght, x++)

{

if ( values [x] == value to Find)

system.out.println("value at '"=x),

}

N pieces of data, Algorithm of order n O(n). 7 steps

Selection Sort 2n steps 14 steps n+1* (n/2) = 1/2 n ^2+ 1/2n = 1/2 ( n^2 +n) = (n(n-1))/2

int valueTo Find = 17;

int [ ] values = { 7,12,34,111,17,64,32];

int min;

int y position;

for ( int x = 0; x< values.length x++)

{ min = values[x];

for ( int y =x; y< values.length y++)

if ( values [y] < min

min = values [y]

hold = values [x};

valutes [x] = min;

values[ y position} = hold;

Binary Search.

int middle index

int top.Index = values [ values. length -1;

while (

Lecture 12.01.09

2-Dimentional Arrays -- > Arrays of Arrays

int[ ] new int [0]

int[ ][ ] gradew = new int [10][4]

10 X4

0,0 0,1 0,2 0,3
1,0 1,1 1,2 1,3
9,0 9,1 9,2 9,3

Average for a single assignment = average for a single column in example

int sum=0;

FOR (int x= 0; x < grades.length, x++)

{

sum += [x][0];

}

int average = sum/grades.length;

average for a single student = average for a single row.

int sum =0:

FOR (int y= 0; y < grades[0] length, y+1)

{

sum += grades[0] [y];

}

int average = sum/grades[0].length;


int stdntSum=0;

int assignSum[grades.length],

FOR (int x= 0; x < grades.length, x++)

{

FOR (int y= 0; y < grades[0] length, y+1)

}

student Sum += grades [x] [y];

assignSum[y] += grades [x] [y];

}

system.out.println (studentSum /Grades [x].length

for ( int z=0; z < assignSum.length;Z==)

{ system.out.println ( assignSum[z]/ grades.length)

}

Multi - dimensional or infinite arrays : Cubes, int [ ] [ ] [ ] grades = new [4] [10] [4 ]

-------------------------------------------------------------------------------------------------------------------------------

Lecture 12.08.09
Final will look like.

OBJECT ORIENTED PROGRAMMING

- cREATE A cLASS

PRIVATE ATTRIBUTES.

create a class

private attributes

get/set

constructors - SPECIAL METHODS TO ASSIGN SPECIAL

reg constructor w input values

copy cont

CALCULATiIONs -

multiple attributes dependent on each other.

Seperate attributes for pennies,nickels, dimes, quarters.

Balance should be a calculation method.

- to STRING ( DEBUGGING)

- eQUALS mETHOD

- PASS BY REFERENCE

- pIGGY - set DIMES, pIGGY - GET dIMES. pASS BY VALUE.

- aGGREGATION ' has a contains an OBJECT'.

x-- > Time Object H = 12, M =57

emp.set time IN ( x)

x set hour equals 1. emp get timein (x)

Copy all attributes of a passed in object to avoid the calling prgram form acessing tpt values of the aggreagate object.

public void set timeIn ( TIME)

Time +2 = new Time ( ):

+1 set Hour ( + get hour );

+1 set Min ( + get Min)+

Public Time. get time

Time +1 = new Time

Conceptually chapter 6 meaty.

Arrays

grades identifier name = new int [ ] size of the array.

An array of length 6 has indexs 0-5.

No Algorithm Analysis on Final

Exceptions.

Inside a method if ( Statement) assigns value.

ELSE throw new Illegal Argument e ( 'Bad Date');

Constructor 1-12 assign - Good or Exception method to throw message.

try { CALL THE METHOd}

CATCH ( ILLEGAL ARGUMENT EXCEPIONp

{ prnt.out mst.}