More Java basics Java syntax Input and Output

Similar documents
First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

CS 106 Introduction to Computer Science I

public static void main(string[] args) { System.out.println("hello, world"); } }

INPUT AND OUTPUT STREAMS

Moving from CS 61A Scheme to CS 61B Java

Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

WRITING DATA TO A BINARY FILE

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Install Java Development Kit (JDK) 1.8

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Division of Informatics, University of Edinburgh

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

CS 106 Introduction to Computer Science I

Java Basics: Data Types, Variables, and Loops

Chapter 2: Elements of Java

Lecture 5: Java Fundamentals III

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Java CPD (I) Frans Coenen Department of Computer Science

Creating a Simple, Multithreaded Chat System with Java

Lesson: All About Sockets

13 File Output and Input

Object-Oriented Programming in Java

Using Files as Input/Output in Java 5.0 Applications

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

Building Java Programs

Stream Classes and File I/O

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

JAVA - FILES AND I/O

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Introduction to Programming

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Programming Languages CIS 443

Java Crash Course Part I

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Building Java Programs

1001ICT Introduction To Programming Lecture Notes

READING DATA FROM KEYBOARD USING DATAINPUTSTREAM, BUFFEREDREADER AND SCANNER

Files and input/output streams

CS506 Web Design and Development Solved Online Quiz No. 01

Lecture J - Exceptions

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Building a Multi-Threaded Web Server

AP Computer Science Java Subset

AP Computer Science Static Methods, Strings, User Input

Chapter 3. Input and output. 3.1 The System class

Introduction to Java. CS 3: Computer Programming in Java

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

Chapter 1 Java Program Design and Development

Mail User Agent Project

6.1. Example: A Tip Calculator 6-1

Crash Course in Java

CS170 Lab 11 Abstract Data Types & Objects

Chapter 2 Introduction to Java programming

CS 121 Intro to Programming:Java - Lecture 11 Announcements

Explain the relationship between a class and an object. Which is general and which is specific?

Learning Outcomes. Networking. Sockets. TCP/IP Networks. Hostnames and DNS TCP/IP

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

Lab 1A. Create a simple Java application using JBuilder. Part 1: make the simplest Java application Hello World 1. Start Jbuilder. 2.

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Simple Java Applications

LAB4 Making Classes and Objects

Week 1: Review of Java Programming Basics

How To Write A Program For The Web In Java (Java)

Event-Driven Programming

Variables, Constants, and Data Types

Input / Output Framework java.io Framework

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

The Java I/O System. Binary I/O streams (ascii, 8 bits) The decorator design pattern Character I/O streams (Unicode, 16 bits)

1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

CSS 543 Program 3: Online Tic-Tac-Toe Game Professor: Munehiro Fukuda Due date: see the syllabus

Java Interview Questions and Answers

B.Sc (Honours) - Software Development

Introduction to Object-Oriented Programming

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Programming and Data Structures with Java and JUnit. Rick Mercer

Contents. 9-1 Copyright (c) N. Afshartous

ECE 122. Engineering Problem Solving with Java

Comp 248 Introduction to Programming

Chapter 20 Streams and Binary Input/Output. Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved.

Evaluation. Copy. Evaluation Copy. Chapter 7: Using JDBC with Spring. 1) A Simpler Approach ) The JdbcTemplate. Class...

The following four software tools are needed to learn to program in Java:

Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

CS106A, Stanford Handout #38. Strings and Chars

J a v a Quiz (Unit 3, Test 0 Practice)

Advanced Network Programming Lab using Java. Angelos Stavrou

Introduction to Java

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

What is an I/O Stream?

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Quick Introduction to Java

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

Java Programming Fundamentals

File I/O - Chapter 10. Many Stream Classes. Text Files vs Binary Files

Transcription:

CS 117 Fall 2003 More Java basics Java syntax Input and Output September 22, 2003 What we've done so far Seen the basics of objects and Object-Oriented programming Looked at a few examples of Java programs Picked out some of the parts of Java programs Learned about two special methods, main and the constructor Written our own method for the Account class Seen different types of comments Figured out how to navigate around Linux in the lab Today A bit more about classes, methods, and variables some of this will be review from last week Input and output: 2 methods screen ( console ) windows (JOptionPane and JFrame) Classes, objects, methods, and variables For the next few slides, we will refer to the programs SimpleShapes.java and Account.java

Standard classes Classes: 2 types a.k.a predefined classes the ones that Java provides e.g. System.out, JFrame Programmer-defined classes the classes that we write e.g., Account, SimpleShapes Classes can contain objects of other classes Example: SimpleShapes contains several objects from other classes JFrame win, Graphics g SimpleShapes is dependent on JFrame and Graphics, because it uses its methods JFrame: setsize(), setlocation(), setvisible(), Graphics: setcolor(), fillrect(), filloval(), Wu: SimpleShapes sends messages to JFrame and Graphics Class name vs. object names Class names: Start with a capital letter Good: Account, BankAccount, CheckingAccount, SavingsAccount, RetirementAccount Bad: 2Account, #$%@Java, bankaccount, bank*account Object names: Start with a lowercase letter Creating an object from a class Use the new keyword account = new Account( Jane Doe, 2000); win = new JFrame( Simple Shapes Example ); Calls the constructor for the class Good: account, acct, bankacct, checkingaccount Bad: BankAccount, #&haha, 2good, bankaccount Remember that Java is case sensitive

Method = action Methods method = message sent to a class (Wu) Syntax: <object>.<method>(<arguments>) win.setsize(500,500); g.getcolor(); acct.deposit(50); perform <method> action in <object> class with <arguments> this data You can tell a method from a variable because it will contain parentheses Methods (cont.) <arguments> could be blank g.getcolor(); Multiple arguments are separated by commas Methods will sometimes return a value, but not always more on this later! Method names: start with a lowercase letter (same rules as for object names) Data used by an object double balance; String name; Variables Consists of <type> <name> Variable names: same rules as for method names and object names More in the next chapter A brief diversion: Strings String string1 = This is a string ; Stored as an array position 0: T position 1: h position 2: i position 15: g Length = 16 characters

String methods you should know length(): returns the number of characters in the string (spaces included) substring(x,y): returns all the string's characters between position x and position y in the array indexof( foo ): returns the position in the array of the first character of foo (case-sensitive!) Concatenation: assemble a string from other strings Examples string1 = bah humbug!, string2 = too much homework! ; Value of string1.length()is 9 Value of string2.length() is 18 string3 = string1 + +string2; string3 is now bah humbug! too much homework! Value of string1.substring(4,9) is humbug Value of string2.indexof( homework ) is 9 Input and output Several ways to do input and output screen (console) graphical windows files For now, we'll concentrate on the first 2 files much later Console output We saw this in the Account class: System.out.println( Account holder: +acct.name); System.out.println( Account balance: $ +acct.balance); console = command window (Windows), terminal window (Linux, Mac) We'll use the term standard output (stdout) to refer to this type of output

Writing to stdout The object System.out handles the task of writing the output to the screen Automatically created by Java System.out has two possible methods: print(): prints text to the screen with no newline at the end println(): prints text to the screen with a newline at the end System.out.print[ln]'s arguments Can be a string System.out.println( Hello, Newman! ); Can be a non-string (e.g., number) and/or variable int x = 56; System.out.println(x); Java automatically converts non-strings to strings in this case Can be a combination of the two System.out.println( Account balance: $ +acct.balance); Standard input (stdin) Console input System.in is the Java object that handles reading in data from the console automatically created Usage is a bit more complicated than for stdout System.in reads in one byte at a time we want to read in more than one byte at a time, typically Reading a line from stdin Step 1: Create an InputStreamReader object reads in one character at a time (4 bytes) Step 2: Create a BufferedReader object reads in a single line of text (up to a carriage return) Step 3: Use the readline() method to read text from stdin store this text in a variable

Example Reading in numerical data import java.io.*; public static void main(string[] args) { InputStreamReader in = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(in); String name, agestr; System.out.println( What is your name? ); name = br.readline(); System.out.println( What is your age? ); agestr = br.readline(); In the example, we read in a number (age) Everything is read in as a string We need to convert numbers manually For integers, we use Integer.parseInt() e.g., add to the end of the previous example int age = Integer.parseInt(ageStr); One more thing to add Sometimes, reading in data from stdin could result in an error In Java, we need to catch errors where they might occur lets the program continue to execute, even if something goes wrong called exception handling will talk about this much more later The error that could occur here is called an IOException Our code should look like this import java.io.*; public static void main(string[] args) throws IOException { InputStreamReader in = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(in); String name, agestr; System.out.println( What is your name? ); name = br.readline(); System.out.println( What is your age? ); agestr = br.readline(); int age = Integer.parseInt(ageStr);

What did we just do? When we throw an exception, we pass the responsibility of handling the error to the next level up in this case, to the system on which we're running We could also catch the exception, and just handle the error here we'll do this later Graphical output We'll call this window output Send output to a pop-up window on the screen There are several ways to do this: use a JFrame (as in SimpleShapes.java) use a JDialog (opens a dialog window ) We'll use the second method for now import javax.swing.*; Example public static void main(string[] args) { JOptionPane.showMessageDialog(null, This is a dialog window in the center of the screen ); import javax.swing.*; Another example public static void main(string[] args) { JFrame win = new JFrame(); win.setsize(200,200); win.setvisible(true); JOptionPane.showMessageDialog(win, This is a dialog window at a specific screen location );

" Window input Retrieve input from a pop-up window on the screen very similar to window output Use a dialog window!joptionpane.showinputdialog() (other methods too) import javax.swing.*; Example public static void main(string[] args) { String name, agestr; name = JOptionPane.showInputDialog(null, What is your name? ); agestr = JOptionPane.showInputDialog(null, What is your age? ); int age = Integer.parseInt(ageStr);