COMP 110 Project 1 Programming Project Warm-Up Exercise

Similar documents
Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

2.8. Decision Making: Equality and Relational Operators

Computer Hardware. Java Software Solutions Lewis & Loftus. Key Hardware Components 12/17/2013

Full file at

First Java Program - Output to the Screen

Introduction to Java Applications; Input/Output and Operators

Introduction to Software Development (ISD) David Weston and Igor Razgon

Programming for Engineers Introduction to C

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Chapter 2: Programming Concepts

Section 2.2 Your First Program in Java: Printing a Line of Text

CS125 : Introduction to Computer Science. Lecture Notes #4 Type Checking, Input/Output, and Programming Style

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

STUDENT LESSON A7 Simple I/O

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

Java Bytecode (binary file)

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

4 Programming Fundamentals. Introduction to Programming 1 1

CS 177 Recitation. Week 1 Intro to Java

Lab # 2. For today s lab:

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

What did we talk about last time? Examples switch statements

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

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Course Outline. Introduction to java

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

Lesson 1: Writing Your First JavaScript

Chapter 2: Data and Expressions

CPS109 Lab 1. i. To become familiar with the Ryerson Computer Science laboratory environment.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Programming with Java

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Oct Decision Structures cont d

Introduction to Java Applications

Introduction to Java. Java Programs Classes, Methods, and Statements Comments Strings Escape Sequences Identifiers Keywords

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to

CS 106 Introduction to Computer Science I

Chapter 2, Part I Introduction to C Programming

Section 2.2 Your First Program in Java: Printing a Line of Text

STUDENT LESSON A12 Iterations

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Programming Exercise 7: Static Methods

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 2: SEP. 8TH INSTRUCTOR: JIAYIN WANG

2.5 Another Application: Adding Integers

Full file at

CSCI 161: Introduction to Programming I Lab 1b: Hello, World (Eclipse, Java)

CPS122 Lecture: From Python to Java

Fundamentals of Programming. By Budditha Hettige

Introduction to Java & Fundamental Data Types

Week 2: Data and Output

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

COMP 202 Java in one week

(Refer Slide Time: 01:12)

St. Edmund Preparatory High School Brooklyn, NY

CMSC 150 LECTURE 1 INTRODUCTION TO COURSE COMPUTER SCIENCE HELLO WORLD

4 WORKING WITH DATA TYPES AND OPERATIONS

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

Welcome to the Primitives and Expressions Lab!

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Chapter 1 Lab Algorithms, Errors, and Testing

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

for (i=1; i<=100000; i++) { x = sqrt (y); // square root function cout << x+i << endl; }

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Chapter 2: Data and Expressions

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Chapter 1. Introduction

AP CS Unit 3: Control Structures Notes

Darrell Bethea May 10, MTWRF 9:45-11:15 AM Sitterson 011

4. Java Project Design, Input Methods

CS 231 Data Structures and Algorithms, Fall 2016

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

Darrell Bethea May 25, 2011

download instant at

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

CHAD Language Reference Manual

4. Structure of a C++ program

Basic Computation. Chapter 2

Fundamentals of Programming Session 4

Software and Programming 1

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

2 Getting Started. Getting Started (v1.8.6) 3/5/2007

Faculty of Science Midterm. COMP-202B - Introduction to Computing I (Winter 2008)

C++ Style Guide. 1.0 General. 2.0 Visual Layout. 3.0 Indentation and Whitespace

Perl Basics. Structure, Style, and Documentation

Lec 3. Compilers, Debugging, Hello World, and Variables

Algorithms and Programming I. Lecture#12 Spring 2015

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Elementary Programming

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

CS11 Java. Fall Lecture 1

Transcription:

COMP 110 Project 1 Programming Project Warm-Up Exercise Creating Java Source Files Over the semester, several text editors will be suggested for students to try out. Initially, I suggest you use JGrasp, however, you are free to use whatever editor you prefer. 1. Launch JGrasp application. 2. Create a new Java source file: File New Java. 3. Type your Java program into the source file window. 4. Save the file: File Save (file is saved to your Z drive, or network drive). 5. Compile the file: Build Compile. 6. Read the messages in the status window at the bottom. If there are errors, you must correct them and recompile. 7. Run the compiled program: Build Run. 8. Read the output in the status window to confirm that your output is correct. If not, modify your program, recompile, and rerun. Java Background A Java program is ASCII text entered using a text editor such as Notepad or Emacs and saved to an ASCII text file with filename extension.java (you cannot use the default.txt extension). Such a file is called a Java source file. The source file is converted to an executable form by use of Java software development applications or tools called the Java compiler (javac) and the Java interpreter (java). The text of the source file is organized according to the syntactical rules of the Java language. The general organization of any Java source file is as follows: Inside each Java source file, there will be one or more class definitions. Within each class definition, there will be one or more method definitions. Within each method, there will be a series of statements. Each statement is a command to the computer to perform some operation on the data or information being processed by the program or application. A statement is analogous to an English sentence. It represent a single thought or command. Statements are grouped together into related sets called methods. A method is analogous to a paragraph. All the statements in a method work together as a unit to accomplish a single task or compute a single value. Next, multiple methods are grouped together into classes. A class is like a chapter. Finally, a complete Java program is organized at the highest level as a group of class definitions. There are many options for storing class definitions into files. Some programmers put each class definition into its own separate source file. Others put multiple classes into a single file. You will be given guidelines on the best organizational style as the course proceeds. General Java Source File Syntax Java programs are case sensitive. Upper and lower case are not interchangeable. Java programs use many punctuation characters than come in matching pairs. " double quote o Used to delimit String constants "this is a string" ' single quote o Used to delimit character constants 'a' 'b' 'X' 'Y' '3' ( ) parentheses o Used for grouping parts of expressions to control precedence 3 + 4 * 5 multiply before add (3 + 4) * 5 add before multiply o Also used to indicate input parameter lists to methods o double v = Math.exp(3,2) { curly braces/brackets o Used to group lists of statements into larger units. [ ] square brackets o Used to identify to array indices. int []x = new int[10]; x[3] = 5; Grouping characters are also subject to rules for nesting and balance.

Other Punctuation ; or semicolon Indicates the end of statement, similar to a period. at the end of an English sentence. Note: semicolons appear at the end of most statements, but since some statements are spread over multiple lines, you will not necessarily see a semicolon at the end of every line., or comma Separates items in a list, such as input parameters to a method call. Math.exp(2.0,3.0);. or period Separates the name of an object or class from a member of that object or class System.out.print + - * / % += -= *= /= %= ++ -- Indicates arithmetic operations (or arithmetic-assignment combos) = or assignment Indicates assignment of a value to a variable ==!= > >= < <= Indicates comparisons &&! Indicates logical operations Source File Style: Indentation, White Space, Comments Strictly speaking, the Java compiler does not distinguish between a Java source file that is pretty in contrast to a source file that is sloppy. However, your grader cares very much. For this reason, you will be required to correctly format your source files using correct techniques for indentation, white space, and comments. Indentation The elements of a Java source file are arranged in a hierarchical fashion, as described above: statements are organized into methods, and methods are organized into classes. Curly brackets are used to indicate the starting and stopping point of both classes and methods, and for other groupings within methods called compound statements. In order to keep the hierarchy of such elements clear to the reader of your program, you will be required to use the following indentation rules. Start typing on the left margin of the source file If a line ends with a left curly bracket, the next line (and all subsequent lines) are indented by one tab to the right. Since elements may be nested, indentation will continue to move to the right by one tab every time another left curly bracket is entered. Sometime later in the file after a left curly bracket has been entered, the corresponding or matching right curly bracket will appear. The right curly bracket appears on a line by itself, and the indentation of this line is moved back to the left by one tab, relative to the previous line. Following these rules, whenever a Java source file is created, the typing starts at the left margin, some number of left and right curly brackets are entered, and since the number of left and right curly brackets must match, the typing of the program will return all the way to the left margin, just in time for the last right curly bracket, which will be on the last line of the file by itself. Text will appear to shift left and right as one reads a Java source file from top to bottom. One potential problem with indentation is for complex programs that use a high degree of nesting of curly brackets. In such programs, it is possible that indentation may push so far to the right that the program runs far beyond the normal right margin boundary of a typical printed page. This is not necessarily a problem when accessing the file using the text editor. But it becomes a big problem if you need to print a hard copy of the file. This problem is sometimes called word wrap or line wrap. If line wrap occurs when you print out a Java source file, the correct indentation structure of the file is obscured, and the printed result has an unacceptable amateurish look. The instructor will give examples of how to avoid this problem in later examples. 2

White Space There are many cases when white space (ie, the space character, the tab character, and/or the newline character) must be entered into a program to create a separation between program elements in order for the program to compile (ie such white space is required, not optional). In other cases, white space should be used even when it is not required, in order to make the program more readable. Example (x+y*z)/((2*a-1)*(4*b*b+c)) no white space, not required, but hard to read (x + y*z) / ((2*a - 1) * (4*b*b + c)) white space added for readability Comments Comments are remarks that are typed into the source file only for documentation purposes. They must be marked so that the compiler will not try to compile them as if they were part of the Java code Comment Style 1: Double slash // As the compiler reads a line of the source file from left to right, as soon as it encounters a double slash, the rest of the line is treated as a comment. x = 3; // initialize the value of x to 3 Comment Style 2: Slash-star and Star-slash /* */ This style of comment is useful for multi-line comments. The comment starts whenever the /* character combo is encountered. The comment continues over multiple lines until the */ character combo is encountered. x = 3; x = x + 1; /* this is a multi-line comment that can extend over multiple lines */ Although the presence or absence of comments by definition has no effect on the computer s compilation and execution of your program, they are nevertheless a required part of any non-trivial program. They quickly and clearly explain to a human reader of the program details regarding how the program works, without the reader having to laboriously study the code to understand it. Comments must be written at the correct level of detail. Using no comments at all is a sign of a lack of consideration and professionalism, and too many comments will annoy the reader. The best balance is to have a few lines of comments for every major section of the code. A good rule of thumb would be to have a little explanation for each block of 10 statements or so. 3

Part I: Hello, world! This exercise introduces you to the tools and procedures you will use to write Java programs and convert them into executable software applications. This program creates an extremely simple application called Hello, world!. It s not useful in a practical sense, but is a good place to start for getting some practice in using the Java development tools. Step 1: Logon, launch JGrasp, and open a new Java source file (as described above). Step 2: Type the following text into the file: public class Hello { public static void main(string[] args) { System.out.println("Hello, world!"); Step 3: Save the file. Step 4: Compile the file. Step 5: Run or execute the file. Brief Explanation of Hello.java The structure of the Hello.java file consists of a single class definition of a class named Hello. Inside the class is a single method named main. Finally, inside main is a single statement that prints a message to the screen. In simplified form the structure looks like this: The class definition: class Hello { method definitions go here The method definition: main { statements go here The output statement: System.out.println( message goes here ); These elements must be correctly nested, and indented according to proper style. The result will then look more like this: class Hello { main { System.out.println( ); By placing the curly brackets as shown, it becomes easier to read the Java program and understand its structure. In addition to the basic structure, a complete Java program requires correct use of certain adjectives called keywords, such as public, static, void, etc. These will be explained shortly, but in the meantime, you will simply have to enter them into your file as shown in the example. Output Inside a Java program, in order to issue a command to the computer to place information on the display, use the command System.out.print or System.out.println. The structure of the command is as follows: System.out.println("some message in the form of a String"); This command will copy the contents of the String (the text inside the double quotes) exactly as written to the display and will then add a newline or carriage return character to return the prompt to the left margin. To omit the newline, use the System.out.print command instead. 4

Part II: Customized Hello, World! This program is a more complex version of the Hello.java program from Part I. Here, the user will interact with the program by typing in or inputting their first name, and then receiving a customized greeting from the application. Repeat the steps from Part I, except that the name of the class is now CustomHello, and the name of the source file is CustomHello.java. The file to be entered is as follows: import java.util.*; public class CustomHello { public static void main(string [] args) { Scanner in = new Scanner(System.in); String myname = null; System.out.print("Please enter your name: "); myname = in.next(); System.out.println("Hello, " + myname + "!"); Explanation To receive input into a Java program, the program must create something called a Scanner. The Scanner is an abstraction that represents the keyboard. This program creates a Scanner and calls it in. Other names could have been picked, but I like this one because it s simple and easy to remember. In the textbook, the name keyboard is frequently chosen. We add an import statement at the top of the file to tell the compiler where the definition of Scanner can be found. Now that the Scanner has been created, we can use it to obtain input from the keyboard. In this program there is only one input, the user s name. If the program is to receive input, there must be a storage cell created by the program to hold the input in memory until it is needed. We create a String variable called myname to hold the input. We use the System.out.print command to place a prompt to the user on the screen. We then obtain the input by using the in.next() command. Note that the in part comes from the name of the Scanner we chose earlier. Once the name has been input, we re ready to output the customized greeting. We use the System.out.print command again, but this type we must glue or append together a String from three different pieces. The plus sign + in this situation is a command to append one String to another String. 5

Part III: Integer Addition We conclude the warm-up by showing how to input numerical information into a Java application. This program asks the user to enter two integers. The program then adds the numbers together and prints out the result. Obviously, it is still a very simple program, but it introduces a few more useful Java programming techniques that you ll use repeatedly. Repeat the steps above to write a Java class named Addition, saved to a source file named Addition.java. The content of the file is as follows: import java.util.*; public class Addition { public static void main(string[] args) { Scanner in = new Scanner(System.in); int n1, n2, sum; System.out.print("Enter the first integer: "); n1 = in.nextint(); System.out.print("Enter the second integer: "); n2 = in.nextint(); sum = n1 + n2; System.out.println("The sum of the values is " + sum); Explanation The only new feature of this application is the new command in.nextint(). This demonstrates that the Scanner (named in ) is capable of receiving different types of input from the keyboard. The in.next() command receives the input from the keyboard in the form of a textual string. The in.nextint() command receives the input in the form of an integer. The programmer defines the order and type of inputs that the program will expect when it runs. If the command receives a type of input not compatible with what it was expecting, the program may fail. 6

Part IV: Quadratic Polynomial Evaluation This part is optional, for students who quickly finish the first three parts. It is a preview of a later lab dealing with polynomial evaluation in more detail. Write and test a program to prompt the user to enter a quadratic polynomial and value of x, then evaluate the polynomial at that value of x and print out the result. A quadratic polynomial has the form f(x) = y = ax 2 + bx + c Therefore, your program needs 5 symbols or variables: a, b, c, x, and y. The first four symbols are inputs, whose values must be entered from the keyboard by the user when the program runs. The last symbol is the result, whose value is computed by the program from the inputs and is then printed out to the display. For testing purposes, here are some example values. Compare your program s results with these to confirm that your program is working correctly. f(x) = y = 2.5 x 2 + 5 x 7 X y = f(x) -5 30.5-4 13-3 0.5-2 -7-1 -9.5 0-7 1 0.5 2 13 3 30.5 4 53 f(x) = y = 0.5 x 2-18 x + 3.2 X y = f(x) -5 105.7-4 83.2-3 61.7-2 41.2-1 21.7 0 3.2 1-14.3 2-30.8 3-46.3 4-60.8 7