basics of java programming variables, assignment, and inputmap/1051/f13/02javabasics.pdf ·...

27
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/f13/ Some slides in this presentation are adapted from the slides accompanying Java Software Solutions by Lewis & Loftus CSC 1051 M.A. Papalaskari, Villanova University Basics of Java Programming variables, assignment, and input

Upload: others

Post on 07-Apr-2020

11 views

Category:

Documents


0 download

TRANSCRIPT

CSC 1051 – Algorithms and Data Structures I

Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Course website: www.csc.villanova.edu/~map/1051/f13/ Some slides in this presentation are adapted from the slides accompanying Java Software Solutions by Lewis & Loftus

CSC 1051 M.A. Papalaskari, Villanova University

Basics of Java Programming variables, assignment, and input

int sum; double milesPerGallon; String name, petName; "

Variables

•  A variable is a name for a location in memory

•  A variable must be declared by specifying the variable's name and the type of information that it will hold

data type variable name

CSC 1051 M.A. Papalaskari, Villanova University

Java Primitive Data Types

•  integers:

– byte, short, int, long

•  floating point numbers:

– float, double

•  characters:

– char

•  Logical values (true/false):

– boolean CSC 1051 M.A. Papalaskari, Villanova University

www.toonpool.com/cartoons/PRIMITIVE%20CAVEMAN%20WORDS_25547#

Assignment Statement •  Changes the value of a variable •  The assignment operator is the = sign

total = 55 - discount;

•  The expression on the right is evaluated and the result is stored in the variable on the left

CSC 1051 M.A. Papalaskari, Villanova University

Combined declaration and assignment

A variable can be given an initial value in the declaration

int age = 18; double x = 3.2, y = -0.80; String name = scan.nextLine(); ""

CSC 1051 M.A. Papalaskari, Villanova University

Combined declaration and assignment

A variable can be given an initial value in the declaration - a new value can be assigned later:

int age = 18; double x = 3.2, y = -0.80; String name = scan.nextLine(); age = 19; "x = x + 0.5;"name = scan.nextLine();"

CSC 1051 M.A. Papalaskari, Villanova University

Combined declaration and assignment – CANNOT declare twice

A variable can be given an initial value in the declaration - a new value can be assigned later:

int age = 18; double x = 3.2, y = -0.80; String name = scan.nextLine(); int age = 19; """

CSC 1051 M.A. Papalaskari, Villanova University

Error: declaring variable age again

CONSTANTS: like variables, but value cannot change – declare using final modifier:

"final int INCHES_PER_FOOT = 12;"final double LBS_PER_KG = 2.2;"

CSC 1051 M.A. Papalaskari, Villanova University

Convention: Use UPPER_CASE identifiers

Arithmetic Operators

•  If either or both operands used by an arithmetic operator are floating point, then the result is a floating point

Addition Subtraction Multiplication Division Remainder

+ - * / %

CSC 1051 M.A. Papalaskari, Villanova University

Division and Remainder

•  If both operands are integers, the division result is an integer (the fractional part is discarded):

•  % gives the remainder of the division:

14 / 3

8 / 12

14 % 3

8 % 12

CSC 1051 M.A. Papalaskari, Villanova University

143 / 60

20 / 16

143 % 60

20 % 16

Operator Precedence

result = total + count / max - offset;

Order of evaluation:

1.  Multiplication, division, remainder

2.  addition, subtraction, string concatenation

–  Operators with the same precedence: left àright

–  Use parentheses to override default order

CSC 1051 M.A. Papalaskari, Villanova University

Examples int x = 5;

System.out.println ("Ans= " + (x + 1));

System.out.println ("Ans= " + x + 1);

System.out.println ("Ans= " + (x + 1 * 3));

System.out.println ("Ans= " + ((x + 1) * 3));

System.out.println ("Ans= " + (x / 3 / 2));

System.out.println ("Ans= " + (x / (3 / 2)));

CSC 1051 M.A. Papalaskari, Villanova University

More examples

a + b + c + d + e

a – b / c + d * e

a / (b + c) - d % e

a / (b * (c + (d - e)))

CSC 1051 M.A. Papalaskari, Villanova University

Assignment Revisited •  lower precedence than the arithmetic operators •  evaluated right èleft

First the expression on the right hand side of the = operator is evaluated

Then the result is stored in the variable on the left hand side

answer = sum / 4 + MAX * lowest; 1 4 3 2

CSC 1051 M.A. Papalaskari, Villanova University

Assignment Revisited

•  The right and left hand sides of an assignment statement can contain the same variable

First, one is added to the original value of count

Then the result is stored back into count (overwriting the original value)

count = count + 1;

CSC 1051 M.A. Papalaskari, Villanova University

Increment and Decrement

•  The increment operator (++) adds one to its operand

•  The decrement operator (--) subtracts one from its operand

•  The statement

count++;

is functionally equivalent to

count = count + 1;

CSC 1051 M.A. Papalaskari, Villanova University

Assignment operator

•  Assignment ( = ) copies the value of the right side into the memory location associated with the left side

•  It does not set up an ongoing equivalence

int davesAge = 21; int suesAge = davesAge; davesAge = 22; System.out.println (davesAge); // prints 22 System.out.println (suesAge); // prints 21

CSC 1051 M.A. Papalaskari, Villanova University

Interactive Programs

•  The Scanner class has methods for reading input

•  We declare a Scanner object to read input from the keyboard:

Scanner scan = new Scanner (System.in);

Copyright © 2012 Pearson Education, Inc.

Scanner object keyboard input

Reading Input •  Once created, the Scanner object can be used to

invoke various input methods, such as:

answer = scan.nextLine();

•  The nextLine method reads all of the input until the end of the line is found

Copyright © 2012 Pearson Education, Inc.

Scanner object

Reading Input •  The Scanner class is part of the java.util class

library, and must be imported into a program to be used

•  The import statement goes at beginning of your program (above class definition)

import java.util.Scanner;

(See Echo.java )

•  The details of object creation and class libraries are discussed further in Chapter 3

Copyright © 2012 Pearson Education, Inc.

Copyright © 2012 Pearson Education, Inc.

//******************************************************************** // Echo.java Author: Lewis/Loftus // // Demonstrates the use of the nextLine method of the Scanner class // to read a string from the user. //******************************************************************** import java.util.Scanner; public class Echo { //----------------------------------------------------------------- // Reads a character string from the user and prints it. //----------------------------------------------------------------- public static void main (String[] args) { String message; Scanner scan = new Scanner (System.in); System.out.println ("Enter a line of text:"); message = scan.nextLine(); System.out.println ("You entered: \"" + message + "\""); } }

Copyright © 2012 Pearson Education, Inc.

//******************************************************************** // Echo.java Author: Lewis/Loftus // // Demonstrates the use of the nextLine method of the Scanner class // to read a string from the user. //******************************************************************** import java.util.Scanner; public class Echo { //----------------------------------------------------------------- // Reads a character string from the user and prints it. //----------------------------------------------------------------- public static void main (String[] args) { String message; Scanner scan = new Scanner (System.in); System.out.println ("Enter a line of text:"); message = scan.nextLine(); System.out.println ("You entered: \"" + message + "\""); } }

Sample Run Enter a line of text: You want fries with that? You entered: "You want fries with that?"

Reading in numbers •  nextInt reads in an integer:

•  Example:

age = scan.nextInt();

•  nextDouble similar method for type double

•  White space (space, tab, new line) can be used to separate input tokens

•  next reads the next input token and returns it as a string

•  See GasMileage.java Copyright © 2012 Pearson Education, Inc.

Copyright © 2012 Pearson Education, Inc.

//******************************************************************** // GasMileage.java Author: Lewis/Loftus // // Demonstrates the use of the Scanner class to read numeric data. //******************************************************************** import java.util.Scanner; public class GasMileage { //----------------------------------------------------------------- // Calculates fuel efficiency based on values entered by the // user. //----------------------------------------------------------------- public static void main (String[] args) { int miles; double gallons, mpg; Scanner scan = new Scanner (System.in); continue

Copyright © 2012 Pearson Education, Inc.

continue System.out.print ("Enter the number of miles: "); miles = scan.nextInt(); System.out.print ("Enter the gallons of fuel used: "); gallons = scan.nextDouble(); mpg = miles / gallons; System.out.println ("Miles Per Gallon: " + mpg); } }

Copyright © 2012 Pearson Education, Inc.

continue System.out.print ("Enter the number of miles: "); miles = scan.nextInt(); System.out.print ("Enter the gallons of fuel used: "); gallons = scan.nextDouble(); mpg = miles / gallons; System.out.println ("Miles Per Gallon: " + mpg); } }

Sample Run Enter the number of miles: 328 Enter the gallons of fuel used: 11.2 Miles Per Gallon: 29.28571428571429

Homework •  Read Sections 2.1 – 2.4 and 2.6

–  Always do all self-review exercises when you review material

•  Do Exercises EX 2.2 – 2.7 and 2.11

CSC 1051 M.A. Papalaskari, Villanova University