Upgrade to Pro — share decks privately, control downloads, hide ads and more …

CSE110 Lecture 07

CSE110 Lecture 07

Principles of Programming with Java
Input and Formatted Output
(202205)

More Decks by Javier Gonzalez-Sanchez

Other Decks in Programming

Transcript

  1. CSE110 Principles of Programming with Java Lecture 07: Input and

    Formatted Output Javier Gonzalez-Sanchez [email protected] javiergs.engineering.asu.edu | javiergs.com Office Hours: By appointment
  2. Javier Gonzalez-Sanchez | CSE110 | Summer 2020 | 3 Program

    MyProgram Java API (Application Programming Interface) Classes inside Packages = Files inside folders String Math System.out java.lang java.util java.net javax.swing
  3. Javier Gonzalez-Sanchez | CSE110 | Summer 2020 | 4 Java

    API Packages • The classes of the Java standard class library are organized into packages • java.lang • java.net java.util • java.awt • javax.swing • When you want to use a class from a package, you can import one class or all classes from the package into your program
  4. Javier Gonzalez-Sanchez | CSE110 | Summer 2020 | 5 Java

    API Packages • All classes of the java.lang package are imported automatically into all programs • Other classes should be explicitly imported. Examples: import javax.swing.JOptionPane; import javax.swing.*;
  5. Javier Gonzalez-Sanchez | CSE110 | Summer 2020 | 8 Parsing

    import javax.swing.JOptionPane; public class Lecture06 { public static void main(String [] args) { String test1= JOptionPane.showInputDialog(”write here:"); int value1 = Integer.parseInt(test1); double value2 = Double.parseDouble(test1); System.out.println(value1); System.out.println(value2); } }
  6. Javier Gonzalez-Sanchez | CSE110 | Summer 2020 | 11 printf

    Method printf() method in System.out can be used to specify how many digits for a floating-point number should be display. Ex: double number = 1.0/3.0; System.out.printf("%.2f\n", number); //0.33 System.out.printf("%7.3f\n", 89.123456789); //89.123
  7. Javier Gonzalez-Sanchez | CSE110 | Summer 2020 | 12 printf

    Method • %d à to print an integer • %5d à to print an integer with width 5 • %7.2f à to print a floating point number with 2 digits after the decimal point and with width 7 (including the decimal point) • %s à to print a string
  8. Javier Gonzalez-Sanchez | CSE110 | Summer 2020 | 13 Example

    String str = "apples"; int num = 5; double price = 3.477; System.out.printf("%d %s cost $%.2f\n", num, str, price); //The above prints: //5 apples cost $3.48
  9. CSE110 - Principles of Programming Javier Gonzalez-Sanchez [email protected] Summer 2022

    Disclaimer. These slides can only be used as study material for the class CSE110 at ASU. They cannot be distributed or used for another purpose.