In Java, the symbol + can be used to add numbers or to concatenate strings. This exercise illustrates both uses.

Similar documents
Interactive Programs and Graphics in Java

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Introduction to Java. CS 3: Computer Programming in Java

Chapter 2: Elements of Java

Introduction to Java Applets (Deitel chapter 3)

AP Computer Science Static Methods, Strings, User Input

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

Using Files as Input/Output in Java 5.0 Applications

Characteristics of the Four Main Geometrical Figures

Basics of Java Programming Input and the Scanner class

Basic Math for the Small Public Water Systems Operator

Chapter 3. Input and output. 3.1 The System class

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Introduction to Programming

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Install Java Development Kit (JDK) 1.8

Object-Oriented Programming in Java

Java CPD (I) Frans Coenen Department of Computer Science

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Building Java Programs

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

Java Basics: Data Types, Variables, and Loops

Building Java Programs

6.1. Example: A Tip Calculator 6-1

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Part 1 Foundations of object orientation

Interactive Applications (CLI) and Math

Some Scanner Class Methods

Lab 5: Bank Account. Defining objects & classes

AP Computer Science Java Mr. Clausen Program 9A, 9B

FREE FALL. Introduction. Reference Young and Freedman, University Physics, 12 th Edition: Chapter 2, section 2.5

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

Introduction to Java

Programming Fundamentals I CS 110, Central Washington University. November 2015

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

(Eng. Hayam Reda Seireg) Sheet Java

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Lesson 21. Circles. Objectives

Sample CSE8A midterm Multiple Choice (circle one)

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

LAB4 Making Classes and Objects

CS170 Lab 11 Abstract Data Types & Objects

Part I. Multiple Choice Questions (2 points each):

Calculating Perimeter

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Chapter 1 Java Program Design and Development

Arrays in Java. Working with Arrays

Chapter One Introduction to Programming

Appendix K Introduction to Microsoft Visual C++ 6.0

GAP CLOSING. 2D Measurement. Intermediate / Senior Student Book

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Building Java Programs

Chapter 2 Elementary Programming

Topic 11 Scanner object, conditional execution

CALCULATING THE AREA OF A FLOWER BED AND CALCULATING NUMBER OF PLANTS NEEDED

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION

Perimeter is the length of the boundary of a two dimensional figure.

PROG0101 Fundamentals of Programming PROG0101 FUNDAMENTALS OF PROGRAMMING. Chapter 3 Algorithms

The small increase in x is. and the corresponding increase in y is. Therefore

Programming in Java Course Technology, a part of Cengage Learning.

16 Circles and Cylinders

Geometry Solve real life and mathematical problems involving angle measure, area, surface area and volume.

Kristen Kachurek. Circumference, Perimeter, and Area Grades Day lesson plan. Technology and Manipulatives used:

Dŵr y Felin Comprehensive School. Perimeter, Area and Volume Methodology Booklet

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

GAP CLOSING. 2D Measurement GAP CLOSING. Intermeditate / Senior Facilitator s Guide. 2D Measurement

TUTORIAL 4 Building a Navigation Bar with Fireworks

Inv 1 5. Draw 2 different shapes, each with an area of 15 square units and perimeter of 16 units.

UML Class Diagrams (1.8.7) 9/2/2009

Surface Area Quick Review: CH 5

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

Chapter 2 Introduction to Java programming

SMART Board Menu. Full Reference Guide

Excel -- Creating Charts

Manual For Using the NetBeans IDE

Here's the code for our first Applet which will display 'I love Java' as a message in a Web page

Calculating Area, Perimeter and Volume

Programming Languages CIS 443

In this Chapter you ll learn:

2 Getting Started with jgrasp 2.0

Objective To introduce a formula to calculate the area. Family Letters. Assessment Management

The Basic Java Applet and JApplet

Area of a triangle: The area of a triangle can be found with the following formula: in

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

GAP CLOSING. Volume and Surface Area. Intermediate / Senior Student Book

Calculating the Surface Area of a Cylinder

Worksheets for Teachers. The Lowry

Section 7.2 Area. The Area of Rectangles and Triangles

Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Concepts/Skills. Materials

Transcription:

Chapter 2: Data and Expressions Lab Exercises Two Meanings of Plus In Java, the symbol + can be used to add numbers or to concatenate strings. This exercise illustrates both uses. When using a string literal (a sequence of characters enclosed in double quotation marks) in Java the complete string must fit on one line. The following is NOT legal (it would result in a compile-time error). System.out.println ("It is NOT okay to go to the next line in a LONG string!!!"); The solution is to break the long string up into two shorter strings that are joined using the concatenation operator (which is the + symbol). This is discussed in Section 2.1 in the text. So the following would be legal System.out.println ("It is OKAY to break a long string into " + "parts and join them with a + symbol."); So, when working with strings the + symbol means to concatenate the strings (join them). BUT, when working with numbers the + means what it has always meant add! 1.Exercise a. Open a new java file. Save the empty file as: PlusTest.java. Step1. Start writing the text below in the file. Start by writing the class header and empty body as: public class PlusTest // this is a empty class, do nothing but tell the compiler that this is going to be a java file Compile it! If nothing wrong continue to the next step. If you have compiling errors than you have to review your text. Try to understand the message from the COMPILER!! Step2. Put the empty main method into the class. Then your code should look like below. public class PlusTest public static void main (String[] args) // do nothing.. // this is a empty main method. Meens that this class, do nothing but tell the compiler that this is going to be a java program

Compile this file? Errors? How many? Correct the text until you eliminate all errors. Run this main! What happen? Step3. Fill the main method with the first two print lines from the text below. What is wrong? Correct it. Step4. Fill the other 3 lines in your main method. Explain for your lab colleague sitting next to you why the print is different. public class PlusTest public static void main (String[] args) System.out.println ("This is a long string that is the " + "concatenation of two shorter strings."); System.out.println ( My name is : + Kalle?? + Svensson?? + and I am 21 years old ); System.out.println ("8 plus 5 is " + 8 + 5); System.out.println ("8 plus 5 is " + (8 + 5)); System.out.println (8 + 5 + " equals 8 plus 5."); Area and Circumference of a Circle Study the program below, which uses both variables and CONSTANTS: public class Circle public static void main(string[] args) final double PI = 3.14159; int radius = 10; double area = PI * radius * radius; System.out.println("The area of a circle with radius " + radius + " is " + area); radius = 20; area = PI * radius * radius; System.out.println("The area of a circle with radius " + radius + " is " + area); Some things to notice:

The first three lines inside main are declarations for PI, radius, and area. Note that the type for each is given in these lines: final double for PI, since it is a floating point constant; int for radius, since it is an integer variable, and double for area, since it will hold the product of the radius and PI, resulting in a floating point value. These first three lines also hold initializations for PI, radius, and area. These could have been done separately, but it is often convenient to assign an initial value when a variable is declared. The next line is simply a print statement that shows the area for a circle of a given radius. The next line is an assignment statement, giving variable radius the value 20. Note that this is not a declaration, so the int that was in the previous radius line does not appear here. The same memory location that used to hold the value 10 now holds the value 20 we are not setting up a new memory location. Similar for the next line no double because area was already declared. The final print statement prints the newly computed area of the circle with the new radius. 2. Modify your program as follows: At the very top of the file, add the line import java.util.scanner; This tells the compiler that you will be using methods from the Scanner class. In the main method create a Scanner object called scan to read from System.in. Scanner scan=new Scanner(System.in); // mjukvaru förbindelse mellan tangentbordet System.in och ditt programfil. Instead of initializing the radius in the declaration, just declare it without giving it a value. Now add two statements to read in the radius from the user: A read statement that actually reads in the value. Since we are assuming that the radius is an integer, this will use the nextint() method of the Scanner- object ( called scan in your case) radius = scan.nextint(); // Den här raden använder scan objektet ( förbindelsen scan ) och sitt metod nextint() som transporterar värdet du skvev in från tangentbordet ditt program Compile and run your program. Painting a Room File Paint.java contains the partial program below, which when complete will calculate the amount of paint needed to paint the walls of a room of the given length and width. It assumes that the paint covers 95 square meter per liter //*************************************************************** //File: Paint.java // //Purpose: Determine how much paint is needed to paint the walls //of a room given its length, width, and height //*************************************************************** import java.util.scanner; public class Paint public static void main(string[] args) final int COVERAGE = 12; //paint covers 12 sq meter/liter //declare integers length, width, and height;

//declare double totalsqm; //declare double paintneeded; //declare and initialize Scanner object //Prompt for and read in the length of the room //Prompt for and read in the width of the room //Prompt for and read in the height of the room //Compute the total square meter to be painted--think //about the dimensions of each wall //Compute the amount of paint needed //Print the length, width, and height of the room and the //number of liters of paint needed. Save this file to your directory and do the following: 1. Fill in the missing statements (the comments tell you where to fill in) so that the program does what it is supposed to. Compile and run the program and correct any errors. 2. Suppose the room has doors and windows that don't need painting. Ask the user to enter the number of doors and number of windows in the room, and adjust the total square meter to be painted accordingly. Assume that each door is 2 square meter and each window is 1.5 square meter. Average Now you will do everything by your self from the beginning. Start by open a new java file. Save it as Averge.java. In your class write a programme ( main method) that reads two integers ( using a Scanner object) and prints their average. You should use 2 variables, tal1, tal2, declared as int and average declare as double Important! Test your programme usig the value 3 and 2 for the variables tal1 and tal2. Be sure the average is 1.5 and not 1. Note! Remember about type casting, it may be useful. Ideal Weight (BMI) Write a program to compute the BMI for both males and females. According to one study, the BMI is counted as: weight( kg) / length* length (m). For example, the BMI for a person 70 kg and 1,68 cm will be about 25 ( 70/ 1.68*1.68). Your program should ask the user to enter his/her height and his/her weight. It should then compute and print the BMI. The general outline of your main function would be as follows: Declare your variables (think about what variables you need you need to input two pieces of information (what?), then you need some variables for your calculations (see the following steps) Get the input (height in meter) from the user

Compute the BMI Print the answers Plan your program, then type it in, compile and run it. Be sure it gives correct answers. Calories Open a new java file and class and name it Calories. Save in a file Calories.java One way to measure the amount of energy that is expended during exercise is to use the metabolic equivalents (MET). Here are some METS for various activities: Running Basketball Sleeping 10 METS 8 METS 1 MET The number of calories burned per minute may estimate using the formula: Calories/Minute= 0.0175*MET*weight in kg. a) Write a programme that calculate and outputs the total number of calories burned for a 75 kg person who runs for 30 minutes, play basket for 30 minutes and then sleep for 6 hours. b) Now you will make your programme more general. Change the programme so the user will input his/hers values for weight, different activities METS and sleep hours. Time a) Write an application that reads values representing a time duration in hours minutes and seconds, and then prints the equivalent total number of seconds. b) Create a revised version of the previous program that reverse the computation. That is, read a value representing the number of seconds, than print the equivalent amount of time as a combination of hours, minutes and seconds. For example, 9999 seconds is 2 hours, 46 minutes and 39 seconds. Drawing Shapes The following is a simple applet that draws a blue rectangle on a yellow background. import javax.swing.japplet; import java.awt.*; public class Shapes extends JApplet public void paint (Graphics page) shape // Declare variables int x, y; // x and y coordinates of upper left-corner of each

int width, height; // width and height of each shape // Set the background color setbackground (Color.yellow); // Set the color for the next shape to be drawn page.setcolor (Color.blue); // Assign the corner point and width and height x = 200; y = 150; width = 100; height = 70; // Draw the rectangle page.fillrect(x, y, width, height); Study the code, noting the following: The program imports javax.swing.japplet because this is an applet, and it imports java.awt.* because it uses graphics. There is no main method instead there is a paint method. The paint method is automatically invoked when an applet is displayed, just as the main method is automatically invoked when an application is executed. Most of the methods that draw shapes (see the list in Figure 2.12) require parameters that specify the upper left-hand corner of the shape (using the coordinate system described in Section 2.9) and the width and height of the shape. You can see this in the calls to fillrect, which draws a rectangle filled with the current foreground color. 1. Compile Shapes.java, but don't run it this is an applet, so it is run through a browser or a special programs. 2. Run the program through the jgrasp by using the strawberry button which is actually the run applet for current file button. 4. Now change the width to 200 and the height to 300. Save, recompile and run to see how this affects the rectangle. 5. Modify the program so that it draws four rectangles in all, as follows: One rectangle should be entirely contained in another rectangle. One rectangle should overlap one of the first two but not be entirely inside of it. The fourth rectangle should not overlap any of the others. 6. One last touch to the program... Change the colors for at least three of the shapes so the background and each of the three shapes are different colors (a list of colors is in Figure 2.10 of the text). Also change two of the fillrect methods to filloval so the final program draws two rectangles and two ovals. Be sure that the overlap rules are still met. Creating a Pie Chart Write an applet that draws a pie chart showing the percentage of household income spent on various expenses. Use the percentages below: Rent and Utilities 35% Transportation 15% Food 15% Educational 25% Miscellaneous 10%

Each section of the pie should be in a different color, of course. Label each section of the pie with the category it represents the labels should appear outside the pie itself. Tip! Use the method fillarc(), se the course book or java doc, class Graphics.