This document provides information about basic input and output in Java using System.out, System.in, and the Scanner class. It discusses using print and println to display output, and how to handle input using System.in, BufferedReader, and the Scanner class. The Scanner class allows more flexible input, including the ability to test the next input, read different data types, and handle input errors.
This document discusses how to take input from users in Java using the Scanner class. It provides examples of taking integer, double, character and string input. The Scanner class methods like nextInt(), nextDouble(), next() etc are used to read input. The document also contains sample code and explanations for taking input to calculate sum of two numbers, simple interest and reading a character.
This document discusses Java input and output. It explains that System.out.println(), System.out.print(), and System.out.printf() can be used for output. println() prints the string and moves to the next line, print() prints the string, and printf() provides string formatting. The Scanner class is used for input, by creating a Scanner object and calling methods like nextInt() and nextDouble(). Examples demonstrate getting integer, float, double, and string input from the user.
This document provides an overview of key concepts in Java including Eclipse IDE, creating classes, the main method, printing output, variables, data types, user input, arithmetic operators, and typecasting. It explains how to create a Java class in Eclipse, use print statements, declare and initialize variables, take user input, and perform basic math operations and conversions between data types in Java.
The Scanner class in Java allows user input through methods like nextLine(), nextInt(), and nextDouble(). The next() method only reads input up to the first whitespace, while nextLine() reads the entire line. Java provides output methods like print() and println() to display text on the screen, and printf() allows formatted output by specifying the format before displaying values.
- Writing to the display in Java uses System.out.println() and System.out.print() to output text.
- Reading from keyboard uses the BufferedReader class along with InputStreamReader to read input as strings. The strings can then be split and converted to int or double as needed.
- Key methods for strings include charAt() to get individual characters, and substring() to extract parts of a string.
Solutions manual for absolute java 5th edition by walter savitchAlbern9271
Solutions manual for absolute java 5th edition by walter savitch
Full clear download( no error formatting) at:
https://goo.gl/Aic8JR
absolute java 5th edition pdf free
absolute java 5th edition by walter savitch pdf
absolute java 5th edition solutions pdf
absolute java 6th edition solutions pdf
absolute java programming projects solutions
pearson absolute java 5th ed walter savitch 2012 pdf
walter savitch absolute java 4th edition or newer addison wesley 3rd edition is also fine
- The document discusses input/output (IO) operations in Java, specifically writing to the display using System.out.println() and reading from the keyboard using BufferedReader.
- It provides examples of writing strings and expressions to the display, as well as reading input from the user as strings and converting them to integers or doubles.
- The key aspects covered are using println() and print() for output, BufferedReader for input, and parsing strings to numbers using Integer.parseInt() and Double.parseDouble().
The document discusses various Java programming concepts such as Hello World, primitive data types, variables, input/output, and control structures like if/else, switch/case, while loops. It provides examples of declaring and using variables, type casting between primitives, and commenting code. Various Java classes for input/output like Scanner and System.out are demonstrated.
Java is a cross-platform language originally developed by James Gosling at Sun Microsystems. It enables writing programs for many operating systems using a C/C++-like syntax but with a simpler object model and fewer low-level facilities. Java programs are compiled to bytecode that can run on any Java Virtual Machine (JVM) regardless of computer architecture. Common Java development tools include Eclipse and NetBeans integrated development environments.
This document provides an overview of Java input/output programming, networking, and streams. It discusses reading input from the console and keyboard using BufferedReader, StringTokenizer, and Scanner. It also covers writing output to the console. Predefined streams like System.in and System.out are explained. The basics of character streams, byte streams, and Java streams are summarized. Networking concepts like IP addresses that enable communication between devices on a computer network are also briefly introduced.
Introduction to objects and inputoutput Ahmad Idrees
Java is a computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible.
The document discusses primitive data types in Java including integers, floating point numbers, Booleans, characters, and strings. It also covers variables, their scope and declaration. Variables can store primitive values or object references. The document also discusses input/output in Java using Scanner to read from input streams like the keyboard.
The Scanner class in Java simplifies console input by parsing input into tokens using delimiters. It can read input from various sources like files, strings, and streams. Scanner objects are constructed by passing the input source, and tokens can be read using type-specific next methods like nextInt() or by pattern matching. InputMismatchExceptions may be thrown if the next token does not match the expected type.
The document discusses different ways of implementing type conversion in Java. It covers widening and narrowing conversions, as well as assignment conversion, promotion, and casting. It provides examples of each type of conversion and discusses how conversions can occur during arithmetic expressions and assignments. It also covers wrapper classes and their role in type conversions.
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/OWebStackAcademy
This document discusses console and file input/output in Java. It describes how to read from standard input using System.in, write to standard output using System.out, and read/write files using File and FileReader/FileWriter classes. Methods for formatted output/input are also covered. The document provides examples for reading keyboard input, writing to console, and reading/writing files line-by-line.
This document discusses various fundamental programming concepts including character strings, primitive data, variables, expressions, operator precedence, data conversions, accepting user input, and the difference between Java applications and applets. It provides examples and explanations of these concepts.
This document discusses an introduction to Java programming and data structures. It covers chapters on elementary programming concepts like variables, data types, operators, and input/output. The chapter objectives are listed and include writing programs to perform calculations, obtaining input from the console, using identifiers, variables, and constants. Examples are provided to illustrate computing the area of a circle, reading input, and numeric data types.
Computer science input and output BASICS.pptxRathanMB
Stream is a sequence of data that supports methods to read or write data. There are two types of streams in Java - byte streams and character streams. Byte streams are used for input/output of bytes while character streams are used for input/output of Unicode characters. The java.io package contains classes for input/output in Java, including abstract classes like InputStream and OutputStream for byte streams, and Reader and Writer for character streams. System.in, System.out and System.err are predefined streams for input, output and errors respectively.
The document discusses the eight primitive data types in Java - boolean, char, byte, short, int, long, float, and double. It explains what each type is used for, their possible value ranges, and when to use each type. Key points covered include int being the preferred integer type, double the preferred real number type, and the importance of declaring variables before use and giving them initial values.
The document discusses file input and output in Java. It covers the File class, opening files for reading using a Scanner, handling exceptions, reading data line-by-line and tokenizing the lines. It also discusses opening files for writing using a PrintWriter and outputting data to files. The key topics are file I/O, exception handling, and using Scanners and PrintWriters to read from and write to files in Java.
This document provides an overview of key concepts to be covered in a Java programming language session, including:
1. Writing programs that use command-line arguments, system properties, and standard input/output.
2. Creating, reading and writing files.
3. Understanding the basic collections hierarchy and writing programs using sets, lists, and generic collections.
4. Iterating over collections.
Main Java[All of the Base Concepts}.docxadhitya5119
This is part 1 of my Java Learning Journey. This Contains Custom methods, classes, constructors, packages, multithreading , try- catch block, finally block and more.
This document discusses Java variables, data types, and operators. It covers the basics of declaring variables in Java, including primitive and non-primitive data types. It also describes different types of variables, literals, casting, and operators such as arithmetic, assignment, comparison, and logical operators. Examples are provided to demonstrate variable declaration and usage of various operators.
This document provides an introduction to Java programming concepts including what Java is, how to set up a Java development environment, basic Java code structure, variables, data types, arithmetic operations, conditional statements, loops, and getting user input. It covers elementary Java topics through examples and explanations. Key points include how to write, compile and run a simple Java program that prints "Hello World", how to declare and use variables of different data types, the different conditional statements (if, if-else, if-else-if-else), looping constructs (while, do-while, for), and taking user input using the Scanner class.
This document provides an overview of key concepts in the Java programming language, including:
- Java is an object-oriented language that is simpler than C++ and supports features like platform independence.
- The Java development environment includes tools for compiling, debugging, and running Java programs.
- Java programs work with basic data types like int and double, as well as user-defined classes, variables, and arrays.
- The document explains operators, control structures, formatting output, and the basics of classes and objects in Java.
Dokumen ini membahas tentang variabel dan array dalam PHP. Variabel digunakan untuk menyimpan satu data, sedangkan array digunakan untuk menyimpan banyak data. Dokumen ini juga menjelaskan cara deklarasi variabel dan jenis datanya, serta penjelasan tentang array asosiatif, perulangan array, menambah dan menghapus elemen array, array multidimensi, dan fungsi-fungsi array bawaan PHP.
The document discusses various Java programming concepts such as Hello World, primitive data types, variables, input/output, and control structures like if/else, switch/case, while loops. It provides examples of declaring and using variables, type casting between primitives, and commenting code. Various Java classes for input/output like Scanner and System.out are demonstrated.
Java is a cross-platform language originally developed by James Gosling at Sun Microsystems. It enables writing programs for many operating systems using a C/C++-like syntax but with a simpler object model and fewer low-level facilities. Java programs are compiled to bytecode that can run on any Java Virtual Machine (JVM) regardless of computer architecture. Common Java development tools include Eclipse and NetBeans integrated development environments.
This document provides an overview of Java input/output programming, networking, and streams. It discusses reading input from the console and keyboard using BufferedReader, StringTokenizer, and Scanner. It also covers writing output to the console. Predefined streams like System.in and System.out are explained. The basics of character streams, byte streams, and Java streams are summarized. Networking concepts like IP addresses that enable communication between devices on a computer network are also briefly introduced.
Introduction to objects and inputoutput Ahmad Idrees
Java is a computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible.
The document discusses primitive data types in Java including integers, floating point numbers, Booleans, characters, and strings. It also covers variables, their scope and declaration. Variables can store primitive values or object references. The document also discusses input/output in Java using Scanner to read from input streams like the keyboard.
The Scanner class in Java simplifies console input by parsing input into tokens using delimiters. It can read input from various sources like files, strings, and streams. Scanner objects are constructed by passing the input source, and tokens can be read using type-specific next methods like nextInt() or by pattern matching. InputMismatchExceptions may be thrown if the next token does not match the expected type.
The document discusses different ways of implementing type conversion in Java. It covers widening and narrowing conversions, as well as assignment conversion, promotion, and casting. It provides examples of each type of conversion and discusses how conversions can occur during arithmetic expressions and assignments. It also covers wrapper classes and their role in type conversions.
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/OWebStackAcademy
This document discusses console and file input/output in Java. It describes how to read from standard input using System.in, write to standard output using System.out, and read/write files using File and FileReader/FileWriter classes. Methods for formatted output/input are also covered. The document provides examples for reading keyboard input, writing to console, and reading/writing files line-by-line.
This document discusses various fundamental programming concepts including character strings, primitive data, variables, expressions, operator precedence, data conversions, accepting user input, and the difference between Java applications and applets. It provides examples and explanations of these concepts.
This document discusses an introduction to Java programming and data structures. It covers chapters on elementary programming concepts like variables, data types, operators, and input/output. The chapter objectives are listed and include writing programs to perform calculations, obtaining input from the console, using identifiers, variables, and constants. Examples are provided to illustrate computing the area of a circle, reading input, and numeric data types.
Computer science input and output BASICS.pptxRathanMB
Stream is a sequence of data that supports methods to read or write data. There are two types of streams in Java - byte streams and character streams. Byte streams are used for input/output of bytes while character streams are used for input/output of Unicode characters. The java.io package contains classes for input/output in Java, including abstract classes like InputStream and OutputStream for byte streams, and Reader and Writer for character streams. System.in, System.out and System.err are predefined streams for input, output and errors respectively.
The document discusses the eight primitive data types in Java - boolean, char, byte, short, int, long, float, and double. It explains what each type is used for, their possible value ranges, and when to use each type. Key points covered include int being the preferred integer type, double the preferred real number type, and the importance of declaring variables before use and giving them initial values.
The document discusses file input and output in Java. It covers the File class, opening files for reading using a Scanner, handling exceptions, reading data line-by-line and tokenizing the lines. It also discusses opening files for writing using a PrintWriter and outputting data to files. The key topics are file I/O, exception handling, and using Scanners and PrintWriters to read from and write to files in Java.
This document provides an overview of key concepts to be covered in a Java programming language session, including:
1. Writing programs that use command-line arguments, system properties, and standard input/output.
2. Creating, reading and writing files.
3. Understanding the basic collections hierarchy and writing programs using sets, lists, and generic collections.
4. Iterating over collections.
Main Java[All of the Base Concepts}.docxadhitya5119
This is part 1 of my Java Learning Journey. This Contains Custom methods, classes, constructors, packages, multithreading , try- catch block, finally block and more.
This document discusses Java variables, data types, and operators. It covers the basics of declaring variables in Java, including primitive and non-primitive data types. It also describes different types of variables, literals, casting, and operators such as arithmetic, assignment, comparison, and logical operators. Examples are provided to demonstrate variable declaration and usage of various operators.
This document provides an introduction to Java programming concepts including what Java is, how to set up a Java development environment, basic Java code structure, variables, data types, arithmetic operations, conditional statements, loops, and getting user input. It covers elementary Java topics through examples and explanations. Key points include how to write, compile and run a simple Java program that prints "Hello World", how to declare and use variables of different data types, the different conditional statements (if, if-else, if-else-if-else), looping constructs (while, do-while, for), and taking user input using the Scanner class.
This document provides an overview of key concepts in the Java programming language, including:
- Java is an object-oriented language that is simpler than C++ and supports features like platform independence.
- The Java development environment includes tools for compiling, debugging, and running Java programs.
- Java programs work with basic data types like int and double, as well as user-defined classes, variables, and arrays.
- The document explains operators, control structures, formatting output, and the basics of classes and objects in Java.
Dokumen ini membahas tentang variabel dan array dalam PHP. Variabel digunakan untuk menyimpan satu data, sedangkan array digunakan untuk menyimpan banyak data. Dokumen ini juga menjelaskan cara deklarasi variabel dan jenis datanya, serta penjelasan tentang array asosiatif, perulangan array, menambah dan menghapus elemen array, array multidimensi, dan fungsi-fungsi array bawaan PHP.
Dokumen tersebut membahas bagaimana PHP dapat terhubung dengan database melalui ekstensi PDO atau mysqli, dan cara menginsert atau menampilkan data ke dan dari database MySQL menggunakan perintah SQL seperti INSERT dan SELECT. Dokumen tersebut juga menyertakan contoh kasus penggunaan form untuk menginput dan menampilkan data ke dalam tabel database.
Harddisk adalah media penyimpanan sekunder yang menyimpan data sebagai pulsa magnetik pada piringan logam berputar. Harddisk mampu menyimpan data dalam kapasitas besar dan menawarkan kecepatan akses yang lebih baik dibanding media penyimpanan konvensional seperti disket. Teknologi harddisk terus berkembang dengan peningkatan kerapatan data, kecepatan putar piringan, dan kapasitas penyimpanan.
办留学学历认证(USC毕业证书)南加利福尼亚大学毕业证学历证书代办服务【q微1954292140】Buy University of Southern California Diploma《正式成绩单论文没过》有文凭却得不到认证。又该怎么办???美国毕业证购买,美国文凭购买,【q微1954292140】美国文凭购买,美国文凭定制,美国文凭补办。专业在线定制美国大学文凭,定做美国本科文凭,【q微1954292140】复制美国University of Southern California completion letter。在线快速补办美国本科毕业证、硕士文凭证书,购买美国学位证、南加利福尼亚大学Offer,美国大学文凭在线购买。
主营项目:
1、真实教育部国外学历学位认证《美国毕业文凭证书快速办理南加利福尼亚大学学校原版文凭补办》【q微1954292140】《论文没过南加利福尼亚大学正式成绩单》,教育部存档,教育部留服网站100%可查.
2、办理USC毕业证,改成绩单《USC毕业证明办理南加利福尼亚大学学位证书网上查询》【Q/WeChat:1954292140】Buy University of Southern California Certificates《正式成绩单论文没过》,南加利福尼亚大学Offer、在读证明、学生卡、信封、证明信等全套材料,从防伪到印刷,从水印到钢印烫金,高精仿度跟学校原版100%相同.
3、真实使馆认证(即留学人员回国证明),使馆存档可通过大使馆查询确认.
4、留信网认证,国家专业人才认证中心颁发入库证书,留信网存档可查.
美国南加利福尼亚大学毕业证(USC毕业证书)USC文凭【q微1954292140】高仿真还原美国文凭证书和外壳,定制美国南加利福尼亚大学成绩单和信封。国外毕业证成绩单的办理流程USC毕业证【q微1954292140】学历学位证制作南加利福尼亚大学offer/学位证出售、留信官方学历认证(永久存档真实可查)采用学校原版纸张、特殊工艺完全按照原版一比一制作。帮你解决南加利福尼亚大学学历学位认证难题。
帮您解决在美国南加利福尼亚大学未毕业难题(University of Southern California)文凭购买、毕业证购买、大学文凭购买、大学毕业证购买、买文凭、日韩文凭、英国大学文凭、美国大学文凭、澳洲大学文凭、加拿大大学文凭(q微1954292140)新加坡大学文凭、新西兰大学文凭、爱尔兰文凭、西班牙文凭、德国文凭、教育部认证,买毕业证,毕业证购买,买大学文凭,【q微1954292140】学位证1:1完美还原海外各大学毕业材料上的工艺:水印,阴影底纹,钢印LOGO烫金烫银,LOGO烫金烫银复合重叠。文字图案浮雕、激光镭射、紫外荧光、温感、复印防伪等防伪工艺。《南加利福尼亚大学学位证书英文版美国毕业证书办理USC国外文凭电子版》
【办理南加利福尼亚大学成绩单Buy University of Southern California Transcripts】
购买日韩成绩单、英国大学成绩单、美国大学成绩单、澳洲大学成绩单、加拿大大学成绩单(q微1954292140)新加坡大学成绩单、新西兰大学成绩单、爱尔兰成绩单、西班牙成绩单、德国成绩单。成绩单的意义主要体现在证明学习能力、评估学术背景、展示综合素质、提高录取率,以及是作为留信认证申请材料的一部分。
南加利福尼亚大学成绩单能够体现您的的学习能力,包括南加利福尼亚大学课程成绩、专业能力、研究能力。(q微1954292140)具体来说,成绩报告单通常包含学生的学习技能与习惯、各科成绩以及老师评语等部分,因此,成绩单不仅是学生学术能力的证明,也是评估学生是否适合某个教育项目的重要依据!
南加利福尼亚大学offer/学位证、留信官方学历认证(永久存档真实可查)采用学校原版纸张、特殊工艺完全按照原版一比一制作【q微1954292140】Buy University of Southern California Diploma购买美国毕业证,购买英国毕业证,购买澳洲毕业证,购买加拿大毕业证,以及德国毕业证,购买法国毕业证(q微1954292140)购买荷兰毕业证、购买瑞士毕业证、购买日本毕业证、购买韩国毕业证、购买新西兰毕业证、购买新加坡毕业证、购买西班牙毕业证、购买马来西亚毕业证等。包括了本科毕业证,硕士毕业证。
特殊原因导致无法毕业,也可以联系我们帮您办理相关材料:
1:在南加利福尼亚大学挂科了,不想读了,成绩不理想怎么办?
2:打算回国了,找工作的时候,需要提供认证《USC成绩单购买办理南加利福尼亚大学毕业证书范本》
购买日韩毕业证、英国大学毕业证、美国大学毕业证、澳洲大学毕业证、加拿大大学毕业证(q微1954292140)新加坡大学毕业证、新西兰大学毕业证、爱尔兰毕业证、西班牙毕业证、德国毕业证,回国证明,留信网认证,留信认证办理,学历认证。从而完成就业。南加利福尼亚大学毕业证办理,南加利福尼亚大学文凭办理,南加利福尼亚大学成绩单办理和真实留信认证、留服认证、南加利福尼亚大学学历认证。学院文凭定制,南加利福尼亚大学原版文凭补办,成绩单购买办理,扫描件文凭定做,100%文凭复刻。
Glary Utilities Pro 5.157.0.183 Crack + Key Download [Latest]Designer
Copy Link & Paste in Google👉👉👉 https://alipc.pro/dl/
Glary Utilities Pro Crack Glary Utilities Pro Crack Free Download is an amazing collection of system tools and utilities to fix, speed up, maintain and protect your PC.
Brain, Bytes & Bias: ML Interview Questions You Can’t Miss!yashikanigam1
Preparing for a machine learning role? Get ready to tackle real-world problem-solving questions! From regression vs. classification to the ETL process, expect a deep dive into algorithms and data pipelines. Most live courses for professionals and best online professional certificates now include mock interviews and case studies to gear you up. Mastering these ML interview questions not only helps in cracking top tech interviews but also builds your confidence.
At Tutort Academy, we train you with real-time scenarios and curated interview prep for success.
Content Moderation Services_ Leading the Future of Online Safety.docxsofiawilliams5966
These services are not just gatekeepers of community standards. They are architects of safe interaction, unseen defenders of user well-being, and the infrastructure supporting the promise of a trustworthy internet.
An Algorithmic Test Using The Game of PokerGraham Ware
In an interview you may be presented with a poker set and asked to create a game that mimics the market and data science. Here is a fun way we created such a scenario.
15 Benefits of Data Analytics in Business Growth.pdfAffinityCore
Explore how data analytics boosts business growth with insights that improve decision-making, customer targeting, operations, and long-term profitability.
Embracing AI in Project Management: Final Insights & Future VisionKavehMomeni1
🚀 Unlock the Future of Project Management: Embracing AI – Final Session!
This presentation is the culminating session (Session 13) of the "AI Applications in Project Management Workshop," hosted by OnAcademy and instructed by Kaveh Momeni, PMP®, COB & AI Lead at Chaharsotoon.
Dive deep into "Embracing AI: Empowering Project Managers for an AI-Driven Future." We consolidate critical learnings from the entire workshop and provide a forward-looking perspective on how AI is revolutionizing project management.
Inside, you'll discover:
A Comprehensive Course Recap: Key takeaways from across the workshop, covering everything from knowledge management and predictive analytics to AI agents.
Cutting-Edge AI Trends: The latest developments in AI impacting PM, including market growth, task automation, and the rise of autonomous project assistants.
AI vs. Human Capabilities: Understanding the unique strengths of AI and the irreplaceable value of human intuition, strategic thinking, and leadership in PM.
Optimizing Human-AI Collaboration: Practical models and frameworks for seamlessly integrating AI tools into PM workflows, emphasizing prompt engineering and growth mindsets.
Cultivating AI-Ready Mindsets: Strategies to foster organizational cultures that embrace AI as an opportunity for innovation and competitive advantage.
Essential Skills for Future-Proof PMs: Identifying the core competencies, including AI literacy, data-driven decision-making, and ethical AI governance, crucial for thriving in an AI-augmented world.
Implementation Roadmap & Best Practices: A strategic guide for integrating AI into your projects and organizations, from pilot projects to establishing Centers of Excellence.
Ethical & Practical Considerations: Navigating data quality, bias, transparency, regulatory compliance (like the EU AI Act), and human-centric values in AI-driven PM.
A Vision for AI-Enabled PM: Envisioning AI as a strategic partner, leading to enhanced outcomes, sustainable competitive advantage, and the rise of the "AI-Augmented PM."
Actionable Next Steps: Concrete steps you can take today to advance your AI journey in project management.
Presented by Kaveh Momeni, a seasoned Project Manager with 15+ years of experience and extensive AI/ML certifications from leading institutions. This session is designed to empower project managers, team leaders, and decision-makers to confidently navigate and leverage AI for transformative project success.
Perfect for anyone looking to understand the strategic implications of AI in project delivery and how to prepare for an AI-driven future.
How Data Annotation Services Drive Innovation in Autonomous Vehicles.docxsofiawilliams5966
Autonomous vehicles represent the cutting edge of modern technology, promising to revolutionize transportation by improving safety, efficiency, and accessibility.
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
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