Scope, Comments, Code Style, Keyboard Input

Slides:



Advertisements
Similar presentations
Today’s lecture Review of Chapter 1 Go over homework exercises for chapter 1.
Advertisements

CS0007: Introduction to Computer Programming Console Output, Variables, Literals, and Introduction to Type.
CS0007: Introduction to Computer Programming
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
Introduction to Primitives. Overview Today we will discuss: –The eight primitive types, especially int and double –Declaring the types of variables –Operations.
11 Chapter 5 METHODS. 22 INTRODUCTION TO METHODS A method is a named block of statements that performs a specific task. Other languages use the terms.
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
1 Chapter 2 JAVA FUNDAMENTALS CONT’D. 2 PRIMITIVE DATA TYPES Computer programs operate on data values. Values in Java are classified according to their.
CS0007: Introduction to Computer Programming Scope, Comments, Code Style, Keyboard Input.
Week 2 - Friday.  What did we talk about last time?  Data representation  Binary numbers  Types  int  boolean  double  char  String.
© The McGraw-Hill Companies, 2006 Chapter 1 The first step.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Simple Programs from Chapter 2 Putting the Building Blocks All Together (corresponds with Chapter 2)
JAVA BASICS: Variables and References SYNTAX, ERRORS, AND DEBUGGING.
Java Fundamentals 3 Input and Output statements. Standard Output Window Using System.out, we can output multiple lines of text to the standard output.
CHAPTER 3 GC Java Fundamentals. 2 BASICS OF JAVA ENVIRONMENT  The environment  The language  Java applications programming Interface API  Various.
Chapter 2: Java Fundamentals
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
A First Look at Java Chapter 2 1/29 & 2/2 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010.
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals. Procedural Constructs.
Can we talk?. In Hello World we already saw how to do Standard Output. You simply use the command line System.out.println(“text”); There are different.
CMSC 202 Java Console I/O. July 25, Introduction Displaying text to the user and allowing the user to enter text are fundamental operations performed.
CS0007: Introduction to Computer Programming Classes: Documentation, Method Overloading, Scope, Packages, and “Finding the Classes”
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Lecture 4 – Scanner & Style. Console Output The console that starts a Java application is typically known as the standard output device. The standard.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Java – Variables and Constants By: Dan Lunney. Declaring Variables All variables must be declared before they can be used A declaration takes the form:
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC 110 – INTRO TO COMPUTING - PROGRAMMING String and Scanner Objects.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Elementary Programming.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
2.1 The Part of a C++ Program. The Parts of a C++ Program // sample C++ program #include using namespace std; int main() { cout
Lecture 4 – Scanner & Style
CompSci 230 S Programming Techniques
Chapter 2 Basic Computation
CS0007: Introduction to Computer Programming
Chapter 3 GC 101 Java Fundamentals.
Console Output, Variables, Literals, and Introduction to Type
Introduction to Computer Science / Procedural – 67130
Yanal Alahmad Java Workshop Yanal Alahmad
Variables, Expressions, and IO
Type Conversion, Constants, and the String Object
Intro to PHP & Variables
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 2 Basic Computation
Program Style Console Input and Output
Type Conversion, Constants, and the String Object
2.1 Parts of a C++ Program.
Introduction to C++ Programming
Chapter 2 Edited by JJ Shepherd
Variables ICS2O.
MSIS 655 Advanced Business Applications Programming
Fundamentals 2.
Defining methods and more arrays
elementary programming
Chapter 2: Introduction to C++.
CS2011 Introduction to Programming I Elementary Programming
Lecture Notes - Week 2 Lecture-1. Lecture Notes - Week 2 Lecture-1.
Introduction to Primitives
Tutorial 10: Programming with javascript
Introduction to Primitives
Primitive Types and Expressions
Unit 3: Variables in Java
Chapter 2: Java Fundamentals cont’d
Chapter 2 Primitive Data Types and Operations
Presentation transcript:

Scope, Comments, Code Style, Keyboard Input CS0007: Introduction to Computer Programming

Review How would I write x = x + y; using combined assignment operators? x += y; How would I increment the variable x? x++; Since Java is a Strongly Typed Language , before a value is assigned to a variable… Java checks the types of the variable and the value being assigned to it to determine if they are compatible. Rank as it applies to type means… that if a type has a higher rank than another, it can hold more numbers, and thus, will not lose any precision.

Review Ranks (Highest to Lowest): double float long int short Byte A Widening Conversion is… a conversion of a value to a higher-ranked type. A Narrowing Conversion is… a conversion of a value to a lower-ranked type. Type Cast Operators allow you to… manually convert from one type to another, even if it is a narrowing conversion.

Review Two advantages of using a named constant: A Named Constant is… If the value of the constant changes, you only need to change the line where the constant was initialized. The name of the constant provides information about what it holds (self-documentation). A String is not a primitive type in Java, it is a… Class A Class Type Variable (reference variable) does not hold the actual value, but... the memory address of the data item it is associated with. A Named Constant is… a variable whose value is read only and cannot be changed during the program’s execution.

Review A String object is not created for a String variable until… The variable is assigned a value String Methods: length() returns the number of characters in the string as an int charAt(index) index is an int value that specifies a character position in the string that is to be returned. The first character is at index 0. Return type is char. toLowerCase() returns a new string that is the lowercase equivalent of the string. toUpperCase() returns a new string that is the uppercase equivalent of the string.

Scope Every variable has scope. Scope refers to where in a program an entity can be accessed by name. A variable is only visible to statements that are inside it’s scope. Scoping rules are complex, we will only discuss a few right now. We’ll add to these later. So far we’ve only seen variables declared inside of the main method. Variables declared inside of a method are called local variables, and have local scope. The scope of a local variable begins where they were declared and ends at the end of the method in which they were declared. Also, you cannot have two local variables with the same name in the same scope

Scope Example //Scope - shows an example of a local variable being used out of its scope // and with another variable with the same name being in the same scope public class Scope { public static void main(String[] args) { x = 11; int x; System.out.println(x); int x = 15; }

Comments Internal Documentation takes the form of Comments in Java. A Comment is… line(s) in a program that is ignored by the compiler entirely. Why do we have comments? Include documentation inside of the code to allow other programmers (or ourselves) to understand what the code does, who wrote it, when, etc. To temporarily make lines of code not executed instead of removing them outright Three kinds of comments in Java Single-Line – begin with // and the entire line is ignored // Here is a comment Multi-Line – begin with /* and end with */, and everything between is ignored /* Here is a comment and it is still going on here */ Documentation Comments – special comments that can be used to make attractively formatted HTML files that document the source code.

Comments Your comments should do three things at this point Give a block comment at the top of the file to give information about the file. In this class I want them to include: Author’s name The course number (CS0007) The date created A short description about what file is and does Give information about what codes does, especially if you are worried the reader will not know what the code does, but even if you think it is obvious. Either goes above the line, or next to it. You can NEVER have too many comments. Cite the source if a small snippet of code is taken from somewhere. Later we will talk more about how to document different constructs as we get to them.

Block Comments There are many styles to making block comments: //////////////////////////////////////// // One Style // Looks like this /////////////////////////////////////// /* * Another * Looks like this */ //-------------------------------------- // Yet another is

Commenting Example /************************************************************* * Author: Eric Heim * Course: CS0007 * Date Created: 5/25/2011 *Description: This file holds the triangle stats program, which computes the * perimeter and area of a triangle with sides of length 2.3, 5.9, and 7.2, then * displays the lengths of the sides, the perimeter and the area to the screen ***********************************************************/ public class Commenting { public static void main(String[] args) { //Declarations for the sides, the perimeter, the area, and the //semiperimeter s double side1 = 2.3, side2 = 5.9, side3 = 7.2, perimeter, s, area; perimeter = side1 + side2 + side3;//Computes the perimeter s = perimeter/2; //Computes the semiperimeter //Computes the area area = Math.sqrt(s * (s - side1) * (s - side2) * (s - side3)); Continued on Next Slide

Commenting Example (Continued) //Displays the triangle's sides, the perimeter, and the area to the screen System.out.print("The lengths of the triangle's sides are " + side1); System.out.println(", " + side2 + ", " + side3 + "."); System.out.println("The perimeter of the triangle is " + perimeter ); System.out.println("The area of the triangle is " + area ); } }

Documentation Comments The Java SDK provides a tool for creating attractive, HTML-based, documentation files for your source code called javadoc. The resulting documentation file can be viewed in any web browser. Any comments that begin with /** and end in */ are considered javadoc comments, and can be used by javadoc. Right, now, this has little use, because our programs are simple, but later they can be used to describe things like the methods and attributes of the classes we make. To run javadoc program on a source code file, simply execute the command: javadoc sourceCodeFile.java

Documentation Comments Example /** *Class that holds the triangle stats program, which * computes the perimeter and area of a triangle * with sides of length 2.3, 5.9, and 7.2, then * displays the lengths of the sides, the perimeter * and the area to the screen. */

Programming Style Programming Style refers to the way a programmer uses spaces, indentation, blank lines, and punctuation characters to visually arrange a program’s source code. This has NOTHING to do with syntax. General Rule: Make your code easy to read. We could write a program like this: public class Compact {public static void main(String [] args){int number = 5; System.out.println(number);}} It even compiles and runs, but its really difficult to read.

Programming Style Rule 1: All statements inside of a block should be indented one tab more than the statements directly outside of the block. public class Neat { public static void main(String [] args) { int number; … } Notice that all lines inside of the public class Neat headed block are tabbed once, and all lines inside of the public static void main… block are tabbed again. Also note that the closing braces are in the same column as their headers.

Programming Style Rule 2: Lines that are wrap onto the next line should be vertically aligned: System.out.println("Here I am going to " + "display a variable " + number); Notice that instead of having the string wrap to the next line, the concatenation operator is used and the string begins where the last one did. Also, if you are commenting variables, do something similar: int fahrenheit, //holds the Fahrenheit temperature celsius, //holds the Celsius temperature kelvin; //holds the Kelvin temperature

Programming Style We’ve also went over some naming conventions: Self-documenting code Classes start with a capital letter Variables start with a lowercase letter Named Constants are all caps with underscores We will add more good programming practices throughout the semester.

Reading Keyboard Input Just like System.out object refers to the standard output device, the Java API provides an object, System.in, that refers to the standard input device. The standard input device is normally the keyboard. Unfortunately, using System.in is not as straight- forward as using System.out System.in reads all input as bytes…which is often not very useful. Fortunately, the Java API provides the Scanner class that allows us to retrieve input as primitive types or strings.

The Scanner Class To create an object from the Scanner class that takes in keyboard input we use the line: Scanner keyboard = new Scanner(System.in); Scanner keyboard declares a variable named keyboard that is type Scanner. Because Scanner is a class, keyboard is a reference variable. = is the assignment operator, so we are initializing the keyboard variable. new is a Java keyword that creates an object in memory, what follows it tells the compiler what object is to be created. Scanner(System.in) tells the compiler that the object to be created is a Scanner object, and it should be associated with standard input. This is called a constructor, and it creates the object in memory. We will talk more about constructors much later in the course. The result is that we have a reference variable, keyboard, that references a scanner object that is associated with standard input.

The Scanner Class Some classes provided by the Java API are not automatically available for use with all programs, and the Java compiler needs to be told where to find them. Scanner is one of these classes. For this reason we must put the following line near the beginning of the file, outside of the class definition: import java.util.Scanner; This tells the compiler where to find the definition for the Scanner class

See Scanner Class Example 1 The Scanner Class The Scanner class provides methods for reading input as different types: nextByte() – Returns input as a byte nextDouble() – Returns input a double nextFloat() – Returns input as a float nextInt() – Returns input as an int nextLine() – Returns input as a String nextLong() – Returns input as a long nextShort() – Returns input as a short When associated with standard input, the user will be able to type characters on their keyboard and finish by pressing enter. The result is then returned as the type specified by the method. See Scanner Class Example 1

The Scanner Class SEE Read Character Example 2 Notice there is no nextChar() method. If you want to take in a single character, you must use the nextLine() method and use charAt(0) to retrieve the first character. SEE Read Character Example 2

The nextLine() method problem. Let’s look at the program InputProblem.java. It didn’t take in the user’s name at all! The problem is that nextLine() works differently than the other Scanner class methods. When the user types keystrokes at the keyboard, those keystrokes are stored in an area of memory sometimes called the keyboard buffer. When the user pressed enter, the new line character is stored in the keyboard buffer. When a user inputs a number for nextInt(), everything the user entered is stored in the keyboard buffer, including the newline character. Then, the value entered by the user is read from the buffer, leaving the newline character still in the buffer. The nextDouble() method is designed so that it skips any leading newline characters it encounters, so when it tries to read the keyboard buffer, it sees the newline from nextInt(), it ignores it. However, when nextLine() encounters the same situation, it is NOT designed to skip leading newline characters and assumes the user has pressed enter, stopping keyboard input.

The newLine() method problem. Solution: If you use another Scanner method before the nextLine() method, simply put another call to nextine() before the one that you want to take the user’s input. Look At Input Problem