Input and Formatted Output (printf)

Slides:



Advertisements
Similar presentations
 2005 Pearson Education, Inc. All rights reserved Introduction.
Advertisements

1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
The Print Formatting Statement … named printf. 2 Introduction to printf statements print and println statements don’t allow us to easily format output.
Chapter 2 Console Input and Output Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Introduction to Computer Programming Looping Around Loops I: Counting Loops.
Chapter 2 Console Input and Output Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Introduction to Computer Programming Loops N Decisions If/Else Counting Loops.
Input and Output The system console. In the beginning … When computers were relatively expensive and rare, most users interacted with a terminal –CRT.
© 2006 Pearson Addison-Wesley. All rights reserved2-1 Console Input Using the Scanner Class Starting with version 5.0, Java includes a class for doing.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Parameters, Return, and Interactive Programs with Scanner.
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;
2.2 Information on Program Appearance and Printing.
11 Chapter 3 DECISION STRUCTURES CONT’D. 22 FORMATTING FLOATING-POINT VALUES WITH THE DecimalFormat CLASS We can use the DecimalFormat class to control.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf.
Methods (Functions) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
EPSII 59:006 Spring Introduction In this lecture  Formatted Input/Output scanf and printf  Streams (input and output) gets, puts, getchar, putchar.
Introduction to Java Thanks to Dan Lunney (SHS). Java Basics File names The “main” method Output to screen Escape Sequence – Special Characters format()
Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
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.
Arrays and Array Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
First Programs CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Can we talk?. In Hello World we already saw how to do Standard Output. You simply use the command line System.out.println(“text”); There are different.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) public static void main(String[]
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.
3. FORMATTED INPUT/OUTPUT. The printf Function The first argument in a call of printf is a string, which may contain both ordinary characters and conversion.
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)
Lecture 4 – Scanner & Style. Console Output The console that starts a Java application is typically known as the standard output device. The standard.
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.
Slides prepared by Rose Williams, Binghamton University Console Input and Output.
Simple Console Output. What we will briefly discuss System.out.println( … ) System.out.print( … ) System.out.printf( … )
Simple Console Output CS 21a. What we will briefly discuss System.out.println( … ) System.out.print( … ) System.out.printf( … )
Input and Output The system console. In the beginning … When computers were relatively expensive and rare, most users interacted with a terminal –CRT.
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.
Formatted Output (printf) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Arrays and Array Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Java Fundamentals 4. Java Programming: From Problem Analysis to Program Design, Second Edition2 Parsing Numeric Strings  Integer, Float, and Double are.
Strings CSE 1310 – Introduction to Computers and Programming
Lecture 4 – Scanner & Style
Chapter 9 - Formatted Input/Output
User Input ICS2O.
Java Fundamentals 4.
Strings CSE 1310 – Introduction to Computers and Programming
Strings CSE 1310 – Introduction to Computers and Programming
Input/Output.
Formatted Output (printf)
Exceptions and User Input Validation
Console Input and Output
Chapter 5: Control Structures II
First Programs CSE 1310 – Introduction to Computers and Programming
OUTPUT STATEMENTS GC 201.
Methods (Functions) CSE 1310 – Introduction to Computers and Programming Alexandra Stefan and Vassilis Athitsos University of Texas at Arlington.
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
CSS 161 Fundamentals of Computing Introduction to Computers & Java
Chapter 9 - Formatted Input/Output
Introduction to Computer Programming
Variables, Types, Operations on Numbers
Variables, Types, Operations on Numbers
elementary programming
Introduction to Java Brief history of Java Sample Java Program
Strings CSE 1310 – Introduction to Computers and Programming
First Programs CSE 1310 – Introduction to Computers and Programming
Presentation transcript:

Input and Formatted Output (printf) CSE 1310 – Introduction to Computers and Programming University of Texas at Arlington

Book reference 2.3 Input and Output

Input Import: java.util.Scanner Create a Scanner object: Scanner kb = new Scanner(System.in); (You can use any name instead of kb. E.g: Scanner in = new Scanner(System.in); ) E.g. read in (from the user/keyboard): Any of the methods above for reading data in, when executed, “halt” to allow the user to type data. Only after the user hits Enter the continues to execute. Read data and store it as type: Method call (on a Scanner object named kb) Example instruction int kb.nextInt() int n = kb.nextInt(); double kb.nextDouble() double salary = kb.nextDouble(); String kb.nextLine() String name = kb.nextLine(); (data until Enter, Enter dissapears) kb.next() String name = kb.next(); (data until space or Enter, Enter remains)

Entering more than one piece of data per line int age=0; double temp=0; String nm = ""; System.out.println("Enter (separated by one space): age name number"); age = kb.nextInt(); nm = kb.next(); // NOT nextLine temp = kb.nextDouble(); System.out.printf("Hi %s!%n", nm); System.out.printf("The outside temperature is %.2f.%nYour age is %d.%n", temp, age); Sample run: Enter (separated by one space): age name number 20 Sam 87.5 Hi Sam! The outside temperature is 87.50. Your age is 20.

next() vs nextLine() Code Output System.out.print("What is your name? "); // nextLine reads the whole line (up to new line): name = kb.nextLine(); System.out.println("Hello " + name); What is your name? Alex Stefan Hello Alex Stefan // next reads up to first separator (space, Enter, tab): name = kb.next(); Hello Alex

Why nextLine() seems to not work sometimes - When the user presses Enter, the corresponding symbol (%n) is recorded in the input stream. So there will be a character there for the Enter (also called new-line character: %n or \n). - nextInt(), nextDouble() and next() do NOT “eat” the Enter at the end of the line. - nextLine() DOES consume the Enter from the end of the line. - If nextLine() is used after a next()/nextInt()/nextDouble() it will just read the Enter left there from these methods. Solution: use an extra nextLine() just to consume that Enter. Code Output System.out.print("What is your name? "); name = kb.next(); // will NOT “eat” the Enter after Alex System.out.println("Hello " + name); System.out.print("What is your last name? "); last = kb.nextLine(); System.out.println("Hello " + last); What is your name? Alex Hello Alex What is your last name? Hello System.out.print("What is your last name? "); kb.nextLine(); // it will “eat” the Enter after Alex What is your last name? Stefan Hello Stefan

System.out.printf public class example1 { public static void main(String[] args) { int days = 31; String month = "July"; double temperature = 85.3; System.out.printf("There are %d days in %s%n", days, month); System.out.printf("Average temperature in %s: %f degrees%n", month, temperature); } Output: There are 31 days in July Average temperature in July: 85.300000 degrees System.out.printf gives you an easy way to print nicer output, by combining text, variables, and other values.

System.out.printf printf works as follows: public class example1 { public static void main(String[] args) { int days = 31; String month = "July"; double temperature = 85.3; System.out.printf("There are %d days in %s%n", days, month); System.out.printf("Average temperature in %s: %f degrees%n", month, temperature); } printf works as follows: It starts printing the text in the first argument. There are

System.out.printf printf works as follows: public class example1 { public static void main(String[] args) { int days = 31; String month = "July"; double temperature = 85.3; System.out.printf("There are %d days in %s%n", days, month); System.out.printf("Average temperature in %s: %f degrees%n", month, temperature); } printf works as follows: It starts printing the text in the first argument. When it finds the first % sign, it prints the second argument. There are 31

System.out.printf printf works as follows: public class example1 { public static void main(String[] args) { int days = 31; String month = "July"; double temperature = 85.3; System.out.printf("There are %d days in %s%n", days, month); System.out.printf("Average temperature in %s: %f degrees%n", month, temperature); } printf works as follows: It starts printing the text in the first argument. When it finds the first % sign, it prints the second argument. It continues printing text. There are 31 days in

System.out.printf printf works as follows: public class example1 { public static void main(String[] args) { int days = 31; String month = "July"; double temperature = 85.3; System.out.printf("There are %d days in %s%n", days, month); System.out.printf("Average temperature in %s: %f degrees%n", month, temperature); } printf works as follows: It starts printing the text in the first argument. When it finds the first % sign, it prints the second argument. It continues printing text. When it finds the second % sign, it prints the third argument. There are 31 days in July

System.out.printf printf works as follows: public class example1 { public static void main(String[] args) { int days = 31; String month = "July"; double temperature = 85.3; System.out.printf("There are %d days in %s%n", days, month); System.out.printf("Average temperature in %s: %f degrees%n", month, temperature); } printf works as follows: It starts printing the text in the first argument. When it finds the first % sign, it prints the second argument. It continues printing text. When it finds the second % sign, it prints the third argument. And so on, until the entire text is processed.

System.out.printf public class example1 { public static void main(String[] args) { int days = 31; String month = "July"; System.out.printf("There are %d days in %s%n", days, "July"); System.out.printf("Average temperature in %s: %f degrees%n", month, (85.1 + 85.5) / 2.0); } The values that you provide in the second argument, third argument, and so on, can be: variables, like days in the example above. constants, like "July" in the example above. expressions, like: (85.1 + 85.5) / 2.0 in the example above. Math.PI, (int)Math.floor(5.3)

Format Specifiers %d, %f, %s are called format specifiers. public class example1 { public static void main(String[] args) { int days = 31; String month = "July"; System.out.printf("There are %d days in %s%n", days, "July"); System.out.printf("Average temperature in %s: %f degrees%n", month, (85.1 + 85.5) / 2.0); } %d, %f, %s are called format specifiers. A format specifier must match the value that will be printed. %d is for values of type int %f is for values of type double %s is for values of type String or char %c is for values of type char (a type we will see soon). %b is for values of type boolean (a type we will see soon).

Specifying Width public class example1 { public static void main(String[] args) { System.out.printf("%20s, current temperature: %8.2f%n", "Dallas", 106.7431); "San Francisco", 64.918262); "surface of the sun", 12000.0); } After the % sign, you can put a number, specifying the minimum width for that value. For example: %5d means "allocate at least 5 spaces for that int". %10s means "allocate at least 10 spaces for that string". %7f means "allocate at least 7 spaces for that double". %7.2f means "allocate at least 7 spaces for that double, but only two after the decimal point". %.2f means "allocate as many spaces as needed for that double, but only two after the decimal point". This way you get nicely aligned columns in the output.

Specifying Width public class example1 { public static void main(String[] args) { System.out.printf("%20s, current temperature: %8.2f%n", "Dallas", 106.7431); "San Francisco", 64.918262); "surface of the sun", 12000.0); } Output: Dallas, current temperature: 106.74 San Francisco, current temperature: 64.92 surface of the sun, current temperature: 12000.00

Not Specifying Width Compare the previous output to this one. public class example1 { public static void main(String[] args) { System.out.printf("%s, current temperature: %f%n", "Dallas", 106.7431); "San Francisco", 64.918262); "surface of the sun", 12000.0); } Output: Dallas, current temperature: 106.743100 San Francisco, current temperature: 64.918262 surface of the sun, current temperature: 12000.000000 Compare the previous output to this one. In this version of the code, we do not specify widths in printf. The output does not look as nice.

Printing a New Line with %n public class example1 { public static void main(String[] args) { System.out.printf("%s, current temperature: %8.2f%n", "Dallas", 106.7431); "San Francisco", 64.918262); "surface of the sun", 12000.0); } Output: Dallas, current temperature: 106.743100 San Francisco, current temperature: 64.918262 surface of the sun, current temperature: 12000.000000 When you want to print a new line, put the special code %n in your text.

Printing a New Line with %n public class example1 { public static void main(String[] args) { System.out.printf("%s, current temperature: %8.2f", "Dallas", 106.7431); System.out.printf("%20s, current temperature: %8.2f", "San Francisco", 64.918262); "surface of the sun", 12000.0); } Output: Dallas, current temperature: 106.74 San Francisco, current temperature: 64.92 surface of the sun, current temperature: If you forget new lines, the output can look pretty ugly!

Syntax of System.out.printf Syntax: System.out.printf("t1f1t2f2t3f3…tnfntn+1", v1, v2, v3, …, vn); ti is text. You can put in there whatever you want. fi is a format specifier. It specifies several things: Value vi should be printed at that point. The type of value vi. How many characters should vi occupy. vi is an int, double, or string. It can be a variable. It can be a constant, like 5, or 2.5, or "hello". It can be any expression that evaluates to an int, double, or string.

Syntax of System.out.printf Syntax: System.out.printf("t1f1t2f2t3f3…tnfntn+1", v1, v2, v3, …, vn); ti is text. You can put in there whatever you want. fi is a format specifier. It specifies several things: vi is an int, double, or string. System.out.printf("There are %d days in %s%n", 31, "July"); What is each ti in the line above?

Syntax of System.out.printf Syntax: System.out.printf("t1f1t2f2t3f3…tnfntn+1", v1, v2, v3, …, vn); ti is text. You can put in there whatever you want. fi is a format specifier. It specifies several things: vi is an int, double, or string. System.out.printf("There are %d days in %s%n", 31, "July"); What is each ti in the line above? t1 = "There are " t2 = " days in " t3 = “%n"

Syntax of System.out.printf Syntax: System.out.printf("t1f1t2f2t3f3…tnfntn+1", v1, v2, v3, …, vn); ti is text. You can put in there whatever you want. fi is a format specifier. It specifies several things: vi is an int, double, or string. System.out.printf("There are %d days in %s%n", 31, "July"); What is each fi in the line above?

Syntax of System.out.printf Syntax: System.out.printf("t1f1t2f2t3f3…tnfntn+1", v1, v2, v3, …, vn); ti is text. You can put in there whatever you want. fi is a format specifier. It specifies several things: vi is an int, double, or string. System.out.printf("There are %d days in %s%n", 31, "July"); What is each fi in the line above? f1 = %d f2 = %s

Syntax of System.out.printf Syntax: System.out.printf("t1f1t2f2t3f3…tnfntn+1", v1, v2, v3, …, vn); ti is text. You can put in there whatever you want. fi is a format specifier. It specifies several things: vi is an int, double, or string. System.out.printf("There are %d days in %s%n", 31, "July"); What is each vi in the line above?

Syntax of System.out.printf Syntax: System.out.printf("t1f1t2f2t3f3…tnfntn+1", v1, v2, v3, …, vn); ti is text. You can put in there whatever you want. fi is a format specifier. It specifies several things: vi is an int, double, or string. System.out.printf("There are %d days in %s%n", 31, "July"); What is each vi in the line above? v1 = 31 v2 = "July"

Examples (added 9/9/15) Example Output: Notice the effect of public class hello1 { public static void main(String[] args) { System.out.printf("%-10.2f%n", 18.0); // left aligned: - System.out.printf("%10.2f%n", 20.0); // right aligned System.out.printf("%10.2f", 10.2); // no text System.out.printf(“%n"); // only %n System.out.printf("%10.2f%5d%n", 15.7,3); // no text and %n System.out.printf("%10.2f%d%n", 15.7,3); System.out.printf("%10.2f%d", 15.7,3); System.out.printf(“%n%10.2f%n%5d%n", 11.3,8); } Example Output: Notice the effect of %-10.2f for 18.00 18.00 20.00 10.20 15.70 3 15.703 11.30 8

Escape sequences (added 9/9/15) public class hello1 { public static void main(String[] args) { System.out.printf("some\ttext%nmore text"); System.out.printf("\roverwrite"); System.out.printf(“%nover\b\b\bwrite"); System.out.println(“%n123456\b\b\b\bXY"); System.out.printf(“%n\'\"\\"); System.out.printf(“%n"); } } Output: some text overwrite owrite 12XY '"\ Escape sequences: %n - new line (note: use %n (platform appropriate), not \n ) \t - tab \r - carriage return (back to the beginning of the line) \b - backspace (back one character) \' - insert single quote in text \" - insert double quote in text \\ - insert backslash in text To print the % sign, use %%. E.g. System.out.printf("%%");

Formatted Printing - References Java API: https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax Oracle Java tutorial (brief): https://docs.oracle.com/javase/tutorial/java/data/numberformat.html FUN: You can also build a string (without printing it) using String.format(…). The format method works like the System.out.printf(…), but it returns a string. String s; s = String.format("There are %d days in %s%n", 31, "July"); System.out.println(s);

How the output screen “works” You always print: Left to right and From top down You can go back to the beginning of the line you’re on with \r You can NEVER go up a line So if you need to print something that looks like a table of numbers, you must print it row –by-row (according to the desired output). You cannot print it column-by-column. If you printed more than a screen length, it scrolls down so you always have the line you are on at the bottom. To see the earlier lines, scroll up. You can simulate clearing the screen by printing enough new lines to push the previous outputted text out of the visible range. See this image.

Extra

The Circles Program, Revisited import java.util.Scanner; public class hello1 { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.printf("Please enter the radius: "); double radius = in.nextDouble(); double circumference = 2 * Math.PI * radius; double area = Math.PI * Math.pow(radius, 2); System.out.println(circumference); System.out.println(area); } <-- Last version we saw. Used println. Example Output:

The Circles Program, Revisited import java.util.Scanner; public class hello1 { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.printf("Please enter the radius: "); double radius = in.nextDouble(); double circumference = 2 * Math.PI * radius; double area = Math.PI * Math.pow(radius, 2); System.out.println(circumference); System.out.println(area); } <-- Last version we saw. Used println. Example Output: Please enter the radius: 10 62.83185307179586 314.1592653589793 The output does not look very nice. Too many decimals. No text. Can we get output like this? Please enter the radius: 10 The circumference is 62.83. The area is 314.16.

The Circles Program, Revisited import java.util.Scanner; public class example1 { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.printf("Please enter the radius: "); double radius = in.nextDouble(); double circumference = 2 * Math.PI * radius; double area = Math.PI * Math.pow(radius, 2); System.out.printf("The circumference is %.2f.%n", circumference); System.out.printf("The area is %.2f.%n", area); } Improved version, using printf. Example Output: Please enter the radius: 10 The circumference is 62.83. The area is 314.16.