SlideShare a Scribd company logo
1 of 33
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

Lab01.pptx
Lab01.pptxLab01.pptx
Lab01.pptxKimVeeL
 
Quest 1 define a class batsman with the following specifications
Quest  1 define a class batsman with the following specificationsQuest  1 define a class batsman with the following specifications
Quest 1 define a class batsman with the following specificationsrajkumari873
 
KOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
KOLEJ KOMUNITI - Sijil Aplikasi Perisian KomputerKOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
KOLEJ KOMUNITI - Sijil Aplikasi Perisian KomputerAiman Hud
 
import java.util.;public class Program{public static void.pdf
import java.util.;public class Program{public static void.pdfimport java.util.;public class Program{public static void.pdf
import java.util.;public class Program{public static void.pdfoptokunal1
 
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxPROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxamrit47
 
import java.util.Scanner;public class Digits { public static v.pdf
import java.util.Scanner;public class Digits { public static v.pdfimport java.util.Scanner;public class Digits { public static v.pdf
import java.util.Scanner;public class Digits { public static v.pdfapexelectronices01
 
Import java
Import javaImport java
Import javaheni2121
 
Assume you have a scanner object (called input).Declare an integer.pdf
Assume you have a scanner object (called input).Declare an integer.pdfAssume you have a scanner object (called input).Declare an integer.pdf
Assume you have a scanner object (called input).Declare an integer.pdfezzi552
 
Input and output basic of c++ programming and escape sequences
Input and output basic of c++ programming and escape sequencesInput and output basic of c++ programming and escape sequences
Input and output basic of c++ programming and escape sequencesssuserf86fba
 
Create a menu-driven program that will accept a collection of non-ne.pdf
Create a menu-driven program that will accept a collection of non-ne.pdfCreate a menu-driven program that will accept a collection of non-ne.pdf
Create a menu-driven program that will accept a collection of non-ne.pdfrajeshjangid1865
 
The java code works, I just need it to display the results as in t.pdf
The java code works, I just need it to display the results as in t.pdfThe java code works, I just need it to display the results as in t.pdf
The java code works, I just need it to display the results as in t.pdfakaluza07
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manualsameer farooq
 

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

Lab01.pptx
Lab01.pptxLab01.pptx
Lab01.pptx
 
C#.net
C#.netC#.net
C#.net
 
Quest 1 define a class batsman with the following specifications
Quest  1 define a class batsman with the following specificationsQuest  1 define a class batsman with the following specifications
Quest 1 define a class batsman with the following specifications
 
KOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
KOLEJ KOMUNITI - Sijil Aplikasi Perisian KomputerKOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
KOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
 
import java.util.;public class Program{public static void.pdf
import java.util.;public class Program{public static void.pdfimport java.util.;public class Program{public static void.pdf
import java.util.;public class Program{public static void.pdf
 
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxPROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
 
Lecture 2 java.pdf
Lecture 2 java.pdfLecture 2 java.pdf
Lecture 2 java.pdf
 
import java.util.Scanner;public class Digits { public static v.pdf
import java.util.Scanner;public class Digits { public static v.pdfimport java.util.Scanner;public class Digits { public static v.pdf
import java.util.Scanner;public class Digits { public static v.pdf
 
Import java
Import javaImport java
Import java
 
Assume you have a scanner object (called input).Declare an integer.pdf
Assume you have a scanner object (called input).Declare an integer.pdfAssume you have a scanner object (called input).Declare an integer.pdf
Assume you have a scanner object (called input).Declare an integer.pdf
 
Input and output basic of c++ programming and escape sequences
Input and output basic of c++ programming and escape sequencesInput and output basic of c++ programming and escape sequences
Input and output basic of c++ programming and escape sequences
 
Computer programming 2 chapter 1-lesson 2
Computer programming 2  chapter 1-lesson 2Computer programming 2  chapter 1-lesson 2
Computer programming 2 chapter 1-lesson 2
 
Create a menu-driven program that will accept a collection of non-ne.pdf
Create a menu-driven program that will accept a collection of non-ne.pdfCreate a menu-driven program that will accept a collection of non-ne.pdf
Create a menu-driven program that will accept a collection of non-ne.pdf
 
PSI 3 Integration
PSI 3 IntegrationPSI 3 Integration
PSI 3 Integration
 
The java code works, I just need it to display the results as in t.pdf
The java code works, I just need it to display the results as in t.pdfThe java code works, I just need it to display the results as in t.pdf
The java code works, I just need it to display the results as in t.pdf
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manual
 
5 Rmi Print
5  Rmi Print5  Rmi Print
5 Rmi Print
 
Java final lab
Java final labJava final lab
Java final lab
 
programming for Calculator in java
programming for Calculator in javaprogramming for Calculator in java
programming for Calculator in java
 

More from Ajenkris Kungkung

More from Ajenkris Kungkung (7)

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

Recently uploaded

Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfKantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfSocial Samosa
 
VIP High Class Call Girls Bikaner Anushka 8250192130 Independent Escort Servi...
VIP High Class Call Girls Bikaner Anushka 8250192130 Independent Escort Servi...VIP High Class Call Girls Bikaner Anushka 8250192130 Independent Escort Servi...
VIP High Class Call Girls Bikaner Anushka 8250192130 Independent Escort Servi...Suhani Kapoor
 
B2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docxB2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docxStephen266013
 
Data Warehouse , Data Cube Computation
Data Warehouse   , Data Cube ComputationData Warehouse   , Data Cube Computation
Data Warehouse , Data Cube Computationsit20ad004
 
04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationships04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationshipsccctableauusergroup
 
Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...
Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...
Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...dajasot375
 
100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptxAnupama Kate
 
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfMarket Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfRachmat Ramadhan H
 
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Customer Service Analytics - Make Sense of All Your Data.pptx
Customer Service Analytics - Make Sense of All Your Data.pptxCustomer Service Analytics - Make Sense of All Your Data.pptx
Customer Service Analytics - Make Sense of All Your Data.pptxEmmanuel Dauda
 
From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...Florian Roscheck
 
Call Girls In Noida City Center Metro 24/7✡️9711147426✡️ Escorts Service
Call Girls In Noida City Center Metro 24/7✡️9711147426✡️ Escorts ServiceCall Girls In Noida City Center Metro 24/7✡️9711147426✡️ Escorts Service
Call Girls In Noida City Center Metro 24/7✡️9711147426✡️ Escorts Servicejennyeacort
 
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...Suhani Kapoor
 
RA-11058_IRR-COMPRESS Do 198 series of 1998
RA-11058_IRR-COMPRESS Do 198 series of 1998RA-11058_IRR-COMPRESS Do 198 series of 1998
RA-11058_IRR-COMPRESS Do 198 series of 1998YohFuh
 
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service Bhilai
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service BhilaiLow Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service Bhilai
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service BhilaiSuhani Kapoor
 
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPramod Kumar Srivastava
 
Dubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls DubaiDubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls Dubaihf8803863
 

Recently uploaded (20)

Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfKantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
 
VIP High Class Call Girls Bikaner Anushka 8250192130 Independent Escort Servi...
VIP High Class Call Girls Bikaner Anushka 8250192130 Independent Escort Servi...VIP High Class Call Girls Bikaner Anushka 8250192130 Independent Escort Servi...
VIP High Class Call Girls Bikaner Anushka 8250192130 Independent Escort Servi...
 
B2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docxB2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docx
 
Data Warehouse , Data Cube Computation
Data Warehouse   , Data Cube ComputationData Warehouse   , Data Cube Computation
Data Warehouse , Data Cube Computation
 
04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationships04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationships
 
Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...
Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...
Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...
 
100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx
 
Deep Generative Learning for All - The Gen AI Hype (Spring 2024)
Deep Generative Learning for All - The Gen AI Hype (Spring 2024)Deep Generative Learning for All - The Gen AI Hype (Spring 2024)
Deep Generative Learning for All - The Gen AI Hype (Spring 2024)
 
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfMarket Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
 
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
 
Customer Service Analytics - Make Sense of All Your Data.pptx
Customer Service Analytics - Make Sense of All Your Data.pptxCustomer Service Analytics - Make Sense of All Your Data.pptx
Customer Service Analytics - Make Sense of All Your Data.pptx
 
From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...
 
Call Girls In Noida City Center Metro 24/7✡️9711147426✡️ Escorts Service
Call Girls In Noida City Center Metro 24/7✡️9711147426✡️ Escorts ServiceCall Girls In Noida City Center Metro 24/7✡️9711147426✡️ Escorts Service
Call Girls In Noida City Center Metro 24/7✡️9711147426✡️ Escorts Service
 
꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...
꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...
꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...
 
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
 
RA-11058_IRR-COMPRESS Do 198 series of 1998
RA-11058_IRR-COMPRESS Do 198 series of 1998RA-11058_IRR-COMPRESS Do 198 series of 1998
RA-11058_IRR-COMPRESS Do 198 series of 1998
 
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service Bhilai
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service BhilaiLow Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service Bhilai
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service Bhilai
 
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
 
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
 
Dubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls DubaiDubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls Dubai
 

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