Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Laboratory 3: Course Code: CPCS-202 Course Name: Programming I Introduction: The purpose of this Lab. is to familiarize you how to solve practical problems programmatically; you will practice on elementary programming using primitive data types, variables, constants, operators, expressions, and input and output. Also, you will learn how to diagnose errors that may occur when a program is compiled or executed. Objective: This lab teaches you the following topics. ■To write Java programs to perform simple calculations (§2.2). ■ To obtain input from the console using the Scanner class (§2.3). ■ To use identifiers to name variables, constants, methods, and classes (§2.4). ■ To use variables to store data (§§2.5–2.6). ■ To program with assignment statements and assignment expressions (§2.6). ■ To use constants to store permanent data (§2.7). ■ To declare Java primitive data types: byte, short, int, long, float, double, and char (§2.8.1). ■ To use Java operators to write numeric expressions (§§2.8.2–2.8.3). ■ To use shorthand operators (§2.10). ■ To cast the value of one type to another type (§2.11). ■ To represent a string using the String type (§2.15). ■ To distinguish syntax errors, runtime errors, and logic errors and debug errors (§2.17). ■ (GUI) To obtain input using the JOptionPane input dialog boxes (§2.18). 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. 1 Solution1: 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. /* 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 2 System.out.println("After Swap Number 1 =" + num1 + " Number 2= "+ num2); } } Activity 2: 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. 3 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 3 // 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 } } // 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); }} 4 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 4: 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. 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 5 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; // 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); } } 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. 6 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 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! Another way to convert between variables is using some defined methods that converts between variables. 7 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. Activity 5: 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. 8 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); } } Home Activities: (One week to submit) 1. Which of the following identifiers are valid? Which are Java keywords? applet, Applet, a++, ––a, 4#R, $4, #44, 9 apps, class, public, int, x, y, radius 2. 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); } 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 10 [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] 8. 9. Using JOptionPane, ask for three words from the user and output those three words on the screen. For example, 11 Lab Report: The laboratory report of this lab (and also all the following labs in this manual) should include the following items/sections: - A cover page with your name, course information, lab number and title, and date of submission. - A summary of the addressed topic and objectives of the lab. - Implementation: a brief description of the process you followed in conducting the implementation of the lab scenarios. - Results obtained throughout the lab implementation, the analysis of these results, and a comparison of these results with your expectations. - Answers to the given exercises at the end of the lab. If an answer incorporates new graphs, analysis of these graphs should be included here. - A conclusion that includes what you learned, difficulties you faced, and any suggested extensions/improvements to the lab. 12