java_help_index 08/14/18 07:14:34 walton 1 of 1

Size: px
Start display at page:

Download "java_help_index 08/14/18 07:14:34 walton 1 of 1"

Transcription

1 java_help_index 08/14/18 07:14:34 walton 1 of 1 JAVA LANGUAGE HELP Tue Aug 14 07:14:34 EDT 2018 Programming Language Specific Help java How to write JAVA solutions. jdebug How to debug infinite loops and crashes in JAVA programs.

2 java 08/06/17 15:49:31 walton 1 of 8 JAVA Help Mon Feb 18 06:24:37 EST 2013 JAVA Language Program Structure Typical program structure including end of file detection, finding symbols such as = that end a string of numbers, and debugging is: import java.util.scanner; static class MyClass If you define classes, remember to make them static public static void main ( String[] args ) debug = ( args.length > 0 ); public class PPP Here PPP is the program name and this code is in the PPP.java file. static boolean debug = false; static Scanner scan = new Scanner ( System.in ); printf ( format,... ) prints output using the given format with... representing the format controlled arguments. static void printf ( String format, Object... args ) System.out.format ( format, args ); Ditto but suppress if debug == false. static void dprintf ( String format, Object... args ) if ( debug ) System.out.format ( format, args ); while ( scan.hasnextline() ) Read and print test case name if there is one. String testcasename = scan.nextline(); System.out.println ( testcasename ); Read a number and process a number if there is one. WARNING: number must be terminated by whitespace. if ( scan.hasnextdouble() ) double d = scan.nextdouble(); Math.sin... Math.PI... Check that next thing is ZZZ. WARNING: ZZZ must be terminated by whitespace. assert ( scan.next().equals ( "ZZZ" ) );

3 java 08/06/17 15:49:31 walton 2 of 8 Skip line feed at end of line. Needed because we must be at a line beginning when we start the next test case. scan.nextline();..... Debugging output. dprintf (... ); It is fairly common for JAVA programs that run well for the contestant to crash when run by the judge. The usual cause is judge s input data that triggers an exception not observed with contestant s input data. If you are NOT in an ACM programming contest, the judge will likely return to you the input of the test case your program crashed on, and you can debug that. If you ARE in an ACM programming contest, your best bet is to type into the PPP.in file a lot of legal input data that might break the program, so your program will be run against it by make submit and you will observe any crash before you submit. Output. printf ( "XXX %.6f XXX",... ); System.out.println ( ); WARNING: Numbers printed with println or print may use exponen- tial notation. Input Input is read from the standard input, System.in; you MUST NOT open any file for input. You may assume that input is correctly formatted, except for the rare problem where you are told to produce special output if the input contains a formatting error. Do not waste time checking for input errors when you do not have to. Remember that the main class of a program must have the same name as the program, and also that everything declared directly within this class, including subclasses, must be static. Test cases begin with a test case name line checked for by Scanner hasnextline and read by nextline. As soon as the test case name is successfully read it is printed by System.out.println. After reading and printing the test case name line, the rest of the test case data is read with Scanner functions such as next, hasnextdouble nextdouble, etc. WARNING: this assumes that input tokens are delimited by whitespace. Dealing with delimiters other than whitespace is tricky if the delimiters are also important input, and one method of doing so is described in the Delimiter Tokens section below.

4 java 08/06/17 15:49:31 walton 3 of 8 Data may consist of numbers, perhaps with non-number tokens like * thrown in to indicate the end of a sequence of numbers. The lines containing numbers may be very long, so they should be read one number at a time and not read as a line. See the summer demonstration problem solution which reads numbers. For some problems there are no test case name lines but instead each test case has one input line containing text and one output line containing text. For these the test case input line is read the same way as the test case name line is read above. See the reverser demonstration problem solution which reads text lines. Output Output is written to the standard output, System.out; you MUST NOT open any file for output; you MUST NOT write to the standard error output. In general, to be correct your program must produce EXACTLY the one and only correct sequence of output characters. The main exception is that when floating point numbers are output with a given number of decimal places, you are permitted to output numbers which differ from other correct output by one unit in the last decimal place. You must use the correct upper or lower case and use only a single space character as a separator unless instructed to line things up in columns. Output can be written using System.out.println and the + string concatenation operator, or it can be written using System.out.format. The latter is necessary if numbers must be written with decimal places, as converting numbers to Strings with + may produce numbers in exponential notation. Some formats that may be useful are "%.3f" to print a double with exactly 3 decimal places in as few columns as possible, "%10.3f" to print the double right adjusted in 10 columns, "%10s" to print a string right adjusted in 10 columns, and "%-10s" to print a string LEFT adjusted in 10 columns. Here the numbers 3 and 10 are merely representative, and can be replaced by any other non-zero positive integers. When using System.out.format, use "%n" to output an end-of-line. See the summer demonstration problem solution which outputs floating point double s. Debugging When your program is executed by the judge, it will NOT be passed ANY arguments. A standard debugging technique is to output extra debugging information if and only if your program is passed an argument. The above program defines debug to be true if and only if the program is called with one or more arguments, and defines dprintf to do what System.out. format does if and only if debug is true. Thus dprintf can be used to print debugging information.

5 java 08/06/17 15:49:31 walton 4 of 8 Debugging is best done with information printed by dprintf, and not with a debugger. In JAVA, crashes usually give the line number where the fault occurred, so using the debugger may not be necessary for crashes. As the standard jdb debugger is difficult to use directly, a special program is provided to run it if you must: see help jdebug file. This is of most use if your program goes into an infinite loop or crashes. It is also a good idea to use assert statements to check that assumptions you have made are valid during actual program execution. For example, if you expect the next input token to be "ZZZ" you can use assert ( scan.next().equals ( "ZZZ" ) ); In our environment JAVA is run with assert statement execution enabled (by the -ae option to the java(1) interpreter), so you can count on assert statements executing (which would not be true in other programming environments). See the summer demonstration problem solution which uses dprintf and assert. Delimiter Tokens If you want to use characters like, to delimit numbers, but also want to make, into a token, you have to use usedelimiter and findinline. If you want to determine whether the next thing in the input is a line feed, you must use findwithinhorizon with a horizon of 1 character. The following code makes,, (, ), :, and end-of-line (represented by \n ) into both delimiters and tokens. The code also provides a means of determining whether a token String represents a number and extracting that number. import java.util.scanner; import java.util.regex.pattern; final static Scanner scan = new Scanner ( System.in ).usedelimiter ( "[(),: \t\f\n]+" ); static Pattern end_of_line = Pattern.compile ( "\\G\n" ); Use in findwithinhorizon ( end_of_line, 1 ). static Pattern end_space = Pattern.compile ( "\\G[ \t\f]*(?m)$" ); Skips horizontal whitespace before end of line. Use with findinline. Note that (?m) must be used to turn on multi-line mode so $ matches a the point just before a line feed. static Pattern separator = Pattern.compile ( "\\G[ \t\f]*([(),:])" ); Skips to and returns separator other than line feed. For use with findinline. static String EOL = "(END OF LINE)"; static String EOF = "(END OF FILE)"; static String get_token ( ) if ( scan.findinline ( separator )!= null ) return scan.match().group ( 1 ); Match group 1 is what was matched by the first (...) parenthesized subexpres- sion in the pattern, i.e., ([(),:]). scan.findinline ( end_space ); if ( scan.findwithinhorizon ( end_of_line, 1 )!= null ) return EOL; if ( scan.hasnext() ) return scan.next(); return EOF;

6 java 08/06/17 15:49:31 walton 5 of 8 Return Double if string is a number, or null if not. doublevalue() of the Double returns the number proper. static Double get_number ( String s ) try return Double.valueOf ( s ); catch ( NumberFormatException e ) return null; The fundamental problem with findwithinhorizon is that you do not know what horizon to use. If you use 0, which denotes infinity, your program will NOT be interactive, because findwithinhorizon will read to an end of file before it returns anything. So the only horizon you can use with an interactive program is 1 character, and we only use it above to find the end of line. Another difficulty is that findinline ( end_space ), if called with a line feed next, returns null and NOT an empty string, so it cannot be used to determine that there is nothing before the next line feed. So findwithinhorizon ( end_of_line, 1 ) is the only way to discover that the next character in the input is a line feed without possibly reading and skipping a non-whitespace character. See the vcalc demonstration problem solution which implements delimiters that are also tokens. Function and Macro Synopsis You can get full documentation of the functions mentioned above plus other useful information from your favorite web site if you are permitted to use the web. Some useful classes are- String Scanner Formatter Math Double Pattern In ACM contests in which you are not permitted access to the web, local JAVA documentation can be accessed by the command: javahelp The following is an extract from JAVA documentation of details needed to use common functions and numeric constants. Here we assume you already know something about how to use the above classes so we do not have to explain them from scratch. Note that an int is guaranteed to be at least 32 bits and a long is guaranteed to be at least 64 bits. Floating point computations should always be done using double s, and NOT float s, to avoid having too little precision. import java.util.scanner; import java.util.regex.pattern; Scanner s = new Scanner ( System.in ); Pattern p1 = Pattern.compile ( "\\G[ \t\f]*([(),:])" ); Pattern p2 = Pattern.compile ( "\\G[ \t\f]*(?m)$" ); Pattern p3 = Pattern.compile ( "\\G\n" );

7 java 08/06/17 15:49:31 walton 6 of 8 s.hasnextline() s.nextline() Returns true iff nextline() will not raise an exception. Returns a String consisting of all input up to the next line end, and skips that input and the line end. s.hasnextdouble() Returns true iff nextdouble(), s.hasnextint() nextint(), or nextlong() will not s.hasnextlong() raise an exception. s.nextdouble() s.nextint() s.nextlong() s.hasnext() s.next() Returns next token which must be a number as a double, int, or long. Number must be delimited by whitespace (if usedelimiter not used). Returns true if next() will not raise an exception. Returns next token. Token is a non-empty String delimited by whitespace (if usedelimiter not used). s.usedelimiter ( "[ \t\f\n,():]+" ) Reset token delimiter to a regular expression. The example given makes whitespace and the characters,, (, ), : delimiters. s.findinline ( p1 ) Return next String matching the Pattern p1 if such exists before the next line feed, or return null if there is no such String. For p1 as above, to get a match the input must consist of within line whitespace followed by one of the characters,, (, ), or :. s.match().group ( 1 ) Return as a String the part of the last find- InLine matched string that matches the first () parenthesized group within the pattern s regular expression. For p1 this group is ([(),:]). s.findinline ( p2 ) Returns any whitespace at the end of a line, or returns null if a line feed is next or if there is a non-whitespace character before the next line feed. s.findwithinhorizon ( p3, 1 ) If the next character in the input is a line feed, returns that as a string. Else returns null. Double.valueOf ( s ) Returns Double containing numeric double value represented by String s, or if s does not represent a double number, raises the NumberFormatException. Double.valueOf(s).doubleValue() Returns the double numeric value represented by String s, or if s does not represent a double number, raises the NumberFormatException.

8 java 08/06/17 15:49:31 walton 7 of 8 System.out.format ( format,... ) Format is a String that can contain the following directives, in which W and P stand for sequences of decimal digits, where W is used for widths and P for precisions : %d Outputs an int or long as a decimal integer with no spaces before or after. %Wd Outputs an int or long as a decimal integer right adjusted in W columns. %f Outputs a double as a floating point number with 6 decimal places and no spaces before or after. %n Outputs an end of line. import java.text.decimalformat; DecimalFormat d = new DecimalFormat ( "0.##############" ); d.format ( n ) Returns the number n converted to a string. Given d as above, the result will have up to 14 decimal places with trailing 0 s stripped, unlike the %.14f format which does not strip trailing 0 s. Integer.MAX_VALUE, Integer.MIN_VALUE, Long.MAX_VALUE, Long.MIN_VALUE, Double.MAX_VALUE, Double.MIN_VALUE. %.Pf %Wf Ditto but with P decimal places instead of 6 decimal places. Outputs a double as a floating point number with 6 decimal places right adjusted in W columns. These are the maximum and minimum numbers that can be stored respectively in an int, long, or double. Math.PI, Math.E Math.abs, Math.sin, Math.cos, Math.atan2, Math.exp. %W.Pf Ditto but with P decimal places instead of 6 decimal places. %s Outputs a String (or char[]) with no spaces before or after. The mathematical constants PI and e, and typical math functions. These must have the Math. prefix. %Ws %-Ws Ditto but outputs the String RIGHT adjusted in W columns. Ditto but outputs the String LEFT adjusted in W columns. %c Outputs a char as a UNICODE character with no spaces before or after.

9 java 08/06/17 15:49:31 walton 8 of 8 File: Author: Date: java Bob Walton <walton@deas.harvard.edu> See top of file. The authors have placed this file in the public domain; they make no warranty and accept no liability for this file.

10 jdebug 10/12/15 06:53:44 walton 1 of 2 Debugging with JDEBUG Wed Jan 30 12:03:25 EST 2013 Introduction If the program is going to crash, it will do so. Otherwise if the program loops indefinitely, wait until it is so looping, type a carriage return to get a prompt, and then type Jdebug is an interface to the jdb debugger which is needed because jdb by itself does not allow the program being debugged to have a standard input that is distinct from the standard input of the jdb debugger itself. It is recommended that a debugger like jdebug not be used unless your program crashes or goes into an infinite loop. In all other cases it is better to put print statements (such as dprintf or dprintln - see help java ) into your code to print just exactly what you need to see. So in this help file we assume you are debugging a crash or infinite loop in a JAVA program. Running the Program Assume the program you are debugging is named PPP and its input file is PPP.in. Then % jdebug PPP.in PPP [main 1] cont will start the program in the debugger with PPP.in as its input file. Here cont is the continue command. > suspend > thread 1 to first stop the program and then tell the debugger that you want to look at the main thread, thread 1. Examining a Crashed or Stopped Program Once stopped execute > where to see the backtrace of methods that have been called. Each method call is referred to as a frame and the where command lists the frames in the stack. The debugger has a current frame that it is looking at, and initially the current frame is where execution stopped because of the suspend command or the throw of an uncaught exception. To see the execution point in the current frame and the local variables use the commands > list > locals

11 jdebug 10/12/15 06:53:44 walton 2 of 2 To move up or down the stack and to see where in the stack you are use the commands > up > where > down > where The up and down commands change the current frame. Make the frame called by the current frame current: Set a breakpoint at line N: Here PPP is the program name. Continue to next breakpoint: List breakpoints: > down > stop at PPP:N > cont > clear The following is a synopsis of useful commands. Continue: Stop the Program: Go to next statement in current frame: > cont > suspend > next Delete breakpoint at line N: Here PPP is the program name. > clear PPP:N Trace methods during execution: > trace go methods Print value of expression E: A static variable V in class PPP is denoted by PPP.V. > print E Do N nexts: > N next Dump contents of object E: > dump E Go to next statement in current frame or frame called by current frame: Do N steps: Print local variables: Print the execution point in the current frame: Print the part of the stack that ends with the current frame: Make the caller of the current frame current: > step > N step > locals > list > where > up File: Author: Date: Output documentation: > help jdebug Bob Walton <walton@seas.harvard.edu> See top of file. The authors have placed this file in the public domain; they make no warranty and accept no liability for this file.

java_advanced_io_demos_index 08/14/18 07:14:41 walton 1 of 1

java_advanced_io_demos_index 08/14/18 07:14:41 walton 1 of 1 java_advanced_io_demos_index 08/14/18 07:14:41 walton 1 of 1 JAVA ADVANCED IO DEMOS Tue Aug 14 07:14:41 EDT 2018 Advanced Input/Output Demonstrations -------- ------------ -------------- vcalc 2D Geometry

More information

ing execution. That way, new results can be computed each time the Class The Scanner

ing execution. That way, new results can be computed each time the Class The Scanner ing execution. That way, new results can be computed each time the run, depending on the data that is entered. The Scanner Class The Scanner class, which is part of the standard Java class provides convenient

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

File I/O Array Basics For-each loop

File I/O Array Basics For-each loop File I/O Array Basics For-each loop 178 Recap Use the Java API to look-up classes/method details: Math, Character, String, StringBuffer, Random, etc. The Random class gives us several ways to generate

More information

A token is a sequence of characters not including any whitespace.

A token is a sequence of characters not including any whitespace. Scanner A Scanner object reads from an input source (keyboard, file, String, etc) next() returns the next token as a String nextint() returns the next token as an int nextdouble() returns the next token

More information

Text User Interfaces. Keyboard IO plus

Text User Interfaces. Keyboard IO plus Text User Interfaces Keyboard IO plus User Interface and Model Model: objects that solve problem at hand. User interface: interacts with user getting input from user giving output to user reporting on

More information

Lecture Set 2: Starting Java

Lecture Set 2: Starting Java Lecture Set 2: Starting Java 1. Java Concepts 2. Java Programming Basics 3. User output 4. Variables and types 5. Expressions 6. User input 7. Uninitialized Variables 0 This Course: Intro to Procedural

More information

Programming with Java

Programming with Java Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules

More information

First Java Program - Output to the Screen

First Java Program - Output to the Screen First Java Program - Output to the Screen These notes are written assuming that the reader has never programmed in Java, but has programmed in another language in the past. In any language, one of the

More information

Lecture Set 2: Starting Java

Lecture Set 2: Starting Java Lecture Set 2: Starting Java 1. Java Concepts 2. Java Programming Basics 3. User output 4. Variables and types 5. Expressions 6. User input 7. Uninitialized Variables 0 This Course: Intro to Procedural

More information

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI CSCI 2010 Principles of Computer Science Data and Expressions 08/09/2013 CSCI 2010 1 Data Types, Variables and Expressions in Java We look at the primitive data types, strings and expressions that are

More information

Using APIs. Chapter 3. Outline Fields Overall Layout. Java By Abstraction Chapter 3. Field Summary static double PI

Using APIs. Chapter 3. Outline Fields Overall Layout. Java By Abstraction Chapter 3. Field Summary static double PI Outline Chapter 3 Using APIs 3.1 Anatomy of an API 3.1.1 Overall Layout 3.1.2 Fields 3.1.3 Methods 3.2 A Development Walkthrough 3.2.1 3.2.2 The Mortgage Application 3.2.3 Output Formatting 3.2.4 Relational

More information

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string COMP 202 Built in Libraries and objects CONTENTS: Introduction to objects Introduction to some basic Java libraries string COMP 202 Objects and Built in Libraries 1 Classes and Objects An object is an

More information

CS2: Debugging in Java

CS2: Debugging in Java CS2: Debugging in Java 1. General Advice Jon Cook (LFCS) April 2003 Debugging is not always easy. Some bugs can take a long time to find. Debugging concurrent code can be particularly difficult and time

More information

COMP102: 181. Menu. More while loops. Admin: Test. Peter Andreae

COMP102: 181. Menu. More while loops. Admin: Test. Peter Andreae Menu COMP102: 181 More while loops Admin: Test Designing loops with numbers COMP102: 182 When the number of steps is known at the beginning of the loop: int count = 0; int num = 1; while ( count < number)

More information

Basic Programming Elements

Basic Programming Elements Chapter 2 Basic Programming Elements Lecture slides for: Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2

More information

Computational Expression

Computational Expression Computational Expression Variables, Primitive Data Types, Expressions Janyl Jumadinova 28-30 January, 2019 Janyl Jumadinova Computational Expression 28-30 January, 2019 1 / 17 Variables Variable is a name

More information

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on: Data and Expressions Data and Expressions Let's explore some other fundamental programming concepts Chapter 2 focuses on: Character Strings Primitive Data The Declaration And Use Of Variables Expressions

More information

BASIC INPUT/OUTPUT. Fundamentals of Computer Science

BASIC INPUT/OUTPUT. Fundamentals of Computer Science BASIC INPUT/OUTPUT Fundamentals of Computer Science Outline: Basic Input/Output Screen Output Keyboard Input Simple Screen Output System.out.println("The count is " + count); Outputs the sting literal

More information

A variable is a name for a location in memory A variable must be declared

A variable is a name for a location in memory A variable must be declared Variables A variable is a name for a location in memory A variable must be declared, specifying the variable's name and the type of information that will be held in it data type variable name int total;

More information

EXCEPTIONS. Fundamentals of Computer Science I

EXCEPTIONS. Fundamentals of Computer Science I EXCEPTIONS Exception in thread "main" java.lang.numberformatexception: For input string: "3.5" at java.lang.numberformatexception.forinputstring(numberformatexception.java:48) at java.lang.integer.parseint(integer.java:458)

More information

Using Java Classes Fall 2018 Margaret Reid-Miller

Using Java Classes Fall 2018 Margaret Reid-Miller Using Java Classes 15-121 Fall 2018 Margaret Reid-Miller Today Strings I/O (using Scanner) Loops, Conditionals, Scope Math Class (random) Fall 2018 15-121 (Reid-Miller) 2 The Math Class The Math class

More information

4. Java Project Design, Input Methods

4. Java Project Design, Input Methods 4-1 4. Java Project Design, Input Methods Review and Preview You should now be fairly comfortable with creating, compiling and running simple Java projects. In this class, we continue learning new Java

More information

Chapter. Let's explore some other fundamental programming concepts

Chapter. Let's explore some other fundamental programming concepts Data and Expressions 2 Chapter 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design 2007 Pearson Addison-Wesley. All rights reserved Data and Expressions Let's explore some

More information

AP Computer Science Unit 1. Writing Programs Using BlueJ

AP Computer Science Unit 1. Writing Programs Using BlueJ AP Computer Science Unit 1. Writing Programs Using BlueJ 1. Open up BlueJ. Click on the Project menu and select New Project. You should see the window on the right. Navigate to wherever you plan to save

More information

Input. Scanner keyboard = new Scanner(System.in); String name;

Input. Scanner keyboard = new Scanner(System.in); String name; Reading Resource Input Read chapter 4 (Variables and Constants) in the textbook A Guide to Programming in Java, pages 77 to 82. Key Concepts A stream is a data channel to or from the operating system.

More information

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration STATS 507 Data Analysis in Python Lecture 2: Functions, Conditionals, Recursion and Iteration Functions in Python We ve already seen examples of functions: e.g., type()and print() Function calls take the

More information

We now start exploring some key elements of the Java programming language and ways of performing I/O

We now start exploring some key elements of the Java programming language and ways of performing I/O We now start exploring some key elements of the Java programming language and ways of performing I/O This week we focus on: Introduction to objects The String class String concatenation Creating objects

More information

AP Computer Science Unit 1. Writing Programs Using BlueJ

AP Computer Science Unit 1. Writing Programs Using BlueJ AP Computer Science Unit 1. Writing Programs Using BlueJ 1. Open up BlueJ. Click on the Project menu and select New Project. You should see the window on the right. Navigate to wherever you plan to save

More information

COMP 202 Java in one week

COMP 202 Java in one week CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator COMP 202 Java in one week The Java Programming Language A programming language

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 02: Using Objects MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Using Objects 2 Introduction to Object Oriented Programming Paradigm Objects and References Memory Management

More information

Programming Language Basics

Programming Language Basics Programming Language Basics Lecture Outline & Notes Overview 1. History & Background 2. Basic Program structure a. How an operating system runs a program i. Machine code ii. OS- specific commands to setup

More information

Class Library java.util Package. Bok, Jong Soon

Class Library java.util Package. Bok, Jong Soon Class Library java.util Package Bok, Jong Soon javaexpert@nate.com www.javaexpert.co.kr Enumeration interface An object that implements the Enumeration interface generates a series of elements, one

More information

Project 1. Java Data types and input/output 1/17/2014. Primitive data types (2) Primitive data types in Java

Project 1. Java Data types and input/output 1/17/2014. Primitive data types (2) Primitive data types in Java Java Data types and input/output Sharma Chakravarthy Information Technology Laboratory (IT Lab) Computer Science and Engineering Department The University of Texas at Arlington, Arlington, TX 76019 Email:

More information

Chapter 4 Defining Classes I

Chapter 4 Defining Classes I Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the

More information

Chapter 4 Classes in the Java Class Libraries

Chapter 4 Classes in the Java Class Libraries Programming Fundamental I ACS-1903 Chapter 4 Classes in the Java Class Libraries 1 Random Random The Random class provides a capability to generate pseudorandom values pseudorandom because the stream of

More information

Reading Input from Text File

Reading Input from Text File Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2114) Lab 5 Reading Input from Text File Eng. Mohammed Alokshiya November 2, 2014 The simplest

More information

Classes and Objects Part 1

Classes and Objects Part 1 COMP-202 Classes and Objects Part 1 Lecture Outline Object Identity, State, Behaviour Class Libraries Import Statement, Packages Object Interface and Implementation Object Life Cycle Creation, Destruction

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

AP Computer Science Unit 1. Programs

AP Computer Science Unit 1. Programs AP Computer Science Unit 1. Programs Open DrJava. Under the File menu click on New Java Class and the window to the right should appear. Fill in the information as shown and click OK. This code is generated

More information

COMP102: Test 1 Model Solutions

COMP102: Test 1 Model Solutions Family Name:.......................... Other Names:.......................... ID Number:............................ COMP102: Test 1 Model Solutions 27 July, 2007 Instructions Time allowed: 45 minutes.

More information

Primitive Data Types: Intro

Primitive Data Types: Intro Primitive Data Types: Intro Primitive data types represent single values and are built into a language Java primitive numeric data types: 1. Integral types (a) byte (b) int (c) short (d) long 2. Real types

More information

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan COSC 123 Computer Creativity Introduction to Java Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Key Points 1) Introduce Java, a general-purpose programming language,

More information

Java Bytecode (binary file)

Java Bytecode (binary file) Java is Compiled Unlike Python, which is an interpreted langauge, Java code is compiled. In Java, a compiler reads in a Java source file (the code that we write), and it translates that code into bytecode.

More information

Full file at

Full file at Chapter 2 Console Input and Output Multiple Choice 1) Valid arguments to the System.out object s println method include: (a) Anything with double quotes (b) String variables (c) Variables of type int (d)

More information

Operators and Expressions

Operators and Expressions Operators and Expressions Conversions. Widening and Narrowing Primitive Conversions Widening and Narrowing Reference Conversions Conversions up the type hierarchy are called widening reference conversions

More information

Fundamentals of Programming Data Types & Methods

Fundamentals of Programming Data Types & Methods Fundamentals of Programming Data Types & Methods By Budditha Hettige Overview Summary (Previous Lesson) Java Data types Default values Variables Input data from keyboard Display results Methods Operators

More information

Introduction to Java Unit 1. Using BlueJ to Write Programs

Introduction to Java Unit 1. Using BlueJ to Write Programs Introduction to Java Unit 1. Using BlueJ to Write Programs 1. Open up BlueJ. Click on the Project menu and select New Project. You should see the window on the right. Navigate to wherever you plan to save

More information

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value Lecture Notes 1. Comments a. /* */ b. // 2. Program Structures a. public class ComputeArea { public static void main(string[ ] args) { // input radius // compute area algorithm // output area Actions to

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

COMP 202. Java in one week

COMP 202. Java in one week COMP 202 CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator Java in one week The Java Programming Language A programming language

More information

CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING

CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING INPUT AND OUTPUT Input devices Keyboard Mouse Hard drive Network Digital camera Microphone Output devices.

More information

Introduction to Java Applications

Introduction to Java Applications 2 Introduction to Java Applications OBJECTIVES In this chapter you will learn: To write simple Java applications. To use input and output statements. Java s primitive types. Basic memory concepts. To use

More information

Classes and Objects Miscellany: I/O, Statics, Wrappers & Packages. CMSC 202H (Honors Section) John Park

Classes and Objects Miscellany: I/O, Statics, Wrappers & Packages. CMSC 202H (Honors Section) John Park Classes and Objects Miscellany: I/O, Statics, Wrappers & Packages CMSC 202H (Honors Section) John Park Basic Input/Output Version 9/10 2 Printing to the Screen In addition to System.out.print() (and println()):

More information

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls. Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:

More information

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous CS256 Computer Science I Kevin Sahr, PhD Lecture 25: Miscellaneous 1 main Method Arguments recall the method header of the main method note the argument list public static void main (String [] args) we

More information

CISC-124. This week we continued to look at some aspects of Java and how they relate to building reliable software.

CISC-124. This week we continued to look at some aspects of Java and how they relate to building reliable software. CISC-124 20180129 20180130 20180201 This week we continued to look at some aspects of Java and how they relate to building reliable software. Multi-Dimensional Arrays Like most languages, Java permits

More information

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. File Input and Output

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. File Input and Output WIT COMP1000 File Input and Output I/O I/O stands for Input/Output So far, we've used a Scanner object based on System.in for all input (from the user's keyboard) and System.out for all output (to the

More information

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 10/e Education, Inc. All Rights Reserved. Each class you create becomes a new type that can be used to declare variables and create objects. You can declare new classes as needed;

More information

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Java application programming } Use tools from the JDK to compile and run programs. } Videos at www.deitel.com/books/jhtp9/ Help you get started

More information

Chapter 4 Introduction to Control Statements

Chapter 4 Introduction to Control Statements Introduction to Control Statements Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives 2 How do you use the increment and decrement operators? What are the standard math methods?

More information

Chapter 2 Elementary Programming

Chapter 2 Elementary Programming Chapter 2 Elementary Programming Part I 1 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from this chapter, you will learn how to solve practical

More information

COMP 202 Java in one week

COMP 202 Java in one week COMP 202 Java in one week... Continued CONTENTS: Return to material from previous lecture At-home programming exercises Please Do Ask Questions It's perfectly normal not to understand everything Most of

More information

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming Exam 1 Prep Dr. Demetrios Glinos University of Central Florida COP3330 Object Oriented Programming Progress Exam 1 is a Timed Webcourses Quiz You can find it from the "Assignments" link on Webcourses choose

More information

Java for Python Programmers. Comparison of Python and Java Constructs Reading: L&C, App B

Java for Python Programmers. Comparison of Python and Java Constructs Reading: L&C, App B Java for Python Programmers Comparison of Python and Java Constructs Reading: L&C, App B 1 General Formatting Shebang #!/usr/bin/env python Comments # comments for human readers - not code statement #

More information

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M Università degli Studi di Bologna Facoltà di Ingegneria Principles, Models, and Applications for Distributed Systems M tutor Isam M. Al Jawarneh, PhD student isam.aljawarneh3@unibo.it Mobile Middleware

More information

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a Spring 2017 Name: TUID: Page Points Score 1 28 2 18 3 12 4 12 5 15 6 15 Total: 100 Instructions The exam is closed book, closed notes. You may not use a calculator, cell phone, etc. i Some API Reminders

More information

Software Practice 1 Basic Grammar

Software Practice 1 Basic Grammar Software Practice 1 Basic Grammar Basic Syntax Data Type Loop Control Making Decision Prof. Joonwon Lee T.A. Jaehyun Song Jongseok Kim (42) T.A. Sujin Oh Junseong Lee (43) 1 2 Java Program //package details

More information

CS112 Lecture: Working with Numbers

CS112 Lecture: Working with Numbers CS112 Lecture: Working with Numbers Last revised January 30, 2008 Objectives: 1. To introduce arithmetic operators and expressions 2. To expand on accessor methods 3. To expand on variables, declarations

More information

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output Last revised January 12, 2006 Objectives: 1. To introduce arithmetic operators and expressions 2. To introduce variables

More information

Formatted Output Pearson Education, Inc. All rights reserved.

Formatted Output Pearson Education, Inc. All rights reserved. 1 29 Formatted Output 2 OBJECTIVES In this chapter you will learn: To understand input and output streams. To use printf formatting. To print with field widths and precisions. To use formatting flags in

More information

CSE 142 Su 04 Computer Programming 1 - Java. Objects

CSE 142 Su 04 Computer Programming 1 - Java. Objects Objects Objects have state and behavior. State is maintained in instance variables which live as long as the object does. Behavior is implemented in methods, which can be called by other objects to request

More information

Section 2: Introduction to Java. Historical note

Section 2: Introduction to Java. Historical note The only way to learn a new programming language is by writing programs in it. - B. Kernighan & D. Ritchie Section 2: Introduction to Java Objectives: Data Types Characters and Strings Operators and Precedence

More information

Lesson 3: Accepting User Input and Using Different Methods for Output

Lesson 3: Accepting User Input and Using Different Methods for Output Lesson 3: Accepting User Input and Using Different Methods for Output Introduction So far, you have had an overview of the basics in Java. This document will discuss how to put some power in your program

More information

STUDENT LESSON A7 Simple I/O

STUDENT LESSON A7 Simple I/O STUDENT LESSON A7 Simple I/O Java Curriculum for AP Computer Science, Student Lesson A7 1 STUDENT LESSON A7 Simple I/O INTRODUCTION: The input and output of a program s data is usually referred to as I/O.

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Getting started with Java

Getting started with Java Getting started with Java Magic Lines public class MagicLines { public static void main(string[] args) { } } Comments Comments are lines in your code that get ignored during execution. Good for leaving

More information

Chapter 17. Iteration The while Statement

Chapter 17. Iteration The while Statement 203 Chapter 17 Iteration Iteration repeats the execution of a sequence of code. Iteration is useful for solving many programming problems. Interation and conditional execution form the basis for algorithm

More information

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1 Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1 Motivation In the programs we have written thus far, statements are executed one after the other, in the order in which they appear. Programs often

More information

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls. Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:

More information

Full file at

Full file at Java Programming, Fifth Edition 2-1 Chapter 2 Using Data within a Program At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional

More information

Full file at

Full file at Chapter 1 Primitive Java Weiss 4 th Edition Solutions to Exercises (US Version) 1.1 Key Concepts and How To Teach Them This chapter introduces primitive features of Java found in all languages such as

More information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 112 Introduction to Programming Summary of Methods; User Input using Scanner Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu Admin

More information

Chapter 5 Methods. public class FirstMethod { public static void main(string[] args) { double x= -2.0, y; for (int i = 1; i <= 5; i++ ) { y = f( x );

Chapter 5 Methods. public class FirstMethod { public static void main(string[] args) { double x= -2.0, y; for (int i = 1; i <= 5; i++ ) { y = f( x ); Chapter 5 Methods Sections Pages Review Questions Programming Exercises 5.1 5.11 142 166 1 18 2 22 (evens), 30 Method Example 1. This is of a main() method using a another method, f. public class FirstMethod

More information

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15 Table of Contents 1 INTRODUCTION... 1 2 IF... 1 2.1 BOOLEAN EXPRESSIONS... 3 2.2 BLOCKS... 3 2.3 IF-ELSE... 4 2.4 NESTING... 5 3 SWITCH (SOMETIMES KNOWN AS CASE )... 6 3.1 A BIT ABOUT BREAK... 7 4 CONDITIONAL

More information

CSCI 1103: File I/O, Scanner, PrintWriter

CSCI 1103: File I/O, Scanner, PrintWriter CSCI 1103: File I/O, Scanner, PrintWriter Chris Kauffman Last Updated: Mon Dec 4 10:03:11 CST 2017 1 Logistics Reading from Eck Ch 2.1 on Input, File I/O Ch 11.1-2 on File I/O Goals Scanner for input Input

More information

2: Basics of Java Programming

2: Basics of Java Programming 2: Basics of Java Programming CSC 1051 Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/

More information

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs CSC 1051 Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova

More information

CSC Java Programming, Fall Java Data Types and Control Constructs

CSC Java Programming, Fall Java Data Types and Control Constructs CSC 243 - Java Programming, Fall 2016 Java Data Types and Control Constructs Java Types In general, a type is collection of possible values Main categories of Java types: Primitive/built-in Object/Reference

More information

Example Program. public class ComputeArea {

Example Program. public class ComputeArea { COMMENTS While most people think of computer programs as a tool for telling computers what to do, programs are actually much more than that. Computer programs are written in human readable language for

More information

CSCI 355 Lab #2 Spring 2007

CSCI 355 Lab #2 Spring 2007 CSCI 355 Lab #2 Spring 2007 More Java Objectives: 1. To explore several Unix commands for displaying information about processes. 2. To explore some differences between Java and C++. 3. To write Java applications

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

Java Coding 3. Over & over again!

Java Coding 3. Over & over again! Java Coding 3 Over & over again! Repetition Java repetition statements while (condition) statement; do statement; while (condition); where for ( init; condition; update) statement; statement is any Java

More information

Tools : The Java Compiler. The Java Interpreter. The Java Debugger

Tools : The Java Compiler. The Java Interpreter. The Java Debugger Tools : The Java Compiler javac [ options ] filename.java... -depend: Causes recompilation of class files on which the source files given as command line arguments recursively depend. -O: Optimizes code,

More information

CSE 1223: Exam II Autumn 2016

CSE 1223: Exam II Autumn 2016 CSE 1223: Exam II Autumn 2016 Name: Instructions: Do not open the exam before you are told to begin. This exam is closed book, closed notes. You may not use any calculators or any other kind of computing

More information

Programming in Java

Programming in Java 320341 Programming in Java Fall Semester 2015 Lecture 2: Fundamental Structures Instructor: Jürgen Schönwälder Slides: Bendick Mahleko Outline - Program structure - Data types - Variables - Constants -

More information

Hello World. n Variables store information. n You can think of them like boxes. n They hold values. n The value of a variable is its current contents

Hello World. n Variables store information. n You can think of them like boxes. n They hold values. n The value of a variable is its current contents Variables in a programming language Basic Computation (Savitch, Chapter 2) TOPICS Variables and Data Types Expressions and Operators Integers and Real Numbers Characters and Strings Input and Output Variables

More information

Name: Checked: Access the Java API at the link above. Why is it abbreviated to Java SE (what does the SE stand for)?

Name: Checked: Access the Java API at the link above. Why is it abbreviated to Java SE (what does the SE stand for)? Lab 6 Name: Checked: Objectives: Learn about the Java API Test code snippets interactively to explore data representation and casts Practice using Math, Random, String, and other classes from the Java

More information

CSCI 1103: File I/O, Scanner, PrintWriter

CSCI 1103: File I/O, Scanner, PrintWriter CSCI 1103: File I/O, Scanner, PrintWriter Chris Kauffman Last Updated: Wed Nov 29 13:22:24 CST 2017 1 Logistics Reading from Eck Ch 2.1 on Input, File I/O Ch 11.1-2 on File I/O Goals Scanner for input

More information

Today. Book-keeping. File I/O. Subscribe to sipb-iap-java-students. Inner classes. Debugging tools

Today. Book-keeping. File I/O. Subscribe to sipb-iap-java-students. Inner classes.  Debugging tools Today Book-keeping File I/O Subscribe to sipb-iap-java-students Inner classes http://sipb.mit.edu/iap/java/ Debugging tools Problem set 1 questions? Problem set 2 released tomorrow 1 2 So far... Reading

More information