Pascal Lab #1



Java Programming Name ____________________

import javax.swing.JOptionPane: This command will bring in (import) the input dialog box and the message dialog box that we will use to ask a question and print the results.

VARIABLE TYPES - int (whole numbers and their negatives), double (decimals), and String (series of characters such as a word). The type of variable describes the kind of information it will be assigned. It is better to use descriptive identifiers for variable names rather than x or y like in Algebra.

A variable which represents the score on the front nine holes of a golf round could be named front. int is the appropriate type for front since golf scores are whole numbers, so the variable declaration is:

int front;

A variable which represents the radius of a circle could be named radius. double is the appropriate type for radius since it is possible to have decimal values for a radius, so our variable declaration is:

double radius;

A variable which represents a person’s name could be named person. String is the appropriate type for person since it is a series of characters, so the variable declaration is:

String person;

If a program attempts to use a variable name that has not been declared, it generates an error message. When the compiler reads a variable declaration, it sets aside space in the computer’s memory to store the information that will be assigned to each variable. Think of this storage space as a box within the computer’s memory identified by the variable name.

Often variables have to be initialized. Variables need an initial or starting value. You can initialize a variable at the same time that you declare it or you can initialize it separately. The following examples show how to declare and initialize a variable. In the first column, variables are declared and initialized in one step. Column two shows how to first declare a variable and then initialize it later.

|int front=0; |int front; |

| |front=0; |

|double radius=0.0; |double radius; |

| |radius=0.0; |

|String name=””; |String name; |

| |name=””; |

Variable names are case sensitive so watch your use of capitalization. Also watch that you spell the name of a variable the same way every time you use it.

JOptionPane.showInputDialog: This method call will bring up a dialog box that will print the words that you have entered, and then wait for the user to enter a response and click the OK button. If you type the following line of code, you will get the pictured box.

answer=JOptionPane.showInputDialog(“Enter score on front nine holes”);

When the user clicks OK, their answer is returned as a String (a series of characters) and is stored in the variable specified at the start of the line. So in this case, their typing is stored in the variable answer. Therefore prior to this line, the variable answer must have been declared as a String variable.

The program then needs to convert the user’s typing from a String into an integer so it can do math with it. The following line converts the String answer into the integer front. Prior to this line, the variable front must have been declared as an int variable.

front=Integer.parseInt(answer);

So in order to store the integer answer for the user’s score on the front nine holes, the following four lines of code are needed:

String answer;

int front;

answer=JOptionPane.showInputDialog(“Enter score on front nine holes”);

front=Integer.parseInt(answer);

JOptionPane.showMessageDialog: This method call will bring up a dialog box to display the desired text. The method call needs to have 2 items (parameters) inside its parentheses separated by 1 comma. The first parameter is the word null which centers the dialog box in the window. The second parameter is the String that is to be printed.

If the following line of code was used, the pictured message box that would appear.

JOptionPane.showMessageDialog(null,”Good Bye”);

The same results would be gotten if a String variable answer was assigned the text Good Bye and then that variable is used in the message box.

String answer=”Good Bye”;

JOptionPane.showMessageDialog(null, answer);

CONSTANTS: Constants keep the same (constant) value throughout the run of the programs. Java provides a way for the programmer to define constants as in the following 2 examples. In each, the keyword final identifies them as constants.

final static int PAR=72;

final static double PI=3.14;

The first line says that the integer PAR represents the value 72 and that it will not change during the execution of the program. The second line says that the double PI represents the value 3.14 and that it will not change during the execution of the program. The constant definition section appears after the start of the class but before the start of the public static void main function. Constants are usually written in solid capitals so that they are easy to see.

There are three advantages to using constants.

1. They make programs clearer. area = PI * radius * radius is an obvious statement of the formula for the area of a circle.

2. They help programmers avoid errors. The compiler will not allow the value of a constant to be changed mistakenly during a run of the program.

3. They make programs easier to change. Suppose PI were used many times throughout a long program and a more accurate value was later desired (3.14159). Rather than searching through the entire program for every occurrence of 3.14 and changing it to 3.14159, only the value in the final definition would have to be changed.

Golf Program

This program will ask the golfer for his scores on the front and back nine holes. The program will then tell him his total score and how much over par he his. For those of you who have never played golf, par is usually 72.

Here is a sample run:

The program will have four integer variables named front, back, total, and overpar. The program will have one String variable named answer. The program will have one integer constant named PAR. The plus signs (+) will be used to build or concatenate the String answer. The following line will put together 4 words followed by a number followed by 2 words followed by a number followed by 2 words.

answer="The total score is "+total+", which is "+overpar+" over par.";

The line will produce the following sentence when integers are inserted in place of the variables.

The total score is 82, which is 10 over par.

//your name lab#0

import javax.swing.JOptionPane;

public class Golf

{

final static int PAR = 72;

public static void main(String[] args)

{

int front, back, total, overpar;

String answer;

answer=JOptionPane.showInputDialog("Enter score on front nine holes: ");

front=Integer.parseInt(answer);

answer=JOptionPane.showInputDialog("Enter score on back nine holes: ");

back=Integer.parseInt(answer);

total=front+back;

overpar=total–PAR;

answer="The total score is "+total+", which is "+overpar+" over par.";

JOptionPane.showMessageDialog(null,answer);

}

}

MATH: Addition, subtraction, multiplication, and division of doubles give the results you would expect for decimals. Addition, subtraction, and multiplication of integers give the results you would expect for integers. Division presents a special problem because the result of dividing two integers is cut off at the whole number. If you divide the integer 9 by the integer 4, you will get the answer 2.

9 / 4 = 2

This is probably not what you would expect since your calculator would give you the answer of 2.25 When Java divides two integers, the answer is just the whole number component of the division; the remainder is dropped. To get around this problem, you have to temporarily change one of the integers to a double.

9.0 / 4 = 2.25

Let’s say in the golf program, you wanted to find the average score per hole. Total has been declared as an integer and average has been declared as a double. Pretend the total score was 93. If you had the following equation,

average=total/18;

The computer would divide 93 by 18 and get an answer of 5. But the correct answer that you were looking for is 5.16 You need to use the following equation to get that answer. This equation would temporarily change (cast) total to a double and then divide by 18.

average=(double)total/18;

FORMATTING OUTPUT: A double may not print with the number of decimal places that you desire or it might print in scientific notation. Therefore a new type of variable will be needed; that type is a DecimalFormat. You will need to have an additional import line as the second line of your program as follows:

import java.text.DecimalFormat;

In the main method, you need to declare a DecimalFormat variable. A good name for that variable might be output. Set that variable up to hold a decimal format of 2 decimal places.

DecimalFormat output=new DecimalFormat(“0.00”);

Instead of having a line like the following which does not control the number of decimal places:

answer=”The average is “+average;

The following line is used to display the average rounded to 2 decimal places:

answer=”The average is “+output.format(average);

So to format decimal numbers with rounding, you have to do 3 things. First import the DecimalFormat package, then define what the decimal format will look like, and then finally apply it to your variable.

import java.text.DecimalFormat ;

DecimalFormat output=new DecimalFormat(“0.00”);

answer=”The average is “+output.format(average);

Lab #1 Bowling

Have your program ask the user his bowling scores for three games. Give the total of all three scores and also give the average score rounded to the nearest hundredth. Your output should match the example below. The three scores and the total variables are integers and the average variable is a double. There aren’t any constants.

Lab #2 FastFood

Write a program that asks for the number of hamburgers, sodas, and fries purchased. Hamburgers cost $1.99 each. Sodas are $0.99 each. Fries are $1.29 each. The program needs to figure out the cost of the food, the 6% sales tax (0.06) and the final cost. There are 4 constants that were just given in the previous sentences. Use the names ONEBURGER, ONEFRY, ONESODA, TAXRATE for the constants.

Make your 3 integers have the variable names numburgers, numsodas, and numfries. Make your 3 doubles have the variable names cost, tax, and finalprice. There should be three separate input dialog boxes that are not shown below, but an example of the message dialog box is shown with the results.

The results should be printed rounded to the nearest cent with dollar signs. Put the dollar sign inside the quotes of the DecimalFormat. To make a new line in your output, put a \n (a backslash followed by the letter n) inside the quotes of the answer string, right before the T in Tax and before the F in Final Price.

Example 1:

Enter number of hamburgers: 3

Enter number of sodas: 4

Enter number of fries: 3

Example 2:

Enter number of hamburgers: 2

Enter number of sodas: 2

Enter number of fries: 1

BRANCHING (DECISION MAKING)

The simplest control statement, if, takes the form:

if (Boolean Expression)

{

statement;

}

The statement part can be any statement allowable in Java. The (Boolean Expression) is an expression that can only have one of two values, true or false. The following is a Boolean expression:

radius < 0.0

Boolean expressions are most commonly formed from one of the following comparison operators.

Operator Meaning

== equal to (be careful to not confuse with = which is the assignment operator

< less than

> greater than

= greater than or equal to

!= not equal to

When an if statement is encountered, the computer first evaluates the Boolean expression to determine if it is true or false. If the Boolean expression is true, the statement following then is executed, after which the program proceeds to the next statement in the program. If the Boolean expression is false, the computer immediately goes to the next statement following the if without executing the optional statement.

if (grade>=65)

{

credit=1;

}

Programmers often want the computer to perform one action if a Boolean expression is true, and another is it is false. This is done by adding an else to the if. Notice the placement of the semicolons and the indenting.

if (grade>=65)

{

credit=1;

}

else

{

credit=0;

}

Sometimes it is necessary to perform more than one action in either a if or an else clause. Notice the placement of the semicolons and indenting. Two lines are executed when the if statement is true; nothing is executed when the if statement is false.

if (grade>=65)

{

JOptionPane.showMessageDialog(null, ”Congrats”);

credit=1;

}

Here is another example that has compound if and compound else statements. Notice the placement of the semicolons and the indenting. Two lines are executed when the if statement is true and a different two lines are executed when the if statement is false.

if (grade>=65)

{

JOptionPane.showMessageDialog(null,”Congrats”);

credit=1;

}

else

{

JOptionPane.showMessageDialog(null,”Sorry”);

credit=0;

}

In addition to using simple Boolean expressions in an if statement, Java permits expressions to be combined using the and/or operators. The symbol for and is two ampersands &&, while the symbol for or is two pipes ||. You can mix ands and ors on the same line. You can put as many as you’d like of each on a line too.

When two Boolean expressions are joined by and, the whole Boolean expression is considered true only when both of the expressions are true. Note how the individual comparisons are enclosed in parentheses as well as the entire Boolean expression. Therefore, the following if statement writes Accept for anyone who has both a high SAT and a high GPA.

if ( (sattotal>1200) && (gpa>3.5) )

{

JOptionPane.showMessageDialog(null,”Accept”);

}

When two Boolean expressions are joined by or, the whole Boolean expression is considered true only at least one of the expressions are true. Therefore, the following if statement writes Wait List for anyone who has a high SAT, or a high GPA, or both.

if ( (sattotal>1200) || (gpa>3.5) )

{

JOptionPane.showMessageDialog(null,”Wait List”);

}

It would make more sense to write the above code as a set of three if-elseif-else statements. This way students with both high a SAT score and a high GPA are accepted. Then students with either a high SAT score or a high GPA are wait listed. Finally students with neither a high SAT score or a high GPA are rejected.

if ( (sattotal>1200) && (gpa>3.5) )

{

JOptionPane.showMessageDialog(null,”Accept”);

}

else if ( (sattotal>1200) || (gpa>3.5) )

{

JOptionPane.showMessageDialog(null,”Wait List”);

}

else

{

JOptionPane.showMessageDialog(null,”Reject”);

}

In summary:

• If you want the program to choose one course of action if true, use an if statement.

• If you want the program to choose between two course of action, follow one course of action if true or follow another course of action if false, use if and else statements.

• If you want the program to choose between three courses of action, use if - else if - else statements.

• If you want the program to choose between four courses of action, us if - else if - else if - else if - else statements. You can keep building these statements longer and longer as you need might be.

You can also put if-else statements inside other if else statements. You can put them inside of loops that you will be learning about shortly.

if (age=80)

{

JOptionPane.showMessageDialog(null,”Need to take refresher course”);

}

}

Lab #3 Payroll

The program calculates weekly wages given the hours worked and the hourly rate. It then figures the taxes that are deducted from your wage and subtracts them to end up with your gross pay.

The federal government has a graduated tax rate schedule. If you make under $100 per week, you have to pay 15% of that in taxes. If you make from $100 to just under $300 per week, you have to pay 28% of that in taxes. If you make $300 or more per week, you have to pay 36% of that in taxes. Write an if-elseif-else to calculate your taxes based on these 3 levels.

There should be 5 constants (100, 300, 0.15, 0.28, 0.36) based on the facts in the above paragraph.

The code to extract a double number is similar to what we have been using to create an integer from answer that is returned from the showInputDialog box. payrate is a double variable and answer is a String variable in the following code:

payrate = Double.parseDouble(answer);

Example 1:

(More examples on next page)

|Example 2: |Example 3: |

| | |

|Hours worked: 12 |Hours worked: 25 |

|Hourly payrate 8.25: |Hourly payrate: 6.50 |

|Wages: $99.00 |Wages: $162.50 |

|Taxes: $14.85 |Taxes: $45.50 |

|Gross Pay: $84.15 |Gross Pay: $117.00 |

|Example 4: |Example 5: |

| | |

|Hours worked: 40 |Hours worked: 20 |

|Hourly payrate: 7.50 |Hourly payrate: 5.00 |

|Wages: $300.00 |Wages: $100.00 |

|Taxes: $108.00 |Taxes: $28.00 |

|Gross Pay: $192.00 |Gross Pay: $72.00 |

LAB #4 DRIVING

The first input dialog box will ask how old a person is. If their age is less than 16, a message box should display how many years before they can drive. If their age is greater than or equal to 16, the program should have two more input boxes that ask the mileage and gallons questions. A final message box should display the miles per gallon (rounded to the nearest tenth) and the appropriate guzzler/efficient message. A gas-guzzler is a car that gets less than 30 mpg.

This program should have an if-else based on whether their age is less than 16. In the else category (for people 16 or over), there should be another if-else that decides whether their car is a gas-guzzler or efficient. There should be 2 constants in this program. Four examples are given on this page and the next.

Example 1:

Example 2:

Example 3:

Age: 44

Gallons of Gas: 9

Miles: 245

That is 27.2 miles per gallon. You drive a gas-guzzler!

Example 4:

Age: 33

Gallons of Gas: 15

Miles: 450

That is 30.0 miles per gallon. You drive an efficient car!

LAB #5 HeadsTails

Ask the user to enter either the number 1 or the number 2. If they enter a 1, have the program say “heads”. If they enter a 2, have the program say “tails”. This is a simple program but you will be adding more to it later.

Example 1:

Example 2:

LOOPING (REPETITION) USING FOR LOOPS: Most computer programs need to be able to perform some tasks repetitively – i.e. to use certain statements more than once. When you want to repeat statements a set or pred-determined number of times, use a for loop. The process of re-executing statements is called looping and each repetition of a loop is called an iteration. The for loop repeatedly executes an instruction as long as the Boolean expression is true. Its structure is:

for (starting value; Boolean expression; increment)

{

statement;

}

The statement contained in the loop is called the body of the loop and may consist of a single statement or many statements inside a set of braces. Note that there is not a semi-colon on the end of the for statement line.

for (int num=1; num ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download