Printing Literals
Most characters can be printed
Certain "problem" characters, such as the quotation mark (")
Must be represented by escape sequences
Represented by a backslash \ followed by an escape character
49 trang |
Chia sẻ: nguyenlam99 | Lượt xem: 1072 | Lượt tải: 0
Bạn đang xem trước 20 trang tài liệu Java - Formatted output, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
29Formatted Output1All the news that’s fit to print.Adolph S. OchsWhat mad pursuit? What struggle to escape?John KeatsRemove not the landmark on the boundary of the fields.Amenehope2OBJECTIVESIn this chapter you will learn: To understand input and output streams.To use printf formatting.To print with field widths and precisions.To use formatting flags in the printf format string.To print with an argument index.To output literals and escape sequences.To format output with class Formatter. 329.1 Introduction 29.2 Streams 29.3 Formatting Output with printf 29.4 Printing Integers 29.5 Printing Floating-Point Numbers 29.6 Printing Strings and Characters 29.7 Printing Dates and Times 29.8 Other Conversion Characters 29.9 Printing with Field Widths and Precisions 29.10 Using Flags in the printf Format String 29.11 Printing with Argument Indices 29.12 Printing Literals and Escape Sequences 29.13 Formatting Output with Class Formatter 29.14 Wrap-Up 429.1 Introduction Method printfFormats and outputs data to the standard output stream, System.outClass FormatterFormats and outputs data to a specified destinationE.g., a string or a file output stream529.2 Streams StreamsSequences of bytesCan often be redirectedStandard input – keyboardStandard output – screenStandard error – screenMore in Chapters 14 and 24629.3 Formatting Output with printf printfPrecise output formattingConversion specifications: flags, field widths, precisions, etc.Can perform roundingaligning columnsright/left justificationinserting literal charactersexponential formatoctal and hexadecimal formatfixed width and precisiondate and time format729.3 Formatting Output with printf (Cont.)Format StringDescribe the output formatConsist of fixed text and format specifierFormat specifierPlaceholder for a valueSpecify the type of data to outputBegins with a percent sign (%) and is followed by a conversion characterE.g., %s, %dOptional formatting informationArgument index, flags, field width, precisionSpecified between % and conversion character829.4 Printing Integers IntegerWhole number (no decimal point): 25, 0, -9Positive, negative, or zeroOnly minus sign prints by defaultFormatprintf( format-string, argument-list );format-stringDescribes the output formatargument-listContains the values that corresponding to the format specifiers9Fig. 29.1 | Integer conversion characters. 10Output the integer in octal formatOutput the integer in hexadecimal formatOutput the integer in hexadecimal format with capital lettersOutput positive and negative integers1129.5 Printing Floating-Point Numbers Floating Point NumbersHave a decimal point (33.5)Computerized scientific notation (exponential notation)150.4582 is 1.504582 x 10² in scientific150.4582 is 1.504582e+02 in exponential (e stands for exponent)use e or Ef – print floating point with at least one digit to left of decimalg (or G) - prints in f or e (E) Use exponential if the magnitude is less than 10-3, or greater than or equal to 10712Fig. 29.3 | Floating-point conversion characters. 13Output positive and negative floating-point numbers using the e conversion characterOutput floating-point number with uppercase E preceding the exponentOutput floating-point number using the f conversion characterOutput floating-point number using the g and G conversion character1429.6 Printing Strings and Characters Conversion character c and CRequire charC displays the output in uppercase lettersConversion character s and SStringObjectImplicitly use object’s toString methodS displays the output in uppercase letters15Common Programming Error 29.1Using %c to print a string causes an IllegalFormatConversionException—a string cannot be converted to a character.16Display character with conversion character cDisplay string with conversion character sDisplay string with conversion characters s and SDisplay Integer object with conversion characters s1729.7 Printing Dates and Times Conversion characters t and T Print dates and times in various formatsFollowed by a conversion suffix characterRequire the corresponding argument to be of type long, Long, Calendar or DateConversion suffix charactersSpecify the date and/or time formatFormat date and time compositionsFormat dateFormat time18Fig. 29.6 | Date and time composition conversion suffix characters. 19Fig. 29.7 | Date formatting conversion suffix characters. 20Fig. 29.8 | Time formatting conversion suffix characters. 21Obtain a Calendar with the current date and timeUse the optional argument index to indicate that all format specifiers in the format string use the first argumentUse the Calendar object in printf statements as the value to be formatted with conversion character t222329.8 Other Conversion CharactersRemaining conversion charactersb or Bboolean or Boolean valueh or HString representation of an object’s hash code in hexadecimal format%Percent characternPlatform-specific line separator\r\n on Windows\n on UNIX\Linux24Common Programming Error 29.2 Trying to print a literal percent character using % rather than %% in the format string might cause a difficult-to-detect logic error. When % appears in a format string, it must be followed by a conversion character in the string. The single percent could accidentally be followed by a legitimate conversion character, thus causing a logic error.25Fig. 29.10 | Other conversion specifiers. 26Print the value of boolean values false and trueAssociate a String and a null object to %b and %BPrint the string representations of the hash code values for strings “hello” and “Hello”Print null in uppercase lettersPrint the % character in a string and a platform-specific line separator2729.9 Printing with Field Widths and PrecisionsField widthSize of field in which data is displayedIf width larger than data, default right justifiedIf field width too small, increases to fit dataMinus sign uses one character position in fieldInteger width inserted between % and conversion specifierE.g., %4d – field width of 4Can be used with all format specifiers except the line separator (%n)2829.9 Printing with Field Widths and Precisions (Cont.)PrecisionMeaning varies depending on data typeFloating pointNumber of digits to appear after decimal (e or E and f)Maximum number of significant digits (g or G)StringsMaximum number of characters to be written from stringFormatUse a dot (.) then precision number after % e.g., %.3f2929.9 Printing with Field Widths and Precisions (Cont.)Field width and precisionCan both be specified%width.precision%5.3fNegative field width – left justifiedPositive field width – right justifiedPrecision must be positiveExample:printf( "%9.3f", 123.456789 );30Common Programming Error 29.3Not providing a sufficiently large field width to handle a value to be printed can offset other data being printed and produce confusing outputs. Know your data!31Print positive numbers with field widthPrint negative numbers with field width32Print same floating-point number with same precision but different conversion characterPrint string with precision3329.10 Using Flags in the printf Format StringFlagsSupplement formatting capabilitiesPlace flag immediately to the right of percent signSeveral flags may be combined34Fig. 29.14 | Format string flags. 35Right justify a string, an integer, a character and a floating-point numberleft justify a string, an integer, a character and a floating-point number36Print a positive number with a plus sign37Prefix a space to the positive number with the space flag38Use the # flag to prefix 0 to the octal value and 0x to the hexadecimal value39Combine the + flag and the 0 flag print 452 in a field of width 9 with a + sign and leading zerosPrint 452 in a field of width 9 using only the 0 flagPrint 452 in a field of width 9 using only the space flag40Use the comma flag to display a decimal and a floating-point number with the thousands separator41OutlineParenthesesFlagTest.java Lines 8-10Program outputEnclose negative numbers in parentheses using the ( flag4229.11 Printing with Argument IndicesArgument indexOptional decimal integer followed by a $ signIndicate the position of the argument in the argument listE.g., 1$ -- first argumentUsageReorder the outputAvoid duplicating arguments43OutlineArgumentIndexTest Lines 11-13Program outputPrint arguments in the argument list in reverse order using the argument index4429.12 Printing Literals and Escape SequencesPrinting LiteralsMost characters can be printedCertain "problem" characters, such as the quotation mark (")Must be represented by escape sequencesRepresented by a backslash \ followed by an escape character45Common Programming Error 29.4Attempting to print as literal data in a printf statement a double quote or backslash character without preceding that character with a backslash to form a proper escape sequence might result in a syntax error. 46Fig. 29.23 | Escape sequences. 4729.13 Formatting Output with Class FormatterClass FormatterProvides same formatting capabilities as printfOutput formatted data to a specified destinationE.g., a file on diskBy default, Formatter creates a string in memoryString static method formatCreate a string in memory without Formatter48Create a Formatter object using the default constructor, which will build a string in memoryInvoke method format to format the outputInvoke Formatter’s toString method to get the formatted data as a string49
Các file đính kèm theo tài liệu này:
- javahtp7e_29_8237.ppt