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

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

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

Full file at

File I/O Array Basics For-each loop

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

Text User Interfaces. Keyboard IO plus

Lecture Set 2: Starting Java

Programming with Java

First Java Program - Output to the Screen

Lecture Set 2: Starting Java

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

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

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

CS2: Debugging in Java

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

Basic Programming Elements

Computational Expression

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

BASIC INPUT/OUTPUT. Fundamentals of Computer Science

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

EXCEPTIONS. Fundamentals of Computer Science I

Using Java Classes Fall 2018 Margaret Reid-Miller

4. Java Project Design, Input Methods

Chapter. Let's explore some other fundamental programming concepts

AP Computer Science Unit 1. Writing Programs Using BlueJ

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

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

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

AP Computer Science Unit 1. Writing Programs Using BlueJ

COMP 202 Java in one week

Programming II (CS300)

Programming Language Basics

Class Library java.util Package. Bok, Jong Soon

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

Chapter 4 Defining Classes I

Chapter 4 Classes in the Java Class Libraries

Reading Input from Text File

Classes and Objects Part 1

Pace University. Fundamental Concepts of CS121 1

AP Computer Science Unit 1. Programs

COMP102: Test 1 Model Solutions

Primitive Data Types: Intro

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

Java Bytecode (binary file)

Full file at

Operators and Expressions

Fundamentals of Programming Data Types & Methods

Introduction to Java Unit 1. Using BlueJ to Write Programs

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

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

COMP 202. Java in one week

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

Introduction to Java Applications

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

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

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

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

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

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

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

Chapter 4 Introduction to Control Statements

Chapter 2 Elementary Programming

COMP 202 Java in one week

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

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

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

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a

Software Practice 1 Basic Grammar

CS112 Lecture: Working with Numbers

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

Formatted Output Pearson Education, Inc. All rights reserved.

CSE 142 Su 04 Computer Programming 1 - Java. Objects

Section 2: Introduction to Java. Historical note

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

STUDENT LESSON A7 Simple I/O

Introduction to Programming Using Java (98-388)

Getting started with Java

Chapter 17. Iteration The while Statement

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

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

Full file at

Full file at

CS 112 Introduction to Programming

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 );

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

CSCI 1103: File I/O, Scanner, PrintWriter

2: Basics of Java Programming

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

CSC Java Programming, Fall Java Data Types and Control Constructs

Example Program. public class ComputeArea {

CSCI 355 Lab #2 Spring 2007

CS 231 Data Structures and Algorithms, Fall 2016

Java Coding 3. Over & over again!

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

CSE 1223: Exam II Autumn 2016

Programming in Java

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

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

CSCI 1103: File I/O, Scanner, PrintWriter

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

Transcription:

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.

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" ) );

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.

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.

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;

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" );

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.

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.

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.

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

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.