Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

Similar documents
Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

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

Programming with Java

Lecture 5. Assignments. Arithmetic Operations. Arithmetic Operations -Summary 1/24/18. Lab 3: Variables and operations. Read Sections

Using Java Classes Fall 2018 Margaret Reid-Miller

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Lecture Set 2: Starting Java

ECE 122 Engineering Problem Solving with Java

A variable is a name for a location in memory A variable must be declared

COMP String and Console I/O. Yi Hong May 18, 2015

Lecture Set 2: Starting Java

Introduction to Computer Programming

Oct Decision Structures cont d

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

CS 302: Introduction to Programming

Elementary Programming

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

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

COMP Primitive and Class Types. Yi Hong May 14, 2015

Computational Expression

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

Building Java Programs

AP Computer Science A

Full file at

Section 2: Introduction to Java. Historical note

Hello World. n Variables store information. n You can think of them like boxes. n They hold values. n The value of a variable is its current contents

Building Java Programs

2: Basics of Java Programming

Basic Computation. Chapter 2

Chapter. Let's explore some other fundamental programming concepts

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Basic Computation. Chapter 2

Full file at

Building Java Programs

Data Conversion & Scanner Class

Lesson 02 Data Types and Statements. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

Building Java Programs Chapter 2

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

We now start exploring some key elements of the Java programming language and ways of performing I/O

CS111: PROGRAMMING LANGUAGE II

CS 106 Introduction to Computer Science I

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming

Building Java Programs Chapter 2. bug. Primitive Data and Definite Loops. Copyright (c) Pearson All rights reserved. Software Flaw.

Building Java Programs Chapter 2

Getting started with Java

Object Oriented Programming. Java-Lecture 1

Chapter 2 ELEMENTARY PROGRAMMING

Question: Total Points: Score:

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

Lesson 02 Data Types and Statements. MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes

COMP 202 Java in one week

CS313D: ADVANCED PROGRAMMING LANGUAGE

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Chapter 2. C++ Basics

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

Fundamentals of Programming Data Types & Methods

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

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

Programming with Java

Topic 4 Expressions and variables

Lecture 2: Operations and Data Types

Computational Expression

Course Outline. Introduction to java

Program Elements -- Introduction

What did we talk about last time? Examples switch statements

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a

A+ Computer Science -

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

Chapter 4: Conditionals and Recursion

CMSC131. Introduction to your Introduction to Java. Why Java?

Operators. Java operators are classified into three categories:

2.5 Another Application: Adding Integers

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

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Primitive Data, Variables, and Expressions; Simple Conditional Execution

Logic & program control part 2: Simple selection structures

Input. Scanner keyboard = new Scanner(System.in); String name;

A+ Computer Science -

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

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

COMP 202 Java in one week

BASIC INPUT/OUTPUT. Fundamentals of Computer Science

double float char In a method: final typename variablename = expression ;

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

4 WORKING WITH DATA TYPES AND OPERATIONS

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual:

Chapter 2 Elementary Programming

A Quick and Dirty Overview of Java and. Java Programming

CIS 110: Introduction to Computer Programming

COMP 202. Java in one week

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

Transcription:

Assignments Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4 Lecture 6 Complete for Lab 4, Project 1 Note: Slides 12 19 are summary slides for Chapter 2. They overview much of what we covered but are not complete. We did not review this in lecture. User Input Java Scanner We have covered how to give information to the user print and println statements. How can we get information from the user? Let s solve a simpler problem how can we get information from the keyboard? Java Scanner class defines all of the functionality needed to read from the keyboard and pass that information on to your program Scanner is a object (just like the String is an object). Scanner will be the type in a variable declaration. Step 0: Add a statement to include the Java Scanner library in our program. Put before the class header. import java.util.scanner; Step 1: Declare a reference to a Scanner Scanner keyboard; Step 2: Create a Scanner object in memory and assign the address to the variable keyboard. 1

Java Scanner Step 2: Create a Scanner object in memory and assign the address to the variable keyboard. new is a Java keyword, it causes creation. We are telling it to create a Scanner object. The parentheses () indicate this is a method call. We saw these before. We are passing the argument System.in to the method. This is the data given to the method. System.in means the console or your keyboard in Java = is the assignment operator. We are assigning the address of the Scanner object to keyboard. Using the Scanner (Read 2.13!) To read sequence of characters until a carriage return, we call the method nextline(). String nextline() Example: Ask a client to enter their name and print a welcome banner System.out.print( Please enter your name: ); String clientname = keyboard.nextline(); System.out.println( Welcome + clientname); Questions: Why was print used instead of println? What difference does it make? What is the type of clientname? What methods can we call on clientname? What are the parameters of the method nextline()? What type does nextline() return? To answer this, ask yourself, the type of clientname Using the Scanner (Read 2.13!) Reading Numerical Values (book, pg 96) Example: Compute a person s BMI Pseudo Code BMI = weight in kilograms / square of the height in meters Ask for the persons weight in KGs Ask for the persons height (in meters) Compute the BMI Print the BM To read sequence of characters until a carriage return, we call the method nextline(). String nextline() How can we read a number? Java provides two different options. Directly read a numerical value Read a String using nextline() and convert the String to its numerical equivalent Solution 1: Read in numerical values. System.out.print( Please enter your weight in KGs: ); double weightinkgs = keyboard.nextdouble(); System.out.print( Please enter your height in meters: ); double heightinmeters = keyboard.nextdouble(); Using nextdouble() (or nextint()) leaves the carriage return in the input stream. This causes problems when used with nextline() commands. See your book for a detailed discussion. 2

Reading Numerical Values (book, pg 96) Solution 2: Read in all data until carriage return and convert System.out.print( Please enter your weight in KGs: ); String weightinkgs = keyboard.nextline(); System.out.print( Please enter your height in meters: ); String heightinmeters = keyboard.nextline(); double weight = Double.parseDouble(weightInKGs); double height = Double.parseDouble(heightInMeters); Using nextline to read keyboard input, so the entire contents until the carriage return is stored in weightinkgs Less error-prone approach than directly reading ints... Double, Integer, String, Scanner,. Java Classes we have see so far: String Used to store a sequence of characters. Scanner Used for reading keyboard input Double Used to convert a String into double value Integer Used to convert a String into an int value Scope Variables have scope lifespan of the variable Start of lifespan - Declaration End of lifespan Closing brace } of code block where declared Summary Program Parts Class Header (class name matches the file name prefix) Class Body Because this is a program, the body contains a main method. Main method header Main method body Special Characters we have seen so far: {} - Braces define a class body, method body () - Parentheses define the parameters to a method ; - Semi colon end of a statement // - Start a 1 line comment - Pair of double quotes enclose a string of letters - Use single quotes to enclose a character (a-z, A-Z, 0-9, punctuation) 3

Summary - Variables Declaration: type name ; Assignment: Variable name on left Operator = in the middle Value on the right Scope lifespan of the variable Start of lifespan - Declaration End of lifespan Closing brace } of code block where declared Summary - Arithmetic Operations There are 5 common operations: Addition: + Subtraction: - Multiplication: * Division: / Recall: A B = Quotient * B + Remainder If both operands are integer: produces the quotient Else same as A B Modulus: % (produces the remainder) Summary - Types Primitive Types Variables store the value byte, short, int, long, float, double, boolean, char Reference Types Variables store references to objects, objects stored elsewhere in memory String, Scanner, Double, Integer Call methods on object using the dot operator String str = hello ; int numchars = str.length(); Summary - String Declare String str; Create str = Mary ; str = new String( Mary ); // str s value is undefined Methods to call: int length(); String tolowercase(); String touppercase(); char charat(int position); // position = 0, length() - 1 4

Summary Program Output String (cont) Operator + concatenates two Strings together Concatenate a String and a number and store result in a new String Using print and println to output information to a program. int number = 17; String color = Green ; System.out.println(number); // outputs 17, value of variable System.out.println(color); // outputs Green, value stored in // object referenced by color Summary Scanner (Program Input) Import Statement Before class header, add: import java.util.scanner; Declare Scanner keyboard; Create keyboard = new Scanner(System.in); Methods to call: String nextline(); double nextdouble(); int nextint(); Summary - Conversions Given a String, there are two ways to convert it to a numeric value double Double.parseDouble(String); int Integer.parseInt(String); When will the conversion fail? 340 will convert to int or double abc will cause a run time exception 34.2 will convert to a double Decision Structures Decision structures allow us to modify the flow of a program We can conditionally execute or conditionally skip one or more statements based on a decision In your first Project, you will extend your TaxComputer program to use decision statements to set the state tax rate based on the the clients state of residence. This project will also use decision statements to determine the taxable income and the amount of federal tax owed. 5

Conditional Execution Goal: Send a message to all students enrolled in the Spring term who have not yet paid their tuition. Pseudo-Code: If a student is enrolled in at least one class If they have not paid their tuition Email them a message indicating that their tuition is due. The email should include the balance and the due date. How do we write Java code that performs the sequence above? A message should be sent only if a student is enrolled and if they have not paid their tuition. Java if Statement - Example boolean tuitiondue = true; if (tuitiondue) System.out.println( Pay your tuition! ); Behavior if is a Java keyword. It is followed by parentheses() Inside the parentheses is a boolean (has the value of true or false) Flow: when tuitiondue has the value of true, the println is executed. when tuitiondue has the value of false, the println is not executed. Example: Converting a Score to a letter Grade Write a program that asks the user to enters 2 exam scores, computes and outputs the average. If the average is at least 97, print a congratulations banner. Pseudo Code Print message for score 1 Read score 1, convert to double Print message for score 2, Read score 2, convert to double Compute average Output average If the average is at least 97, output a congratulations message Print message for score 1 Read score 1, convert to double System.out.print( Please enter the first score: ); String input = keyboard.nextline(); double score1 = Double.parseDouble(input); 6

Compute average Output average double avg = (score1 + score2) / 2; System.out.println( Your average is: + avg); If the average is at least 97, output a congratulations message Use a relational operator to compare the value of the variable avg to the value 97. Result is a boolean Read expressions from left to right! Let a and b be two different primitive variables. Assume they have the same primitive type: boolean result = a < b; // result is true if a less than b boolean result = a > b; // result is true if a greater than b boolean result = a <= b; // result is true if a less than, or equal to, b boolean result = a >= b; // result is true if a greater than, or equal to, b boolean result = a == b; // result is true if a equals b boolean result = a!= b; // result is true if a is not equal to b Java if Statement If the average is at least 97, output a congratulations message Use a relational operator to compare the value of the variable avg to the value 97. Which is the correct operator to use? at least à greater than or equal à >= if (avg >= 97) System.out.println( Great Job!!! ); Note that we put the expression inside the parentheses. this is the most common approach. Read this as: boolean tmp = avg >= 97; If (tmp).. General Form if (booleanexpression) statement; A booleanexpression evaluates to true or false You can use a boolean variable You can use an expression with a relational operator 7

Java if Statement - continued If we want to conditionally execute multiple statements, use braces {} to form a code block if (booleanexpression) { statement1; statement2; statement3; } Flow: When the expression is true, the code block defined by the braces {} is executed When the expression is false, the code block is skipped Compute average Output average If the average is at least 97, output a congratulations message double avg = (score1 + score2) / 2; if (avg >= 97) { } System.out.println( Your average is: + avg); System.out.println( Great Job!!! ); if (avg < 97) System.out.println( Your average is: + avg); Last Note on Relational Operators Relational operators can be used primitive types byte, short, int, long, double, float and char and boolean Let a and b be two different primitive variables. Assume they have the same primitive type: boolean result = a < b; // result is true if a less than b boolean result = a > b; // result is true if a greater than b boolean result = a <= b; // result is true if a less than, or equal to, b boolean result = a >= b; // result is true if a greater than, or equal to, b boolean result = a == b; // result is true if a equals b boolean result = a!= b; // result is true if a is not equal to b See pages 120-121 for examples with char variables. A common task in a program is to display a message that asks the user to enter data via the keyboard. The program then reads the data. To display a message, Java programmers use a print or println statement. To read data, Java programmers use a Scanner. Assume: Scanner keyboard; Circle all that are true. a) The variable keyboard is a primitive type. b) The statement creates a Scanner and assigns the value to keyboard: keyboard = new Scanner(System.in); c) The statement creates a Scanner and assigns the value to keyboard: keyboard = new Scanner(System.out); d) Programs that use a Scanner require an import statement be added to the class body. a) is false, keyboard is a reference to a Scanner. d) is false, import is before the class body. 1/29/2018 8

A programmer needs to read a value that the user has entered to be treated as a number. One option is to read the data as: double number = keyboard.nextdouble(); The other option is to read the entire line the user enters. String data = keyboard.nextline(); How can the user convert this data to a double? a) Not possible. b) Use the statement: int val = Integer.parseDouble(); c) Use the statement: double val = Double.parseDouble(); d) Use the statement: double val = Double.parseDouble(data); d) is the only true statement. We need to give the Double object method parsedouble() what is to be parsed. The variable data points to what is to be parsed. 1/29/2018 9