SlideShare a Scribd company logo
Click to add Text
Basic Input and Output
Display output
System.out.println("I'm a string" + " again");
System.out.print("apple");
System.out.print("bananan");
System.out.print("grape");
I'm a string again
applebanana
grape
Input
int c = System.in.read( ); // read 1 byte
byte[] b;
System.in.read( b ); // array of bytes
Scanner console = new Scanner(System.in);
String word = console.next();
String line = console.nextLine();
int number = console.nextInt();
double x = console.nextDouble();
Use a Scanner to read input as int, double, String, etc.
System.in can only read bytes. Not very useful.
Console Output: print
System.out is a PrintStream object.
It has a "print" method to output (display) :
 any primitive data type
 a String
 any Object
int a = 100;
System.out.print("a = "); // print a string
System.out.print(a); // print an int
System.out.print('t'); // print a TAB char
System.out.print("Square Root of 2 = ");
System.out.print(Math.sqrt(2)); // print double
a = 100 Square Root of 2 = 1.4142135623730951
Console Output: println
println is like print, but after printing a value it also
outputs a newline character to move to start of next line.
println can output:
 any primitive type
 a String
 any Object: it automatically calls object.toString()
System.out.print("a = "); // print a string
System.out.println(a); // print an int
System.out.println(); // empty line
System.out.println(1.0/3.0); // print double
a = 100
0.333333333333333
More on print and println
To print several values at once, if the first value is a
String, you can "join" the other values using +
System.out.println("a = " + a);
a = 100
System.out.print("a = "); // print a string
System.out.println(a); // print an int
Is the same as:
Printing an Object
Date now = new Date( );
System.out.println( now );
// invokes now.toString()
If the argument is an object, Java will call the object's
toString() method and print the result.
Common Error
ERROR:
double angle = Math.toRadians(45);
double x = Math.sin(angle);
System.out.println("sin(" , angle ,") = " , x);
mus use + not comma
Formatted Output: printf
Creating nice output using println can be difficult.
public class SalesTax {
public static final double VAT = 0.07; // 7% tax
public static void showTotal( double amount) {
double total = amount * ( 1.0 + VAT );
System.out.println("The total including VAT is "
+total+" Baht");
}
public static void main( String [] args ) {
showTotal(10000);
showTotal(95);
}
}
The total including VAT is 10700.0 Baht
The total including VAT is 104.86 Baht
printf
Java 1.5 added a "printf" statement similar to C:
public static void showTotal( double amount) {
double total = amount * ( 1.0 + VAT );
System.out.printf(
"The total including VAT is %8.2f Baht", total);
}
public static void main( String [] args ) {
showTotal(10000);
showTotal(95);
}
The total including VAT is 10700.00 Baht
The total including VAT is 104.86 Baht
Format: output a float (%f) using 8
characters with 2 decimal digits
printf Syntax
The syntax of printf is:
System.out.printf(Format_String, arg1, arg2, ...);
or (no arguments):
System.our.printf(Format_String);
The Format_String can contain text and format codes. Values of
arg1, arg2, are substituted for the format codes.
int x = 100, y = 225;
System.out.printf("The sum of %d and %d is %6dn",
x, y, x+y );
%d is the format code to output
an "int" or "long" value.
%6d means output an integer
using exactly 6 digit/spaces
printf Syntax
Example: print the average
int x = 100, y = 90;
System.out.printf("The average of %d and %d is %6.2fn",
x, y, (x+y)/2.0 );
%6.2f means output a floating point using a
width of 6 and 2 decimal digits.
The average of 100 and 90 is 95.00
%6.2f
%d
Common printf Formats
Format Meaning Examples
%d decimal integers %d %6d
%f fixed pt. floating-point %f %10.4f
%e scientific notation %10e (1.2345e-02)
%g general floating point %10g
(use %e or %f, whichever is more compact)
%s String %s %10s %-10s
%c Character %c
String owner = "Taksin Shinawat";
int acctNumber = 12345;
double balance = 4000000000;
System.out.printf("Account %6d Owner %-18s has %10.2fn",
acctNumber, owner, balance );
Account 12345 Owner Taksin Shinawat has 4000000000.00
More details on printf
 printf is an instance of the Formatter class.
 It is predefined for System.out.
 System.out.printf(...) is same as System.out.format(...).
 For complete details see Java API for "Format".
 For tutorial, examples, etc. see:
 Sun's Java Tutorial
 Core Java, page 61.
String.format
A useful method that creates a String using a format.
/** describe a bank acount */
String name = "John Doe";
long accountId = 12345;
double balance = 123.456;
String result = String.format(
"Acct: %09d Owner: %s Balance: %.2f",
accountId, name, balance );
return result;
Acct: 000012345 Owner: John Doe Balance: 123.46
Click to add Text
Input
Input byte-by-byte
System.in is an InputStream object.
It reads data one byte at a time, or an array of bytes.
Use System.in.read( ) to get "raw" data, such as an
image:
int a = System.in.read( );
if (a < 0) /* end of input */;
else {
byte b = (byte)a;
handleInput( b );
}
Boring, isn't it?
Input Line-by-Line
To get a line of input as a String, you can create a
BufferedReader object that "wraps" System.in.
BufferedReader reader = new BufferedReader(
new InputStreamReader( System.in ) );
String s = reader.readLine( ); // read one line
The readLine( ) method removes the NEWLINE (n)
from the input, so you won't see it as part of the string.
Check for end of data
If there is no more data in the input stream, readLine( )
returns a null String.
For console input, readLine( ) will wait (block) until user
inputs something.
Here is how to test for end of data:
BufferedReader reader = new BufferedReader(
new InputStreamReader( System.in ) );
String s = reader.readLine( ); // read one line
if ( s == null ) return; // end of data
Handling I/O Errors
When you use System.in.read or a BufferedReader an
input error can occur -- called an IOException.
Java requires that your program either "catch" this
exception to declare that it might "throw" this exception.
To be lazy and "throw" the exception use:
public static void main(String [] args)
throws IOException {
BufferedReader reader = new BufferedReader(
new InputStreamReader( System.in ) );
// read a line of input
String inline = reader.readLine( );
Catching I/O Errors
To "catch" the exception and do something, use:
BufferedReader reader = new BufferedReader(
new InputStreamReader( System.in ) );
// read a line of input.
// display message and return if error
String line = null;
try {
line = bin.readLine( );
buf.append( line );
}
catch( IOException ioe ) {
System.err.println( ioe.getMessage() );
return;
}
Flexible Input: Scanner class
The Scanner class allow much more flexible input.
A Scanner can:
 read entire line or one word at a time
 test for more data
 test if the next input (word) is an int, long, double, etc.
 read input and convert to int, long, float, double
 skip unwanted data
 report errors (Exceptions) that occur
Import Scanner
Scanner is a "utility" so it is package java.util.
You should import this class to use it:
package myapp;
import java.util.Scanner;
...
public class InputDemo {
Create a Scanner Object
Scanner "wraps" an InputStream.
You give the InputStream object as parameter when you
create a Scanner object...
// create a Scanner to read from System.in
Scanner console = new Scanner( System.in );
Where to Create Scanner object?
1) You can create a Scanner as a local variable
public void myMethod( ) { // no IOException !
// create a Scanner as a local variable
Scanner in = new Scanner( System.in );
// read some different types of data
int count = in.nextInt( );
public class InputDemo {
// create a Scanner as static attribute
static Scanner console =
new Scanner( System.in );
// can use console in any method.
2) or create as an attribute.
Typically a static attribute since System.in is static.
Using Scanner
Look at some simple examples
public void myMethod( ) { // no IOException !
// create a Scanner to process System.in
Scanner in = new Scanner( System.in );
// read some different types of data
int count = in.nextInt( );
long big = in.nextLong( );
float x = in.nextFloat( );
double y = in.nextDouble( );
// read Strings
String word = scan.next( ); // next word
String line = scan.nextLine( ); // next line
Input Errors
If you try to read an "int" but the next input is not an integer
then Scanner throws an InputMismatchException
Scanner scan = new Scanner( System.in );
// read a number
System.out.print("How many Baht? ");
int amount = scan.nextInt( );
How many Baht? I don't know
Exception in thread "main"
java.util.InputMismatchException
convert next input
word to an "int"
How to Test the Input
Scanner has methods to test the next input value:
Scanner scanner = new Scanner( System.in );
int amount;
// read a number
System.out.print("How many Baht? ");
if ( scanner.hasNextInt( ) )
amount = scanner.nextInt( );
else {
System.out.println("Please input an int");
scanner.nextLine(); // discard old input
}
How many Baht? I don't know
Please input an int
true if the next input
value is an "int"
Testing the input
So now you can check for invalid input.
But, what do you do with the bad input?
If scan.hasNextInt( ) is false, then the program doesn't
read it.
So, the bad input is still waiting to be read. Like this:
How many Baht? I don't know
Next input value to read.
We want to remove this bad input, so we can ask the
user to try again. ...what should we do?
Discarding the input
If the input is wrong, then throw it away by reading the
line and discarding it.
get the input line but don't assign
it to anything! (discard it)
Scanner scanner = new Scanner( System.in );
int amount;
// read a number
System.out.print("How many Baht? ");
if ( scanner.hasNextInt( ) )
amount = scanner.nextInt( );
else {
System.out.println("Please input an int");
scanner.nextLine(); // discard input
Useful Scanner Methods
Return type Method Meaning
String next() get next "word"
String nextLine() get next line
int nextInt() get next word as int
long nextLong() get next word as long
float nextFloat() get next word as float
double nextDouble() get next word as double
boolean hasNext() true if there is more input
boolean hasNextInt() true if next word can be "int"
boolean hasNextLong() true if next word can be "long"
boolean hasNextFloat() true if next word can be "float"
boolean hasNextDouble() true if next word can be
"double"
See Java API for java.io.Scanner for a complete list of methods.
Input/Output Example
Read some numbers and output their sum...
Scanner scanner = new Scanner( System.in );
double sum = 0.0;
// prompt user for input
System.out.print("Input some numbers: ");
// read as long as there are more numbers
while ( scanner.hasNextDouble( ) ) {
double x = scanner.nextDouble( );
sum = sum + x;
}
System.out.println();
System.out.println("The sum is "+sum);
TUGAS
Implementasikan contoh-contoh listing program pada
materi dan dikumpulkan.
- isi dari tugas adalah listing program dan hasil output
dari listring tersebut
- tugas dibuat dalam kelompok yang terdiri dari 4 orang
- tuliskan nama-nama anggota kelompok pada lembar
pertama tugas

More Related Content

Similar to 07-Basic-Input-Output.ppt (20)

Lecture 3.pptx
Lecture 3.pptxLecture 3.pptx
Lecture 3.pptx
ShehabEldinSaid
 
Programming with Java: the Basics
Programming with Java: the BasicsProgramming with Java: the Basics
Programming with Java: the Basics
Jussi Pohjolainen
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)
Chhom Karath
 
JAVA (UNIT 3)
JAVA (UNIT 3)JAVA (UNIT 3)
JAVA (UNIT 3)
Dr. SURBHI SAROHA
 
Introduction to objects and inputoutput
Introduction to objects and inputoutput Introduction to objects and inputoutput
Introduction to objects and inputoutput
Ahmad Idrees
 
2 1 data
2 1  data2 1  data
2 1 data
Ken Kretsch
 
ppt on scanner class
ppt on scanner classppt on scanner class
ppt on scanner class
deepsxn
 
Chapter 3.4
Chapter 3.4Chapter 3.4
Chapter 3.4
sotlsoc
 
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/OCore Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
WebStackAcademy
 
All Of My Java Codes With A Sample Output.docx
All Of My Java Codes With A Sample Output.docxAll Of My Java Codes With A Sample Output.docx
All Of My Java Codes With A Sample Output.docx
adhitya5119
 
Numerical Data And Expression
Numerical Data And ExpressionNumerical Data And Expression
Numerical Data And Expression
PRN USM
 
02slide_accessible.pptx
02slide_accessible.pptx02slide_accessible.pptx
02slide_accessible.pptx
MattMarino13
 
Computer science input and output BASICS.pptx
Computer science input and output BASICS.pptxComputer science input and output BASICS.pptx
Computer science input and output BASICS.pptx
RathanMB
 
M C6java2
M C6java2M C6java2
M C6java2
mbruggen
 
ExtraFileIO.pptx
ExtraFileIO.pptxExtraFileIO.pptx
ExtraFileIO.pptx
NguynThiThanhTho
 
Java session08
Java session08Java session08
Java session08
Niit Care
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
OOP-java-variables.pptx
OOP-java-variables.pptxOOP-java-variables.pptx
OOP-java-variables.pptx
ssuserb1a18d
 
JPC#8 Introduction to Java Programming
JPC#8 Introduction to Java ProgrammingJPC#8 Introduction to Java Programming
JPC#8 Introduction to Java Programming
Pathomchon Sriwilairit
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
HCMUTE
 
Programming with Java: the Basics
Programming with Java: the BasicsProgramming with Java: the Basics
Programming with Java: the Basics
Jussi Pohjolainen
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)
Chhom Karath
 
Introduction to objects and inputoutput
Introduction to objects and inputoutput Introduction to objects and inputoutput
Introduction to objects and inputoutput
Ahmad Idrees
 
ppt on scanner class
ppt on scanner classppt on scanner class
ppt on scanner class
deepsxn
 
Chapter 3.4
Chapter 3.4Chapter 3.4
Chapter 3.4
sotlsoc
 
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/OCore Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
WebStackAcademy
 
All Of My Java Codes With A Sample Output.docx
All Of My Java Codes With A Sample Output.docxAll Of My Java Codes With A Sample Output.docx
All Of My Java Codes With A Sample Output.docx
adhitya5119
 
Numerical Data And Expression
Numerical Data And ExpressionNumerical Data And Expression
Numerical Data And Expression
PRN USM
 
02slide_accessible.pptx
02slide_accessible.pptx02slide_accessible.pptx
02slide_accessible.pptx
MattMarino13
 
Computer science input and output BASICS.pptx
Computer science input and output BASICS.pptxComputer science input and output BASICS.pptx
Computer science input and output BASICS.pptx
RathanMB
 
Java session08
Java session08Java session08
Java session08
Niit Care
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
OOP-java-variables.pptx
OOP-java-variables.pptxOOP-java-variables.pptx
OOP-java-variables.pptx
ssuserb1a18d
 
JPC#8 Introduction to Java Programming
JPC#8 Introduction to Java ProgrammingJPC#8 Introduction to Java Programming
JPC#8 Introduction to Java Programming
Pathomchon Sriwilairit
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
HCMUTE
 

More from Ajenkris Kungkung (7)

Transaction.pptx
Transaction.pptxTransaction.pptx
Transaction.pptx
Ajenkris Kungkung
 
Variable dan array.pptx
Variable dan array.pptxVariable dan array.pptx
Variable dan array.pptx
Ajenkris Kungkung
 
Insert dan View Data.pptx
Insert dan View Data.pptxInsert dan View Data.pptx
Insert dan View Data.pptx
Ajenkris Kungkung
 
RDBMS MATERI 3.ppt
RDBMS MATERI 3.pptRDBMS MATERI 3.ppt
RDBMS MATERI 3.ppt
Ajenkris Kungkung
 
Pengantar Sistem Komputer
Pengantar Sistem KomputerPengantar Sistem Komputer
Pengantar Sistem Komputer
Ajenkris Kungkung
 

Recently uploaded (20)

Nonverbal_Communication_Presentation.pptx
Nonverbal_Communication_Presentation.pptxNonverbal_Communication_Presentation.pptx
Nonverbal_Communication_Presentation.pptx
srtcuibinpm
 
BADS-MBA-Unit 1 that what data science and Interpretation
BADS-MBA-Unit 1 that what data science and InterpretationBADS-MBA-Unit 1 that what data science and Interpretation
BADS-MBA-Unit 1 that what data science and Interpretation
srishtisingh1813
 
一比一原版(USC毕业证)南加利福尼亚大学毕业证如何办理
一比一原版(USC毕业证)南加利福尼亚大学毕业证如何办理一比一原版(USC毕业证)南加利福尼亚大学毕业证如何办理
一比一原版(USC毕业证)南加利福尼亚大学毕业证如何办理
Taqyea
 
Glary Utilities Pro 5.157.0.183 Crack + Key Download [Latest]
Glary Utilities Pro 5.157.0.183 Crack + Key Download [Latest]Glary Utilities Pro 5.157.0.183 Crack + Key Download [Latest]
Glary Utilities Pro 5.157.0.183 Crack + Key Download [Latest]
Designer
 
IST606_SecurityManagement-slides_ 4 pdf
IST606_SecurityManagement-slides_ 4  pdfIST606_SecurityManagement-slides_ 4  pdf
IST606_SecurityManagement-slides_ 4 pdf
nwanjamakane
 
Brain, Bytes & Bias: ML Interview Questions You Can’t Miss!
Brain, Bytes & Bias: ML Interview Questions You Can’t Miss!Brain, Bytes & Bias: ML Interview Questions You Can’t Miss!
Brain, Bytes & Bias: ML Interview Questions You Can’t Miss!
yashikanigam1
 
Market Share Analysis.pptx nnnnnnnnnnnnnn
Market Share Analysis.pptx nnnnnnnnnnnnnnMarket Share Analysis.pptx nnnnnnnnnnnnnn
Market Share Analysis.pptx nnnnnnnnnnnnnn
rocky
 
Content Moderation Services_ Leading the Future of Online Safety.docx
Content Moderation Services_ Leading the Future of Online Safety.docxContent Moderation Services_ Leading the Future of Online Safety.docx
Content Moderation Services_ Leading the Future of Online Safety.docx
sofiawilliams5966
 
Is RAG Really Dead Generative AI for Reterial.pptx
Is RAG Really Dead Generative AI for Reterial.pptxIs RAG Really Dead Generative AI for Reterial.pptx
Is RAG Really Dead Generative AI for Reterial.pptx
NajeebAhmed36
 
An Algorithmic Test Using The Game of Poker
An Algorithmic Test Using The Game of PokerAn Algorithmic Test Using The Game of Poker
An Algorithmic Test Using The Game of Poker
Graham Ware
 
Human body make Structure analysis the part of the human
Human body make Structure analysis the part of the humanHuman body make Structure analysis the part of the human
Human body make Structure analysis the part of the human
ankit392215
 
Digestive_System_Presentation_BSc_Nursing.pptx
Digestive_System_Presentation_BSc_Nursing.pptxDigestive_System_Presentation_BSc_Nursing.pptx
Digestive_System_Presentation_BSc_Nursing.pptx
RanvirSingh357259
 
15 Benefits of Data Analytics in Business Growth.pdf
15 Benefits of Data Analytics in Business Growth.pdf15 Benefits of Data Analytics in Business Growth.pdf
15 Benefits of Data Analytics in Business Growth.pdf
AffinityCore
 
Multi-Agent-Solution-Architecture-for-Unified-Loan-Platform.pptx
Multi-Agent-Solution-Architecture-for-Unified-Loan-Platform.pptxMulti-Agent-Solution-Architecture-for-Unified-Loan-Platform.pptx
Multi-Agent-Solution-Architecture-for-Unified-Loan-Platform.pptx
VikashVats1
 
Embracing AI in Project Management: Final Insights & Future Vision
Embracing AI in Project Management: Final Insights & Future VisionEmbracing AI in Project Management: Final Insights & Future Vision
Embracing AI in Project Management: Final Insights & Future Vision
KavehMomeni1
 
How Data Annotation Services Drive Innovation in Autonomous Vehicles.docx
How Data Annotation Services Drive Innovation in Autonomous Vehicles.docxHow Data Annotation Services Drive Innovation in Autonomous Vehicles.docx
How Data Annotation Services Drive Innovation in Autonomous Vehicles.docx
sofiawilliams5966
 
Covid19_Project_ Presentation.pptx
Covid19_Project_       Presentation.pptxCovid19_Project_       Presentation.pptx
Covid19_Project_ Presentation.pptx
pavipraveen37
 
Blue Dark Professional Geometric Business Project Presentation .pdf
Blue Dark Professional Geometric Business Project Presentation .pdfBlue Dark Professional Geometric Business Project Presentation .pdf
Blue Dark Professional Geometric Business Project Presentation .pdf
mohammadhaidarayoobi
 
9.-Composite-Dr.-B.-Nalini.pptxfdrtyuioklj
9.-Composite-Dr.-B.-Nalini.pptxfdrtyuioklj9.-Composite-Dr.-B.-Nalini.pptxfdrtyuioklj
9.-Composite-Dr.-B.-Nalini.pptxfdrtyuioklj
aishwaryavdcw
 
Chronic constipation presentaion final.ppt
Chronic constipation presentaion final.pptChronic constipation presentaion final.ppt
Chronic constipation presentaion final.ppt
DrShashank7
 
Nonverbal_Communication_Presentation.pptx
Nonverbal_Communication_Presentation.pptxNonverbal_Communication_Presentation.pptx
Nonverbal_Communication_Presentation.pptx
srtcuibinpm
 
BADS-MBA-Unit 1 that what data science and Interpretation
BADS-MBA-Unit 1 that what data science and InterpretationBADS-MBA-Unit 1 that what data science and Interpretation
BADS-MBA-Unit 1 that what data science and Interpretation
srishtisingh1813
 
一比一原版(USC毕业证)南加利福尼亚大学毕业证如何办理
一比一原版(USC毕业证)南加利福尼亚大学毕业证如何办理一比一原版(USC毕业证)南加利福尼亚大学毕业证如何办理
一比一原版(USC毕业证)南加利福尼亚大学毕业证如何办理
Taqyea
 
Glary Utilities Pro 5.157.0.183 Crack + Key Download [Latest]
Glary Utilities Pro 5.157.0.183 Crack + Key Download [Latest]Glary Utilities Pro 5.157.0.183 Crack + Key Download [Latest]
Glary Utilities Pro 5.157.0.183 Crack + Key Download [Latest]
Designer
 
IST606_SecurityManagement-slides_ 4 pdf
IST606_SecurityManagement-slides_ 4  pdfIST606_SecurityManagement-slides_ 4  pdf
IST606_SecurityManagement-slides_ 4 pdf
nwanjamakane
 
Brain, Bytes & Bias: ML Interview Questions You Can’t Miss!
Brain, Bytes & Bias: ML Interview Questions You Can’t Miss!Brain, Bytes & Bias: ML Interview Questions You Can’t Miss!
Brain, Bytes & Bias: ML Interview Questions You Can’t Miss!
yashikanigam1
 
Market Share Analysis.pptx nnnnnnnnnnnnnn
Market Share Analysis.pptx nnnnnnnnnnnnnnMarket Share Analysis.pptx nnnnnnnnnnnnnn
Market Share Analysis.pptx nnnnnnnnnnnnnn
rocky
 
Content Moderation Services_ Leading the Future of Online Safety.docx
Content Moderation Services_ Leading the Future of Online Safety.docxContent Moderation Services_ Leading the Future of Online Safety.docx
Content Moderation Services_ Leading the Future of Online Safety.docx
sofiawilliams5966
 
Is RAG Really Dead Generative AI for Reterial.pptx
Is RAG Really Dead Generative AI for Reterial.pptxIs RAG Really Dead Generative AI for Reterial.pptx
Is RAG Really Dead Generative AI for Reterial.pptx
NajeebAhmed36
 
An Algorithmic Test Using The Game of Poker
An Algorithmic Test Using The Game of PokerAn Algorithmic Test Using The Game of Poker
An Algorithmic Test Using The Game of Poker
Graham Ware
 
Human body make Structure analysis the part of the human
Human body make Structure analysis the part of the humanHuman body make Structure analysis the part of the human
Human body make Structure analysis the part of the human
ankit392215
 
Digestive_System_Presentation_BSc_Nursing.pptx
Digestive_System_Presentation_BSc_Nursing.pptxDigestive_System_Presentation_BSc_Nursing.pptx
Digestive_System_Presentation_BSc_Nursing.pptx
RanvirSingh357259
 
15 Benefits of Data Analytics in Business Growth.pdf
15 Benefits of Data Analytics in Business Growth.pdf15 Benefits of Data Analytics in Business Growth.pdf
15 Benefits of Data Analytics in Business Growth.pdf
AffinityCore
 
Multi-Agent-Solution-Architecture-for-Unified-Loan-Platform.pptx
Multi-Agent-Solution-Architecture-for-Unified-Loan-Platform.pptxMulti-Agent-Solution-Architecture-for-Unified-Loan-Platform.pptx
Multi-Agent-Solution-Architecture-for-Unified-Loan-Platform.pptx
VikashVats1
 
Embracing AI in Project Management: Final Insights & Future Vision
Embracing AI in Project Management: Final Insights & Future VisionEmbracing AI in Project Management: Final Insights & Future Vision
Embracing AI in Project Management: Final Insights & Future Vision
KavehMomeni1
 
How Data Annotation Services Drive Innovation in Autonomous Vehicles.docx
How Data Annotation Services Drive Innovation in Autonomous Vehicles.docxHow Data Annotation Services Drive Innovation in Autonomous Vehicles.docx
How Data Annotation Services Drive Innovation in Autonomous Vehicles.docx
sofiawilliams5966
 
Covid19_Project_ Presentation.pptx
Covid19_Project_       Presentation.pptxCovid19_Project_       Presentation.pptx
Covid19_Project_ Presentation.pptx
pavipraveen37
 
Blue Dark Professional Geometric Business Project Presentation .pdf
Blue Dark Professional Geometric Business Project Presentation .pdfBlue Dark Professional Geometric Business Project Presentation .pdf
Blue Dark Professional Geometric Business Project Presentation .pdf
mohammadhaidarayoobi
 
9.-Composite-Dr.-B.-Nalini.pptxfdrtyuioklj
9.-Composite-Dr.-B.-Nalini.pptxfdrtyuioklj9.-Composite-Dr.-B.-Nalini.pptxfdrtyuioklj
9.-Composite-Dr.-B.-Nalini.pptxfdrtyuioklj
aishwaryavdcw
 
Chronic constipation presentaion final.ppt
Chronic constipation presentaion final.pptChronic constipation presentaion final.ppt
Chronic constipation presentaion final.ppt
DrShashank7
 

07-Basic-Input-Output.ppt

  • 1. Click to add Text Basic Input and Output
  • 2. Display output System.out.println("I'm a string" + " again"); System.out.print("apple"); System.out.print("bananan"); System.out.print("grape"); I'm a string again applebanana grape
  • 3. Input int c = System.in.read( ); // read 1 byte byte[] b; System.in.read( b ); // array of bytes Scanner console = new Scanner(System.in); String word = console.next(); String line = console.nextLine(); int number = console.nextInt(); double x = console.nextDouble(); Use a Scanner to read input as int, double, String, etc. System.in can only read bytes. Not very useful.
  • 4. Console Output: print System.out is a PrintStream object. It has a "print" method to output (display) :  any primitive data type  a String  any Object int a = 100; System.out.print("a = "); // print a string System.out.print(a); // print an int System.out.print('t'); // print a TAB char System.out.print("Square Root of 2 = "); System.out.print(Math.sqrt(2)); // print double a = 100 Square Root of 2 = 1.4142135623730951
  • 5. Console Output: println println is like print, but after printing a value it also outputs a newline character to move to start of next line. println can output:  any primitive type  a String  any Object: it automatically calls object.toString() System.out.print("a = "); // print a string System.out.println(a); // print an int System.out.println(); // empty line System.out.println(1.0/3.0); // print double a = 100 0.333333333333333
  • 6. More on print and println To print several values at once, if the first value is a String, you can "join" the other values using + System.out.println("a = " + a); a = 100 System.out.print("a = "); // print a string System.out.println(a); // print an int Is the same as:
  • 7. Printing an Object Date now = new Date( ); System.out.println( now ); // invokes now.toString() If the argument is an object, Java will call the object's toString() method and print the result.
  • 8. Common Error ERROR: double angle = Math.toRadians(45); double x = Math.sin(angle); System.out.println("sin(" , angle ,") = " , x); mus use + not comma
  • 9. Formatted Output: printf Creating nice output using println can be difficult. public class SalesTax { public static final double VAT = 0.07; // 7% tax public static void showTotal( double amount) { double total = amount * ( 1.0 + VAT ); System.out.println("The total including VAT is " +total+" Baht"); } public static void main( String [] args ) { showTotal(10000); showTotal(95); } } The total including VAT is 10700.0 Baht The total including VAT is 104.86 Baht
  • 10. printf Java 1.5 added a "printf" statement similar to C: public static void showTotal( double amount) { double total = amount * ( 1.0 + VAT ); System.out.printf( "The total including VAT is %8.2f Baht", total); } public static void main( String [] args ) { showTotal(10000); showTotal(95); } The total including VAT is 10700.00 Baht The total including VAT is 104.86 Baht Format: output a float (%f) using 8 characters with 2 decimal digits
  • 11. printf Syntax The syntax of printf is: System.out.printf(Format_String, arg1, arg2, ...); or (no arguments): System.our.printf(Format_String); The Format_String can contain text and format codes. Values of arg1, arg2, are substituted for the format codes. int x = 100, y = 225; System.out.printf("The sum of %d and %d is %6dn", x, y, x+y ); %d is the format code to output an "int" or "long" value. %6d means output an integer using exactly 6 digit/spaces
  • 12. printf Syntax Example: print the average int x = 100, y = 90; System.out.printf("The average of %d and %d is %6.2fn", x, y, (x+y)/2.0 ); %6.2f means output a floating point using a width of 6 and 2 decimal digits. The average of 100 and 90 is 95.00 %6.2f %d
  • 13. Common printf Formats Format Meaning Examples %d decimal integers %d %6d %f fixed pt. floating-point %f %10.4f %e scientific notation %10e (1.2345e-02) %g general floating point %10g (use %e or %f, whichever is more compact) %s String %s %10s %-10s %c Character %c String owner = "Taksin Shinawat"; int acctNumber = 12345; double balance = 4000000000; System.out.printf("Account %6d Owner %-18s has %10.2fn", acctNumber, owner, balance ); Account 12345 Owner Taksin Shinawat has 4000000000.00
  • 14. More details on printf  printf is an instance of the Formatter class.  It is predefined for System.out.  System.out.printf(...) is same as System.out.format(...).  For complete details see Java API for "Format".  For tutorial, examples, etc. see:  Sun's Java Tutorial  Core Java, page 61.
  • 15. String.format A useful method that creates a String using a format. /** describe a bank acount */ String name = "John Doe"; long accountId = 12345; double balance = 123.456; String result = String.format( "Acct: %09d Owner: %s Balance: %.2f", accountId, name, balance ); return result; Acct: 000012345 Owner: John Doe Balance: 123.46
  • 16. Click to add Text Input
  • 17. Input byte-by-byte System.in is an InputStream object. It reads data one byte at a time, or an array of bytes. Use System.in.read( ) to get "raw" data, such as an image: int a = System.in.read( ); if (a < 0) /* end of input */; else { byte b = (byte)a; handleInput( b ); } Boring, isn't it?
  • 18. Input Line-by-Line To get a line of input as a String, you can create a BufferedReader object that "wraps" System.in. BufferedReader reader = new BufferedReader( new InputStreamReader( System.in ) ); String s = reader.readLine( ); // read one line The readLine( ) method removes the NEWLINE (n) from the input, so you won't see it as part of the string.
  • 19. Check for end of data If there is no more data in the input stream, readLine( ) returns a null String. For console input, readLine( ) will wait (block) until user inputs something. Here is how to test for end of data: BufferedReader reader = new BufferedReader( new InputStreamReader( System.in ) ); String s = reader.readLine( ); // read one line if ( s == null ) return; // end of data
  • 20. Handling I/O Errors When you use System.in.read or a BufferedReader an input error can occur -- called an IOException. Java requires that your program either "catch" this exception to declare that it might "throw" this exception. To be lazy and "throw" the exception use: public static void main(String [] args) throws IOException { BufferedReader reader = new BufferedReader( new InputStreamReader( System.in ) ); // read a line of input String inline = reader.readLine( );
  • 21. Catching I/O Errors To "catch" the exception and do something, use: BufferedReader reader = new BufferedReader( new InputStreamReader( System.in ) ); // read a line of input. // display message and return if error String line = null; try { line = bin.readLine( ); buf.append( line ); } catch( IOException ioe ) { System.err.println( ioe.getMessage() ); return; }
  • 22. Flexible Input: Scanner class The Scanner class allow much more flexible input. A Scanner can:  read entire line or one word at a time  test for more data  test if the next input (word) is an int, long, double, etc.  read input and convert to int, long, float, double  skip unwanted data  report errors (Exceptions) that occur
  • 23. Import Scanner Scanner is a "utility" so it is package java.util. You should import this class to use it: package myapp; import java.util.Scanner; ... public class InputDemo {
  • 24. Create a Scanner Object Scanner "wraps" an InputStream. You give the InputStream object as parameter when you create a Scanner object... // create a Scanner to read from System.in Scanner console = new Scanner( System.in );
  • 25. Where to Create Scanner object? 1) You can create a Scanner as a local variable public void myMethod( ) { // no IOException ! // create a Scanner as a local variable Scanner in = new Scanner( System.in ); // read some different types of data int count = in.nextInt( ); public class InputDemo { // create a Scanner as static attribute static Scanner console = new Scanner( System.in ); // can use console in any method. 2) or create as an attribute. Typically a static attribute since System.in is static.
  • 26. Using Scanner Look at some simple examples public void myMethod( ) { // no IOException ! // create a Scanner to process System.in Scanner in = new Scanner( System.in ); // read some different types of data int count = in.nextInt( ); long big = in.nextLong( ); float x = in.nextFloat( ); double y = in.nextDouble( ); // read Strings String word = scan.next( ); // next word String line = scan.nextLine( ); // next line
  • 27. Input Errors If you try to read an "int" but the next input is not an integer then Scanner throws an InputMismatchException Scanner scan = new Scanner( System.in ); // read a number System.out.print("How many Baht? "); int amount = scan.nextInt( ); How many Baht? I don't know Exception in thread "main" java.util.InputMismatchException convert next input word to an "int"
  • 28. How to Test the Input Scanner has methods to test the next input value: Scanner scanner = new Scanner( System.in ); int amount; // read a number System.out.print("How many Baht? "); if ( scanner.hasNextInt( ) ) amount = scanner.nextInt( ); else { System.out.println("Please input an int"); scanner.nextLine(); // discard old input } How many Baht? I don't know Please input an int true if the next input value is an "int"
  • 29. Testing the input So now you can check for invalid input. But, what do you do with the bad input? If scan.hasNextInt( ) is false, then the program doesn't read it. So, the bad input is still waiting to be read. Like this: How many Baht? I don't know Next input value to read. We want to remove this bad input, so we can ask the user to try again. ...what should we do?
  • 30. Discarding the input If the input is wrong, then throw it away by reading the line and discarding it. get the input line but don't assign it to anything! (discard it) Scanner scanner = new Scanner( System.in ); int amount; // read a number System.out.print("How many Baht? "); if ( scanner.hasNextInt( ) ) amount = scanner.nextInt( ); else { System.out.println("Please input an int"); scanner.nextLine(); // discard input
  • 31. Useful Scanner Methods Return type Method Meaning String next() get next "word" String nextLine() get next line int nextInt() get next word as int long nextLong() get next word as long float nextFloat() get next word as float double nextDouble() get next word as double boolean hasNext() true if there is more input boolean hasNextInt() true if next word can be "int" boolean hasNextLong() true if next word can be "long" boolean hasNextFloat() true if next word can be "float" boolean hasNextDouble() true if next word can be "double" See Java API for java.io.Scanner for a complete list of methods.
  • 32. Input/Output Example Read some numbers and output their sum... Scanner scanner = new Scanner( System.in ); double sum = 0.0; // prompt user for input System.out.print("Input some numbers: "); // read as long as there are more numbers while ( scanner.hasNextDouble( ) ) { double x = scanner.nextDouble( ); sum = sum + x; } System.out.println(); System.out.println("The sum is "+sum);
  • 33. TUGAS Implementasikan contoh-contoh listing program pada materi dan dikumpulkan. - isi dari tugas adalah listing program dan hasil output dari listring tersebut - tugas dibuat dalam kelompok yang terdiri dari 4 orang - tuliskan nama-nama anggota kelompok pada lembar pertama tugas