CSC 204 - Programming I Lecture 6 September 4, 2002.

Slides:



Advertisements
Similar presentations
L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Advertisements

L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
CS0007: Introduction to Computer Programming Console Output, Variables, Literals, and Introduction to Type.
 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
What Data Do We Have? Sections 2.2, 2.5 August 29, 2008.
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
CMT Programming Software Applications
Mathematical Operators  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming in.
Lecture 3: Strings, Screen Output, and Debugging Yoni Fridman 7/2/01 7/2/01.
Relational Operators Control structures Decisions using “if” statements  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Chapter 2: Writing Java Programs Java Programming FROM THE BEGINNING 1 Chapter 2 Writing Java Programs.
CSCI 1730 January 17 th, 2012 © by Pearson Education, Inc. All Rights Reserved.
Chapter 2: Writing Java Programs Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 2 Writing.
© The McGraw-Hill Companies, 2006 Chapter 1 The first step.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
Android How to Program, 2/e © Copyright by Pearson Education, Inc. All Rights Reserved.
VARIABLES Introduction to Computer Science 1- COMP 1005, 1405 Instructor : Behnam Hajian
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
CNG 140 C Programming Lecture Notes 2 Processing and Interactive Input Spring 2007.
Input, Output, and Processing
CSC Programming I Lecture 5 August 30, 2002.
Intro and Review Welcome to Java. Introduction Java application programming Use tools from the JDK to compile and run programs. Videos at
Chapter 2: Java Fundamentals
Chapter 2: Writing Java Programs Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 2 Writing.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Java basics. Task  Display the supposed forecast I think there is a world market for maybe five computers. Thomas Watson, IBM, 1943.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals. Procedural Constructs -
© 2004 Pearson Addison-Wesley. All rights reserved ComS 207: Programming I Instructor: Alexander Stoytchev
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Chapter 3: Classes and Objects Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved Java’s String Class.
Chapter 2 Variables.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
CSC Programming I Lecture 9 September 11, 2002.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
Debugging, Escape Command, More Math. It’s your birthday!  Write a program that asks the user for their name and their age.  Figure out what their birth.
Chapter 2: Writing Java Programs Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 2 Writing.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
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.
Chapter 2: Writing Java Programs Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 2 Writing.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Chapter 2: Writing Java Programs Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 2 Writing.
Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Class Methods.
Lecture 4 – Scanner & Style
CompSci 230 S Programming Techniques
Yanal Alahmad Java Workshop Yanal Alahmad
2.5 Another Java Application: Adding Integers
Writing Java Programs Chapter 2
Escape Sequences What if we wanted to print the quote character?
Introduction to C++ Programming
Writing Java Programs Chapter 2
MSIS 655 Advanced Business Applications Programming
Writing Java Programs Chapter 2
Writing Java Programs Chapter 2
elementary programming
Writing Java Programs Chapter 2
Unit 3: Variables in Java
Computer Programming-1 CSC 111
Writing Java Programs Chapter 2
Instructor: Alexander Stoytchev
Presentation transcript:

CSC Programming I Lecture 6 September 4, 2002

Input and Output  Most programs require both input and output.  Input is any information fed into the program from an outside source.  Output is any data produced by the program and made available outside the program.

Displaying Output on the Screen  Properties of System.out.print and System.out.println : Can display any single value, regardless of type. The argument can be any expression, including a variable, literal, or value returned by a method. println always advances to the next line after displaying its argument; print does not.

Displaying a Blank Line  One way to display a blank line is to leave the parentheses empty when calling println : System.out.println("Hey Joe"); System.out.println(); // Write a blank line  The other is to insert \n into a string that’s being displayed by print or println : System.out.println("A hop,\na skip,\n\nand a jump"); Each occurrence of \n causes the output to begin on a new line.

Escape Sequences  The backslash character ( \ ) combines with the character after it to form an escape sequence: a combination of characters that represents a single character.  The backslash character followed by n forms \n, the new-line character.

Escape Sequences  Another common escape sequence is \", which represents " (double quote): System.out.println("He yelled \"Stop!\" and we stopped.");  In order to print a backslash character as part of a string, the string will need to contain two backslash characters: System.out.println("APL\\360");

Printing Multiple Items  The + operator can be used to combine multiple items into a single string for printing purposes: System.out.println("Celsius equivalent: " + celsius);  At least one of the two operands for the + operator must be a string.

Obtaining Input from the User  The SimpleIO class (not part of standard Java) simplifies the task of obtaining input.  The SimpleIO.prompt method is first used to prompt the user: SimpleIO.prompt("Enter Fahrenheit temperature: ");  Next, the SimpleIO.readLine method is used to read the user’s input: String userInput = SimpleIO.readLine();

Obtaining Input from the User  If the user’s input represents a number, it will need to be converted to numeric form.  The Convert class (not part of standard Java) provides a toDouble method that converts a string to a double value: double fahrenheit = Convert.toDouble(userInput);  To convert a string to an integer, the Integer.parseInt method is used instead: int n = Integer.parseInt(userInput);

Packages  Java allows classes to be grouped into larger units known as packages.  The package that contains SimpleIO and Convert is named jpb (Java Programming: From the Beginning).  Java comes with a large number of standard packages.

Import Declarations  Accessing the classes that belong to a package is done by using an import declaration: import package-name. * ;  Import declarations go at the beginning of a program. A program that needs SimpleIO or Convert would begin with the line import jpb.*;

Application Programming Interfaces  The packages that come with Java belong to the Java Application Programming Interface (API). In general, an API consists of code that someone else has written but that we can use in our programs. Typically, an API allows an application programmer to access a lower level of software. In particular, an API often provides access to the capabilities of a particular operating system or windowing system.

Program Revisited – Fahrenheit to Celsius FtoC3.java // Converts a Fahrenheit temperature entered by the user to // Celsius import jpb.*; public class FtoC3 { public static void main(String[] args) { final double FREEZING_POINT = 32.0; final double DEGREE_RATIO = 5.0 / 9.0; SimpleIO.prompt("Enter Fahrenheit temperature: "); String userInput = SimpleIO.readLine(); double fahrenheit = Convert.toDouble(userInput); double celsius = (fahrenheit - FREEZING_POINT) * DEGREE_RATIO; System.out.println("Celsius equivalent: " + celsius); }

Case Study – Computing a Course Average  The CourseAverage program will calculate a class average, using the following percentages: Programs30% Quizzes10% Test 115% Test 215% Final exam30%  The user will enter the grade for each program (0–20), the score on each quiz (0–10), and the grades on the two tests and the final (0–100). There will be eight programs and five quizzes.

Output Welcome to the CSc 2310 average calculation program. Enter Program 1 score: 20 Enter Program 2 score: 19 Enter Program 3 score: 15 Enter Program 4 score: 18.5 Enter Program 5 score: 20 Enter Program 6 score: 20 Enter Program 7 score: 18 Enter Program 8 score: 20 Enter Quiz 1 score: 9 Enter Quiz 2 score: 10 Enter Quiz 3 score: 5.5 Enter Quiz 4 score: 8 Enter Quiz 5 score: 9.5 Enter Test 1 score: 78 Enter Test 2 score: 92 Enter Final Exam score: 85 Course average: 88

Design – Algorithm 1. Print the introductory message ("Welcome to the CSc 2310 average calculation program"). 2. Prompt the user to enter eight program scores. 3. Compute the program average from the eight scores. 4. Prompt the user to enter five quiz scores. 5. Compute the quiz average from the five scores. 6. Prompt the user to enter scores on the tests and final exam. 7. Compute the course average from the program average, quiz average, test scores, and final exam score. 8. Round the course average to the nearest integer and display it.

Design  double variables can be used to store scores and averages.  Computing the course average involves scaling the program average and quiz average so that they lie between 0 and 100: courseAverage =.30  programAverage   quizAverage   test  test  finalExam  Math.round can be used to round the course average to the nearest integer.

CourseAverage.java // Program name: CourseAverage // Author: K. N. King // Written: // Modified: // // Prompts the user to enter eight program scores (0-20), five // quiz scores (0-10), two test scores (0-100), and a final // exam score (0-100). Scores may contain digits after the // decimal point. Input is not checked for validity. Displays // the course average, computed using the following formula: // // Programs 30% // Quizzes 10% // Test 1 15% // Test 2 15% // Final exam 30% // // The course average is rounded to the nearest integer.

import jpb.*; public class CourseAverage { public static void main(String[] args) { // Print the introductory message System.out.println("Welcome to the CSc 2310 average " + "calculation program.\n"); // Prompt the user to enter eight program scores SimpleIO.prompt("Enter Program 1 score: "); String userInput = SimpleIO.readLine(); double program1 = Convert.toDouble(userInput); SimpleIO.prompt("Enter Program 2 score: "); userInput = SimpleIO.readLine(); double program2 = Convert.toDouble(userInput); SimpleIO.prompt("Enter Program 3 score: "); userInput = SimpleIO.readLine(); double program3 = Convert.toDouble(userInput);

SimpleIO.prompt("Enter Program 4 score: "); userInput = SimpleIO.readLine(); double program4 = Convert.toDouble(userInput); SimpleIO.prompt("Enter Program 5 score: "); userInput = SimpleIO.readLine(); double program5 = Convert.toDouble(userInput); SimpleIO.prompt("Enter Program 6 score: "); userInput = SimpleIO.readLine(); double program6 = Convert.toDouble(userInput); SimpleIO.prompt("Enter Program 7 score: "); userInput = SimpleIO.readLine(); double program7 = Convert.toDouble(userInput); SimpleIO.prompt("Enter Program 8 score: "); userInput = SimpleIO.readLine(); double program8 = Convert.toDouble(userInput);

// Compute the program average from the eight scores double programAverage = (program1 + program2 + program3 + program4 + program5 + program6 + program7 + program8) / 8; // Prompt the user to enter five quiz scores SimpleIO.prompt("\nEnter Quiz 1 score: "); userInput = SimpleIO.readLine(); double quiz1 = Convert.toDouble(userInput); SimpleIO.prompt("Enter Quiz 2 score: "); userInput = SimpleIO.readLine(); double quiz2 = Convert.toDouble(userInput); SimpleIO.prompt("Enter Quiz 3 score: "); userInput = SimpleIO.readLine(); double quiz3 = Convert.toDouble(userInput);

SimpleIO.prompt("Enter Quiz 4 score: "); userInput = SimpleIO.readLine(); double quiz4 = Convert.toDouble(userInput); SimpleIO.prompt("Enter Quiz 5 score: "); userInput = SimpleIO.readLine(); double quiz5 = Convert.toDouble(userInput); // Compute the quiz average from the five scores double quizAverage = (quiz1 + quiz2 + quiz3 + quiz4 + quiz5) / 5; // Prompt the user to enter scores on the tests and final // exam SimpleIO.prompt("\nEnter Test 1 score: "); userInput = SimpleIO.readLine(); double test1 = Convert.toDouble(userInput);

SimpleIO.prompt("Enter Test 2 score: "); userInput = SimpleIO.readLine(); double test2 = Convert.toDouble(userInput); SimpleIO.prompt("Enter Final Exam score: "); userInput = SimpleIO.readLine(); double finalExam = Convert.toDouble(userInput); // Compute the course average from the program average, // quiz average, test scores, and final exam score. // The program average (0-20) is multiplied by 5 to put // it on a scale of 0 to 100. The quiz average (0-10) is // multiplied by 10 for the same reason. double courseAverage =.30 * programAverage * * quizAverage * * test * test * finalExam;

// Round the course average to the nearest integer and // display it System.out.println("\nCourse average: " + Math.round(courseAverage)); }

Style Issues  Style issues raised by the CourseAverage program: Comment blocks Blank lines Short comments Long lines

Improving the Program  The values of most variables in the CourseAverage program are used only once.  When a variable’s value is used only once, the variable can often be eliminated by substituting the value that’s assigned to it. The lines String userInput = SimpleIO.readLine(); double program1 = Convert.toDouble(userInput); could be replaced by double program1 = Convert.toDouble(SimpleIO.readLine());

Improving the Program  The number of variables in CourseAverage can be reduced by keeping a “running total” of all scores entered so far, rather than storing each score in a separate variable: // Prompt the user to enter eight program scores. SimpleIO.prompt("Enter Program 1 score: "); String userInput = SimpleIO.readLine(); double programTotal = Convert.toDouble(userInput); SimpleIO.prompt("Enter Program 2 score: "); userInput = SimpleIO.readLine(); programTotal += Convert.toDouble(userInput);... // Compute the program average from the eight scores. double programAverage = programTotal / 8;

Debugging  Debugging is the process of finding bugs in a program and fixing them.  Types of errors: Compile-time errors Run-time errors (called exceptions in Java) Incorrect behavior

Fixing Compile-Time Errors  Strategies for fixing compile-time errors: Read error messages carefully. Example: Buggy.java:8: Undefined variable: i System.out.println(i); ^ Buggy.java:10: Variable j may not have been initialized System.out.println(j); ^ Pay attention to line numbers. Fix the first error.

Fixing Compile-Time Errors Don’t trust the compiler (completely). The error isn’t always on the line reported by the compiler. Also, the error reported by the compiler may not accurately indicate the nature of the error. Example: System.out.print("Value of i: ") System.out.println(i); A semicolon is missing at the end of the first statement, but the compiler reports a different error: Buggy.java:8: Invalid type expression. System.out.print("Value of i: ") ^ Buggy.java:9: Invalid declaration. System.out.println(i); ^

Fixing Run-Time Errors  When a run-time error occurs, a message will be displayed on the screen. Example: Exception in thread "main" java.lang.NumberFormatException: foo at java.lang.Integer.parseInt(Compiled Code) at java.lang.Integer.parseInt(Integer.java:458) at Buggy.main(Buggy.java:11)  Once we know what the nature of the error is and where the error occurred, we can work backwards to determine what caused the error.

Fixing Behavioral Errors  Errors of behavior are the hardest problems to fix, because the problem probably lies either in the original algorithm or in the translation of the algorithm into a Java program.  Other than simply checking and rechecking the algorithm and the program, there are two approaches to locating the source of a behavioral problem, depending on whether a debugger is available.