Standard Output, and Strings - PowerPoint PPT Presentation

1 / 20
About This Presentation
Title:

Standard Output, and Strings

Description:

Standard Output, and Strings – PowerPoint PPT presentation

Number of Views:51
Avg rating:3.0/5.0
Slides: 21
Provided by: michaelc7
Category:

less

Transcript and Presenter's Notes

Title: Standard Output, and Strings


1
Standard Output, and Strings
  • System.out an object of type PrintStream
  • println(string) prints string and newline
  • print(string) prints string, no newline
  • String literal is delimited by quotes a
    string
  • Remember special characters start with \
  • e.g., \n is a newline character
  • So println(Hi) is same as print(Hi\n)
  • concatenates e.g., a 5 b becomes a5b
  • Note first 5 is converted to a String.

2
Formatted printing
  • Java 5 printf(format, object1, object2, )
  • Method of PrintStream class so System.out has
  • System.out.printf(x d, x) // x is an
    integer
  • Or use o or x to show same value in octal or
    hexadecimal
  • f or e or g for floating point, and s for
    strings
  • Also control field width, precision, and other
    formatting
  • printf(-9s7.2fn, Value, v)
  • Complete details in java.util.Formatter
  • Format dates, times,
  • Can use to create formatted String objects too
  • String s String.format(pt d, d", x, y)

3
Standard input, and more Strings
  • Actually have to read keyboard or other input as
    a String (also requires exception handling)
  • So must parse string to interpret numbers or
    other types
  • e.g., String s1 426, s2 93.7
  • Then s1 can be parsed to find an int or a double,
    and s2 can be parsed to find a double
  • int n Integer.parseInt(s1)
  • double d Double.parseDouble(s2)

4
java.util.Scanner
  • Important Java 5 enhancement greatly simplifies
    input processing
  • First construct a Scanner object pass it
    System.in (or other input stream, or even a
    string)
  • Scanner in new Scanner(System.in)
  • Then get next string, int or double (or others)
  • String s in.next()
  • String wholeLine in.nextLine()
  • int x in.nextInt()
  • double y in.nextDouble()
  • See class Addition (Fig. 2.7, p. 47)

5
Arithmetic
  • Operators
  • , -, , / add, subtract, multiply, divide
  • modulus operator remainder
  • ( ) means whatever is inside is evaluated
    first
  • Use java.lang.Math for difficult calculations
  • E.g., Math.sqrt(x), Math.cos(x), (more later)
  • Precedence rules so far (will expand)
  • ( )
  • , /,
  • , -

6
Analyzing an expression
7
Simple decisions using if
  • Do something or dont do something depending on
    the circumstances
  • if (value
  • Only prints if value is less than zero
  • Formal definition to implement decision
  • if (boolean expression) statement-to-execute
    // only if expression is true

8
Simple boolean expressions
  • Relational operators , , , !
  • e.g., int x1, y2, z3
  • x y ?
  • Lower precedence than arithmetic
  • x z y ?
  • x z y ?
  • Note not same as x z y // would make x be 5
  • Not equal z ! x y ?
  • See class Comparison (Fig. 2.15, p. 57)

false
true
false
false
9
Define and use a simple class
  • First version of GradeBook.java (Fig. 3.1, p. 75)
  • public class GradeBook
  • public void displayMessage()
    System.out.println ( Welcome )
  • First GradeBookTest.java (Fig. 3.2, p. 77)
  • public class GradeBookTest
  • public static void main( String args )
  • GradeBook myGradeBook new GradeBook()
  • myGradeBook.displayMessage()
  • Notice all GradeBook objects are exactly the same

10
Instance variables
  • Each object is an instance of its class, and each
    instance can have different attributes
  • e.g., course name for GradeBook object
  • private String courseName
  • Related set and get methods
  • public void setCourseName(String name)
  • courseName name
  • public String getCourseName()
  • return courseName
  • See enhanced GradeBook.java (Fig. 3.7, p. 83) and
    new GradeBookTest.java (Fig. 3.8)
  • Notice name is null before set method is used
  • Numeric values default to 0 boolean values to
    false

11
Constructors
  • Definition looks like a method, but always has
    same name as the class, and no return type
  • e.g., alternate constructor for GradeBook
  • public GradeBook(String name)
  • courseName name
  • Initialize course name as object constructed
  • GradeBook myBook
  • new GradeBook (CS 5JA)
  • No need to set later, and never equals null
  • See another GradeBook.java (Fig. 3.10) and
    another new GradeBookTest.java (Fig. 3.11)

12
Syntax for defining methods
  • Method has two parts a header and a body
  • type name (parameter declarations) // header
  • local declarations and statements // body
  • Parentheses in header and brackets around body
    are required
  • type refers to the result of the method
  • May be any primitive type, or any class
  • Or may be void means it does not return any
    results
  • If not void, statements in the method body must
    include a return statement

13
Java has 8 primitive data types(everything else
is an object)
  • 7 are number types
  • 5 of the number types are integral types
  • int most fundamental 4, -123, 9587123 are int
  • long for longer integers (2,147,483,647)
  • short, byte save space for shorter integers
  • char to represent characters A, a, \n
  • Other 2 number types are floating point types
  • double most fundamental 0.4, -123.3, 95.
  • float save space for less precision
  • 8th type is boolean to represent true or false

14
About floating point types
  • Rounding errors occur when an exact conversion
    between numbers is not possible
  • double f 4.35
  • System.out.println(100 f) // prints
    434.99999999999994
  • Illegal to assign a floating-point expression to
    an integer
  • double balance 13.75
  • int dollars balance // Error
  • Casts used to convert a value to a different
    typeint dollars (int) balance // OK
  • Cast discards fractional part truncates
  • Math.round converts floating-point to nearest
    integer
  • long rounded Math.round(balance)
  • If balance is 13.75, then rounded is set to 14

15
Another example class from Deitel
  • Account.java (Fig. 3.13, p. 92)
  • Instance variable, balance, is type double
  • Method credit adds amount (also a double)
  • Also getBalance, but no setBalance
  • UML
  • Static class diagram
  • AccountTest.java uses 2 Account objects

16
Summary Objects classes
  • An object represents a thing (e.g., window,
    spaceship) or a concept (e.g., power, trajectory)
  • A software entity with data and methods
  • i.e., more complex than just a number
  • Technically, an instance of a class
  • A class defines a type of object
  • e.g., class String defines what a String knows
    (data), and what a String can do (methods)
  • Definition includes a public interface (what we
    use), and a private implementation (unimportant
    to user)

17
Syntax for invoking methods
  • Essentially methodName(list of arguments)
  • Effect transfers control to the method named
    may pass data via the list of arguments
  • When method completes control returns to the
    point in the program where the method was called
  • Also returns a result if not a void method
  • Need more if method defined in a different class
  • Full syntax is objectReference.methodName()
  • Or just ClassName.name() if method is static

18
Aside using dialog boxes
  • Simplest type of GUI (Graphical User Interface)
  • Import javax.swing.JOptionPane
  • Message dialogs show user something
  • e.g., a String (and other types of objects)
  • Input dialogs get a String from the user
  • Must parse string to convert to numbers/other
  • See NameDialog.java (Fig 3.18, p. 97)
    - and try GUI/Graphics Case Study Exercise 3.1
    (p. 98)

19
  • Maybe more
  • Maybe less

20
WednesdayIndependence Day
Write a Comment
User Comments (0)
About PowerShow.com