Integer Division What is x? int x = 1729 / 100; Answer: 17.

Slides:



Advertisements
Similar presentations
Introduction to Programming Java Lab 2: Variables and Number Types 1 JavaLab2 lecture slides.ppt Ping Brennan
Advertisements

Self Check 1.Which are the most commonly used number types in Java? 2.Suppose x is a double. When does the cast (long) x yield a different result from.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Chapter 2 Console Input and Output Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
03 Data types1June Data types CE : Fundamental Programming Techniques.
Mathematical Operators  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming in.
Chapter 2 Console Input and Output Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: self-check: #16-19.
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;
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: self-check: #16-19.
Week 2 - Friday.  What did we talk about last time?  Data representation  Binary numbers  Types  int  boolean  double  char  String.
CSCI 1730 January 17 th, 2012 © by Pearson Education, Inc. All Rights Reserved.
© The McGraw-Hill Companies, 2006 Chapter 1 The first step.
Computer Programming Fundamental Data Types Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons.
Slides by Donald W. Smith
Android How to Program, 2/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 4 – Fundamental Data Types.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Chapter 2 Console Input and Output Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Console Input & Output CSS 161: Fundamentals of Computing Joe McCarthy 1.
Sahar Mosleh California State University San MarcosPage 1 System.out.println for console output System.out is an object that is part of the Java language.
Slides prepared by Rose Williams, Binghamton University Chapter 2 Console Input and Output.
Input, Output, and Processing
Week 2 - Wednesday.  What did we talk about last time?  Data representation  Binary numbers  Types  int  boolean  double  char  String.
Chapter 2 Elementary Programming
1 Fencepost loops “How do you build a fence?”. 2 The fencepost problem Problem: Write a class named PrintNumbers that reads in an integer called max and.
Input/Output in Java. Output To output to the command line, we use either System.out.print () or System.out.println() or System.out.printf() Examples.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
First Programs CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Introduction to Programming
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.
Chapter 3: Classes and Objects Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved Java’s String Class.
FUNDAMENTALS 2 CHAPTER 2. OPERATORS  Operators are special symbols used for:  mathematical functions  assignment statements  logical comparisons 
CHAPTER 5 GC 101 Input & Output 1. INTERACTIVE PROGRAMS  We have written programs that print console output, but it is also possible to read input from.
Introduction to Computing Concepts Note Set 12. Writing a Program from Scratch public class SampleProgram1 { public static void main (String [] args)
Chapter 2: Data and Expressions String and String Concatenation Escape Sequences Variables Primitive Date Types Expressions Interactive Programs.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Chapter Two: Fundamental Data Types Slides by Evan Gallagher.
Formatted Output (printf) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Strings CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 4 – Fundamental Data Types.
Chapter 2 Console Input and Output Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Slides prepared by Rose Williams, Binghamton University Console Input and Output.
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: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: self-check: #16-19.
Formatted Output (printf) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. A string is a sequence of characters Strings are objects of the String.
Introduction to Computer Science and Object-Oriented Programming
Strings CSE 1310 – Introduction to Computers and Programming
Lecture 4 – Scanner & Style
Strings CSE 1310 – Introduction to Computers and Programming
Strings CSE 1310 – Introduction to Computers and Programming
Topics Designing a Program Input, Processing, and Output
Input/Output.
Chapter 2 More on Math More on Input
TemperatureConversion
Chapter Goals To understand integer and floating-point numbers
Chapter Goals To understand integer and floating-point numbers
Chapter 4 – Fundamental Data Types
OUTPUT STATEMENTS GC 201.
INPUT STATEMENTS GC 201.
Introduction to Computer Science and Object-Oriented Programming
Wednesday 09/23/13.
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Presentation transcript:

Integer Division What is x? int x = 1729 / 100; Answer: 17

Integer Division The volume of a sphere is given by If the radius is given by a variable radius of type double, write a Java expression for the volume. Answer: 4 * PI * Math.pow(radius, 3) / 3 or (4.0 / 3) * PI * Math.pow(radius, 3), but not (4 / 3) * PI * Math.pow(radius, 3)

Mod Operator (remainder) What is r? int r = 1729 % 100; Answer: 27

Manipulating Places In general, what is x? int x = (n / 10) % 10? Answer: Dividing by ten always trims off the right-most digit, so if n was 1234 the n/10 is 123 Mod by ten always returns the right-most digit, so 123%10 is 3. (n/10)%10 always returns the hundred-place digit

Reading Input First you must indicate what the user should type // Display prompt System.out.print(”Enter number of bottles: "); This message is called a prompt Use the print method, not println, to display the prompt Leave a space after the colon Second, you can use a combination of System.in and Scanner to read keyboard input.

Reading Input - Scanner To obtain a Scanner object: Scanner in = new Scanner(System.in); Use the Scanner's nextInt method to read an integer value: System.out.print("Please enter the number of bottles: "); int bottles = in.nextInt(); When the nextInt method is called, The program waits until the user types a number and presses the Enter key; After the user supplies the input, the number is placed into the bottles variable; The program continues.

Reading Input - Scanner To obtain a Scanner object: Scanner in = new Scanner(System.in); Use the Scanner's nextInt method to read an integer value: System.out.print(”Enter number of bottles: "); int bottles = in.nextInt();

Reading Input - Scanner Scanner in = new Scanner(System.in); System.out.print(”Enter number of bottles: "); int bottles = in.nextInt(); System.out.print("Enter price: "); double price = in.nextDouble(); The Scanner class can get all the built-in data types It is in the java.util package import java.util.Scanner;

Formatted Output printf lets you print this Price per liter: 1.22 Instead of this Price per liter: 1.215962441314554 Here is how: double price = 1.215962441314554; System.out.printf("%.2f", price);

Formatted Output You can also specify a field width: System.out.printf("%10.2f", price); This prints 10 characters This command System.out.printf("Price per liter:%10.2f", price); Prints Price per liter: 1.22 1 2 3 4 5 6 7 8 9 10 .

Formatted Output You use the printf to line up output in neat columns. double perCup = 1.22; double perGallon = 17.29; System.out.printf(”Per cup: %10.2f", perCup ); System.out.printf(”Per gallon:%10.2f", perGallon ); Per cup: 1.22 Per gallon: 17.29

1 import java. util. Scanner; 2 3 / 1 import java.util.Scanner; 2 3 /** 4 This program prints the price per liter for a six-pack of cans and 5 a two-liter bottle. 6 */ 7 public class Volume 8 { 9 public static void main(String[] args) 10 { 11 // Read price per pack 12 13 Scanner in = new Scanner(System.in); 14 15 System.out.print("Please enter the price for a six-pack: "); 16 double packPrice = in.nextDouble(); 17 18 // Read price per bottle 19 20 System.out.print("Please enter price for two-liter bottle: "); 21 double bottlePrice = in.nextDouble(); 22

Program Run Please enter the price for a six-pack: 2.95 23 final double CANS_PER_PACK = 6; 24 final double CAN_VOLUME = 0.355; // 12 oz. = 0.355 l 25 final double BOTTLE_VOLUME = 2; 26 27 // Compute and print price per liter 28 29 double packPricePerLiter = packPrice / (CANS_PER_PACK * CAN_VOLUME); 30 double bottlePricePerLiter = bottlePrice / BOTTLE_VOLUME; 31 32 System.out.printf("Pack price per liter: %8.2f", packPricePerLiter); 33 System.out.println(); 34 35 System.out.printf("Bottle price per liter: %8.2f", bottlePricePerLiter); 36 System.out.println(); 37 } 38 } Program Run Please enter the price for a six-pack: 2.95 Please enter price for two-liter bottle: 2.85 Pack price per liter: 1.38 Bottle price per liter: 1.43

Question Write statements to prompt for and read the user’s age using a Scanner variable named in. Answer: System.out.print("How old are you? "); int age = in.nextInt();

Question What is wrong with the following statement sequence? System.out.print("Please enter the unit price: "); double unitPrice = in.nextDouble(); int quantity = in.nextInt(); Answer: There is no prompt that alerts the program user to enter the quantity.

Question What is problematic about the following statement sequence? System.out.print("Please enter the unit price: "); double unitPrice = in.nextInt(); Answer: The second statement calls nextInt, not nextDouble. If the user were to enter a price such as 1.95, the program would be terminated with an “input mismatch exception”.

Question What is problematic about the following statement sequence? System.out.print("Please enter the number of cans"); int cans = in.nextInt(); Answer: There is no colon and space at the end of the prompt. A dialog would look like this: Please enter the number of cans6

Question How many spaces will be between “is” and 10 int volume = 10; System.out.printf("The volume is %5d", volume); The total volume is 10 Answer: There are four spaces between is and 10. One space originates from the format string and three spaces are added before 10 to achieve a field width of 5.

Algorithms Problem: A row of black and white tiles needs to be placed along a wall. First and last are black. Compute the number of tiles needed and the gap at each end, given the space available and the width of each tile.

Algorithms Constraint: First and last are black. Output: the number of tiles needed and the gap at each end. Input: space to fill and the width of each tile.

Algorithms Carry out the computations by hand first Pick concrete values for a typical situation to use in a hand calculation.

Algorithms Input: space to fill and the width of each tile. numbers Total space to fill: 100 inches Tile width: 5 inches The first tile must always be black, and then we add some number of white/black pairs:

Algorithms The first tile takes up 5 inches, leaving 95 inches to be covered by pairs. Each pair is 10 inches wide. number of pairs needed is 95 / 10 = 9.5 Discard the fractional part. We need 9 tile pairs or 18 tiles, plus the initial black tile => 19 tiles. Tiles span 19 × 5 = 95 inches Gap is 100 – 95 = 5 inches Distribute the gap at both ends gap is 5 / 2 = 2.5 inches

Algorithms Devise an algorithm with arbitrary values for the total width and tile width. The pseudocode number of pairs = integer part of (total width - tile width) / (2 x tile width) number of tiles = 1 + 2 x number of pairs gap at each end = (total width - number of tiles x tile width) / 2

Question Translate the pseudocode for computing the number of tiles and the gap width into Java. Input: totalWidth and tileWidth Answer: int pairs = (totalWidth - tileWidth) / (2 * tileWidth); int tiles = 1 + 2 * pairs; double gap = (totalWidth - tiles * tileWidth) / 2.0;

Question Suppose the architect specifies a pattern with black, gray, and white tiles, like this: Again, the first and last tile should be black. How do you need to modify the algorithm?

Question Answer: Now there are groups of four tiles (gray/ white/gray/black) following the initial black tile. Therefore, the algorithm is now number of groups = integer part of (total width - tile width) /(4 x tile width) number of tiles = 1 + 4 x number of groups

Question number of groups = integer part of (total width - tile width) /(4 x tile width) number of tiles = 1 + 4 x number of groups int groups = (totalWidth - tileWidth) / (4 * tileWidth); int tiles = 1 + 4 * groups ; double gap = (totalWidth - tiles * tileWidth) / 2.0;

String Recap String name = "Harry"; name is a string variable that points to a string literal "Harry” String literals are character sequences enclosed in quotes

String Type String length is the number of characters in the string The length of "Harry" is 5 The length method yields the number of characters in a string int n = name.length(); A string of length 0 is called the empty string Contains no characters Is written as ""

Concatenation Concatenating strings means to put them together to form a longer string Use the + operator Example: String fName = "Harry”; String lName = "Morgan”; String name = fName + lName; Result: "HarryMorgan" To separate the first and last name with a space String name = fName + " " + lName; Results in "Harry Morgan"

Concatenation If one of the arguments of the + operator is a string The other is forced to become to a string: Both strings are then concatenated Example String jobTitle = "Agent”; int employeeId = 7; String bond = jobTitle + employeeId; Result "Agent7"

Concatenation Recap Useful to reduce the number of System.out.print instructions System.out.print("The total is "); System.out.println(total); versus System.out.println("The total is " + total);

String Input Use the next method of the Scanner class to read a string containing a single word. System.out.print("Please enter your name: "); String name = in.next(); Only one word is read. Use a second call to in.next to get a second word.

Escape Sequences To include a quotation mark in a literal string, precede it with a backslash ( \ ) "He said \"Hello\"” Indicates that the quotation mark that follows should be a part of the string and not mark the end of the string Called an escape sequence

Escape Sequences To include a backslash in a string, use the escape sequence \\ "C:\\Temp\\Secret.txt” A newline character is denoted with the escape sequence \n

Strings and Characters A string is a sequences of Unicode characters. Character literals are delimited by single quotes. 'H' is a character. It is a value of type char Don't confuse them with strings "H" is a string containing a single character. It is a value of type String.

Strings and Characters String positions are counted starting with 0. The position number of the last character is always one less than the length of the string. The last character of the string "Harry" is at position 4

Strings and Characters The charAt method returns a char value from a string The example String name = "Harry”; char start = name.charAt(0); char last = name.charAt(4); Sets start to 'H' and last 'y'.

Substrings Use the substring method to extract a part of a string. The method call str.substring(start, pastEnd) Example: String greeting = "Hello, World!”; String sub = greeting.substring(0, 5); // sub is "Hello”

Substrings To extract "World” String sub2 = greeting.substring(7, 12); Substring length is “past the end” - start

Substrings If you omit the end position when calling the substring method, then all characters from the starting position to the end of the string are copied. Example String tail = greeting.substring(7); // Copies all characters from position 7 on Result Sets tail to the string "World!".

1 import java. util. Scanner; 2 3 / 1 import java.util.Scanner; 2 3 /** 4 This program prints a pair of initials. 5 */ 6 public class Initials 7 { 8 public static void main(String[] args) 9 { 10 Scanner in = new Scanner(System.in); 14 System.out.print("Enter your first name: "); 15 String first = in.next(); 16 System.out.print("Enter your last name: "); 17 String second = in.next(); 21 String initials = first.substring(0, 1) 22 + "&" + second.substring(0, 1); 23 System.out.println(initials); 24 } 25 }

Program Run Enter your first name: Sally Enter your last name: Ryan S&R

String Operations

String Operations

String Operations

String Operations

Hebrew, Arabic, and English

Chinese Script