CPCS202 - The Lab Note

Term I
2012
LAB 3: ELEMENTRY PROGRAMMING
Statement Purpose:
The purpose of this Lab. is to familiarize student how to solve practical problems
programmatically; they will practice on elementary programming using primitive data
types, variables, constants, operators, expressions, and input and output. Also, they will
learn how to diagnose errors that may occur when a program is compiled or executed.
There are some exercises, through which they will understand the concept learn in this
chapter.
Activity Outcomes:
Student will learn how to write Java programs to perform simple calculations, they will use
Scanner class to obtain input from the console, they will know how to use identifiers to
name variables, constants, methods, and classes. The use of constants , Java primitive data
types: byte, short, int, long, float, double, and char, Java operators to write numeric
expressions , use shorthand operators , cast the value of one type to another type , use of a
string using the String type etc are some of other outcomes of this lab. Further they can
distinguish syntax errors, runtime errors, and logic errors and debug errors.
Instructor Note:
Read the exercises below and submit your answer in the answer sheet available in the
end. English will be the official language throughout the discussion.
Names
1. .……………..……………………………….
CPCS-202 - The Lab Note
I.D
………………………………
Lab. 3
1
Term I
2012
LAB 3: ELEMENTRY PROGRAMMING
Activity 1: write a program in java to interchange (swap) values of two variables with a use
of 3rd variable.
Input: value num1 and num2
Processing: swapping values of num1 to num2 and num2 to num1 using a third variable
num3.
Output: Display value of num1 and num2 after swap operation.
Solution:
A. File -> New project-> Project Name: Lab3Activities , Main Class Name 
Swap2Nos  click Finish Button
B. Write Code inside the main method and test it by compiling (F9) and running
(Shift + F6) your code.
CPCS-202 - The Lab Note
Lab. 3
2
Term I
2012
LAB 3: ELEMENTRY PROGRAMMING
/* Swap Two Numbers Using Third Vairable*/
public class Swap2Nos {
public static void main(String[] args) {
// declare variables num1, num2, num3 of the type int
int num1, num2, num3;
// assign values to num1 and num2
num1=50;
num2=100;
// display Number before swap
System.out.println("Before Swap Number 1 =" + num1 + " Number 2= "+ num2);
// swap logic starts from here
num3=num1;
num1=num2;
num2=num3;
// swap logic ends here
// display Number After Swap
System.out.println("After Swap Number 1 =" + num1 + " Number 2= "+ num2);
}
}
CPCS-202 - The Lab Note
Lab. 3
3
Term I
2012
LAB 3: ELEMENTRY PROGRAMMING
Activity 2: This activity uses application Greet. Compile and rerun the application
after each modification.
_______________________________________________________
// Application Greet prints a greeting on the screen
_______ class Greet
{
public ______ _______ main(String[] args)
_____
_______String FIRST_NAME __ "Sarah ";
final _______ LAST_NAME = "Sunshine";
String message;
_________ name;
name __ FIRST_NAME __ LAST_NAME;
message = "Good morning" __ ' ' + name + '.';
System.out._______(message);
_____
}
_______________________________________________________
Exercise 1: Application Greet prints a greeting on the screen. However, it is
missing certain identifiers, reserved words, and operators that are necessary for
it to compile. Replace each blank with the appropriate identifier, reserved word,
or operator and run the application. Record the output below.
Exercise 2: Replace the named constants with your first and last names and
rerun the application.
Exercise 3: Make the greeting a named constant rather than a literal constant
and rerun the application.
Exercise 4: Change the action part of the application so that the greeting is
written on one line and your name is on the next line.
CPCS-202 - The Lab Note
Lab. 3
4
Term I
2012
LAB 3: ELEMENTRY PROGRAMMING
Activity 3: Write a program in java that obtains minutes and remaining seconds from an
amount of time in seconds. For example, 500 seconds contains 8 minutes and 20 seconds.
Output of the program can be:
A. File -> New File-> File Type : java main class  next
B. Class Name  ConverSecMin click Finish Button
C. Write Code inside the main method and test it by compiling (F9) and running
(Shift + F6) your code.
CPCS-202 - The Lab Note
Lab. 3
5
Term I
2012
LAB 3: ELEMENTRY PROGRAMMING
Reading Data from keyboard using Scanner Class
Step 1: import java.util.Scanner; /*before your class statement*/
Step 2: create Scanner object to obtain input from command window
Scanner input = new Scanner ( System.in );
/* input is object name of Scanner Class you may write any object name like in , read etc.
*/
Step 3: input.nextInt(); // read number
Activity 4 // let's look at a simple program that computes the area of a circle.
A. File -> New ->Java Main Class-> named it ComputeCircleArea
B. Write Code inside the main method and test it by running the application.
The program can be expanded as follows:
// Step 1 : import java.util.Scanner;
public class ComputeCircleArea
{
public static void main(String[] args) {
// Step 2: declare variables
// Step 3: Read in radius
// Step 4: Compute area
// Step 5: Display the area
} }
CPCS-202 - The Lab Note
Lab. 3
6
Term I
2012
LAB 3: ELEMENTRY PROGRAMMING
// Example a simple program that computes area of a circle.
import java.util.Scanner;
public class ComputeArea {
// Declare a constant PI
static final double PI =3.1414;
public static void main(String[] args) {
double radius, area; // variable declaration
Scanner in = new Scanner (System.in);
System.out.println("Enter Raduis");
// read radius from the system
radius = in.nextDouble();
area=PI*radius*radius;
System.out.println("Area of Circle\t"+ area);
}
}
CPCS-202 - The Lab Note
Lab. 3
7
Term I
2012
LAB 3: ELEMENTRY PROGRAMMING
Arithmetic Expressions:
Writing numeric expressions in Java involves a straightforward translation of an arithmetic
expression using Java operators. For example, the arithmetic expression
Can be translated into a Java expression as:
(3 + 4 * x) / 5 – 10 * (y - 5) * (a + b + c) / x + 9 * (4 / x + (9 + x) / y)
Activity 5: The problem is to write a program that computes loan payments. The loan can
be a car loan, a student loan, or a home mortgage loan. The program lets the user enter the
interest rate, number of years, and loan amount, and displays the monthly and total
payments. The formula to compute the monthly payment is as follows:
Given the monthly interest rate, number of years, and loan amount, you can use it to
compute the monthly payment.
CPCS-202 - The Lab Note
Lab. 3
8
Term I
2012
LAB 3: ELEMENTRY PROGRAMMING
Here are the steps in developing the program:
1. Prompt the user to enter the annual interest rate, number of years, and loan amount.
2. Obtain the monthly interest rate from the annual interest rate.
3. Compute the monthly payment using the preceding formula.
4. Compute the total payment, which is the monthly payment multiplied by 12 and
multiplied by the number of years.
5. Display the monthly payment and total payment.
// Following is complete program for activity 4.
// File / class name ComputeLoan.java
import java.util.Scanner;
public class ComputeLoan {
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
// Enter yearly interest rate
System.out.print("Enter yearly interest rate, for example 8.25: ");
double annualInterestRate = input.nextDouble();
// Obtain monthly interest rate
double monthlyInterestRate = annualInterestRate / 1200;
CPCS-202 - The Lab Note
Lab. 3
9
Term I
2012
LAB 3: ELEMENTRY PROGRAMMING
// Enter number of years
System.out.print( "Enter number of years as an integer, for example 5: ");
int numberOfYears = input.nextInt();
// Enter loan amount
System.out.print("Enter loan amount, for example 120000.95: ");
double loanAmount = input.nextDouble();
// Calculate payment
double monthlyPayment= loanAmount * monthlyInterestRate / (1 - 1 / Math.pow(1 +
monthlyInterestRate, numberOfYears * 12));
double totalPayment= monthlyPayment * numberOfYears * 12;
// Display results
System.out.println("The monthly payment is " + (int)(monthlyPayment * 100) / 100.0);
System.out.println("The total payment is " + (int)(totalPayment * 100) / 100.0);
}
}
CPCS-202 - The Lab Note
Lab. 3
10
Term I
2012
LAB 3: ELEMENTRY PROGRAMMING
Increment and Decrement operators:
Aside from the basic arithmetic operators, Java also includes a unary increment operator
(++) and unary decrement operator (--). Increment and decrement operators increase and
decrease a value stored in a number variable by 1. For example, the expression, count =
count + 1; //increment the value of count by 1 is equivalent to, count++;
The increment and decrement operators can be placed before or after an operand.
When used before an operand, it causes the variable to be incremented or decremented by
1, and then the new value is used in the expression in which it appears.
For example,
int i = 10,
int j = 3;
int k = 0;
k = ++j + i; //will result to k = 4+10 = 14
When the increment and decrement operators are placed after the operand, the old value
of the variable will be used in the expression where it appears. For example,
int i = 10,
int j = 3;
int k = 0;
k = j++ + i; //will result to k = 3+10 = 13
CPCS-202 - The Lab Note
Lab. 3
11
Term I
2012
LAB 3: ELEMENTRY PROGRAMMING
Conversion between Data Types:
We can convert the value of a variable to the format of another variable of different type
and make an assignment between them, conversion is different from another operation
called casting, Following discussion shows the difference between them.
int i; float f; double d;
i = 1;
f = 4.4f;
d = 5.5;
d = i;
i = (int)f;
f = (float)d;
System.out.println("i = " + i + " f = " + f + " d = " + d);
The above code does the following:
● Converts the value of i to double and stores it in d. This conversion is done automatically
by the compiler, because double data type is normally wider than int, there is absolutely no
risk storing int in double.
● In the following two statements, notice that we but a large value into a smaller data type,
in this case, a possible loss of data occurs in which we have to be aware of. Because that,
compiler (by default) refuses to store float value in int, or double in float. Because of that,
we use casting to tell to compiler that we know what we are doing!
CPCS-202 - The Lab Note
Lab. 3
12
Term I
2012
LAB 3: ELEMENTRY PROGRAMMING
Another way to convert between variables is using some defined methods that converts
between variables.
One of them is a well known method that converts a String to integer which is
Integer.parseInt() method, the following example shows how to use it.
String s = "115";
int x = Integer.parseInt(s);
x++;
System.out.println(x); //prints 116
Similarly, we can also use Double.parseDouble(), Float.parseFloat() and
Long.parseLong().
A common method among all objects in Java is toString() method which converts the object
to a string, toString() method will be covered in more details later. Types of conversion
mentioned above are called explicit conversion, because we request that.
CPCS-202 - The Lab Note
Lab. 3
13
Term I
2012
LAB 3: ELEMENTRY PROGRAMMING
Activity 6: gives a program that displays the sales tax with two digits after the decimal
point.
Program: SalesTax.java
import java.util.Scanner;
public class SalesTax {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter purchase amount: ");
double purchaseAmount = input.nextDouble();
double tax = purchaseAmount * 0.06;
System.out.println("Sales tax is " + (int)tax*100/100.0) ;
}
}
Using JOptionPane to get input
Another way to get input from the user is by using the JOptionPane class which is found in
the javax.swing package. JOptionPane makes it easy to pop up a standard dialog box that
prompts users for a value or informs them of something.
CPCS-202 - The Lab Note
Lab. 3
14
Term I
2012
LAB 3: ELEMENTRY PROGRAMMING
Given the following code,
Activity 6:
import javax.swing.JOptionPane;
public class GetInputFromKeyboard
{
public static void main( String[] args ){
String name = "";
name = JoptionPane.showInputDialog("Please enter your name");
String msg = "Hello " + name + "!";
JOptionPane.showMessageDialog(null, msg);
} }
CPCS-202 - The Lab Note
Lab. 3
15
Term I
2012
LAB 3: ELEMENTRY PROGRAMMING
EXERCISES:
1. Lesson 2-4 focuses on constructing an interactive dialog with a user. Each
exercise asks you to fill in parts of a code segment. The last exercise asks you
to put all the parts together into an application. The code segments for
Exercises 1 through 4 are in file CodeSegments.
Exercise 1: Fill in the blanks in the following code segment.
________ in = new Scanner(______________);
System.out.println("Enter name:");
name = ________________________;
Exercise 2: Fill in the blanks in the following code segment.
System.out.___________("Enter message:");
message = ______________;
Exercise 3: Fill in the blanks in the following code segment.
System.out.println("Hello " + _________);
System.out.println(____________);
Exercise 4: Fill in the blanks in the following heading for method main.
public static void main(_________________)
Exercise 5: Declare the variables needed for this application.
Exercise 6: Fill in the pieces from Exercises 1-5 into TestMessage.java.
Compile and run application TestMessage. Show your input and what was
printed.
import java.util.Scanner;
public class TestMessage
{
// Fill in the body using results of Exercises 1-5
}
CPCS-202 - The Lab Note
Lab. 3
16
Term I
2012
LAB 3: ELEMENTRY PROGRAMMING
2. Which of the following identifiers are valid? Which are Java keywords?
applet, Applet, a++, ––a, 4#R, $4, #44,
apps, class, public, int, x, y, radius
3. Translate the following algorithm into Java code:
Step 1: Declare double variable named miles with initial value 100;
Step 2: Declare a double constant named MILES_PER_KILOMETER with value 1.609;
Step 3: Declare a double variable named kilometers, multiply miles and
MILES_PER_KILOMETER, and assign the result to kilometers.
Step 4: Display kilometers to the console. What is a kilometer after Step 4?
4. Identify and fix the errors in the following code:
public class Test {
public void Main(string[] args) {
int i;
int k = 100.0;
int j = i + 1;
System.out.println("j is " + j + " and k is " + k);
}
CPCS-202 - The Lab Note
Lab. 3
17
Term I
2012
LAB 3: ELEMENTRY PROGRAMMING
5. Write a class called TimeConvert, which when executed, prompts the user for to
enter a Number of seconds, and then it prints out the equivalent number of days,
hours, and minutes. You do not have to worry about excess seconds.
A sample run is given below.
Enter total number of Seconds:
84939
84939 second is equal to:
0 day
23 Hours
35 minutes
[Hint: Use the Scanner class to read input from the command console]
6. Write a program in Java to interchange values of two variables without using the
third variable. If A=10 , B=20 after interchange A=20, B=10
7. Write a program that reads an integer between 0 and 1000 and adds all the digits in
the integer. For example, if an integer is 932, the sum of all its digits is 14. [Use the %
operator to extract digits, and use the / operator to remove the extracted digit. For
instance, 932 % 10 = 2 and 932 / 10 = 93]
CPCS-202 - The Lab Note
Lab. 3
18
Term I
2012
LAB 3: ELEMENTRY PROGRAMMING
8. Using JOptionPane, ask for three words from the user and output those three words
on the screen. For example,
CPCS-202 - The Lab Note
Lab. 3
19