Third AP Edition. Object-Oriented Programming and Data Structures. Maria Litvin. Gary Litvin. Phillips Academy, Andover, Massachusetts

Similar documents
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

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

Introduction to Java. CS 3: Computer Programming in Java

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

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

Moving from CS 61A Scheme to CS 61B Java

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

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

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

CS170 Lab 11 Abstract Data Types & Objects

Java Programming. Binnur Kurt Istanbul Technical University Computer Engineering Department. Java Programming. Version 0.0.

java Features Version April 19, 2013 by Thorsten Kracht

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

1001ICT Introduction To Programming Lecture Notes

CS 106 Introduction to Computer Science I

Chapter 2: Elements of Java

Chapter 3. Input and output. 3.1 The System class

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

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

Object-Oriented Programming in Java

AP Computer Science Java Subset

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

Introduction to Programming

Chapter 2 Basics of Scanning and Conventional Programming in Java

Pemrograman Dasar. Basic Elements Of Java

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

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

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

Sample CSE8A midterm Multiple Choice (circle one)

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

Chapter 1 Java Program Design and Development

Building Java Programs

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

6.1. Example: A Tip Calculator 6-1

Introduction to Java

AP Computer Science Static Methods, Strings, User Input

Maria Litvin Phillips Academy, Andover, Massachusetts. Gary Litvin Skylight Publishing, Andover, Massachusetts

Java Crash Course Part I

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

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

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Fundamentals of Java Programming

Variables, Constants, and Data Types

Konzepte objektorientierter Programmierung

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

C++ INTERVIEW QUESTIONS

Lecture 5: Java Fundamentals III

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

Building Java Programs

Data Structures Lecture 1

Chapter 2 Introduction to Java programming

Basics of Java Programming Input and the Scanner class

An Incomplete C++ Primer. University of Wyoming MA 5310

Java Interview Questions and Answers

Comp 248 Introduction to Programming

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

Java Programming Fundamentals

Programming and Data Structures with Java and JUnit. Rick Mercer

Java Basics: Data Types, Variables, and Loops

Week 1: Review of Java Programming Basics

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

Programming in Java Course Technology, a part of Cengage Learning.

Arrays. Introduction. Chapter 7

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

More on Objects and Classes

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Java Application Developer Certificate Program Competencies

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

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

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

Crash Course in Java

ECE 122. Engineering Problem Solving with Java

LAB4 Making Classes and Objects

LAB 1. Familiarization of Rational Rose Environment And UML for small Java Application Development

Lecture 9. Semantic Analysis Scoping and Symbol Table

Chapter 2 Elementary Programming

Using Files as Input/Output in Java 5.0 Applications

Part I. Multiple Choice Questions (2 points each):

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Introduction to Java Lecture Notes. Ryan Dougherty

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

Programming Languages CIS 443

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

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

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

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

Statements and Control Flow

Introduction to Object-Oriented Programming

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

AP Computer Science Java Mr. Clausen Program 9A, 9B

Topic 11 Scanner object, conditional execution

An Overview of Java. overview-1

Installing Java. Table of contents

WHAT ARE PACKAGES? A package is a collection of related classes. This is similar to the notion that a class is a collection of related methods.

Semantic Analysis: Types and Type Checking

Introduction to Python

Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science

Transcription:

Third AP Edition Object-Oriented Programming and Data Structures Maria Litvin Phillips Academy, Andover, Massachusetts Gary Litvin Skylight Software, Inc. Skylight Publishing Andover, Massachusetts

Skylight Publishing 9 Bartlet Street, Suite 70 Andover, MA 01810 web: e-mail: http://www.skylit.com sales@skylit.com support@skylit.com Copyright 2015 by Maria Litvin, Gary Litvin, and Skylight Publishing This material is provided to you as a supplement to the book Java Methods, third AP edition You may print out one copy for personal use and for face-to-face teaching for each copy of the Java Methods book that you own or receive from your school. You are not authorized to publish or distribute this document in any form without our permission. You are not permitted to post this document on the Internet. Feel free to create Internet links to this document s URL on our web site from your web pages, provided this document won t be displayed in a frame surrounded by advertisement or material unrelated to teaching AP * Computer Science or Java. You are not permitted to remove or modify this copyright notice. Library of Congress Control Number: 2014922396 ISBN 978-0-9824775-6-4 * AP and Advanced Placement are registered trademarks of The College Board, which was not involved in the production of and does not endorse this book. The names of commercially available software and products mentioned in this book are used for identification purposes only and may be trademarks or registered trademarks owned by corporations and other commercial entities. Skylight Publishing and the authors have no affiliation with and disclaim any sponsorship or endorsement by any of these product manufacturers or trademark owners. Oracle, Java, and Java logos are trademarks or registered trademarks of Oracle Corporation and/or its affiliates in the U.S. and other countries.

Appendix B: Common Syntax Error Messages Exception in thread "main" java.lang.noclassdeffounderror wrong name Exception in thread "main" java.lang.noclassdeffounderror /java Exception in thread "main" java.lang.noclassdeffounderror /class Exception in thread "main" java.lang.nosuchmethoderror: main class is public, should be declared in a file named cannot return a value from method whose result type is void non-static method cannot be referenced from a static context cannot find symbol -- class cannot find symbol -- method cannot find symbol -- variable '}' expected 'class' or 'interface' expected illegal character <identifier> expected '(' or '[' expected variable might not have been initialized unclosed string literal missing return statement ';' expected incompatible types '[' expected array required, but java.lang.string found possible loss of precision '.class' expected attempting to assign weaker access privileges call to super must be first statement in constructor invalid method declaration; return type required is not abstract and does not override abstract method B-1

B-2 APPENDIX B ~ COMMON SYNTAX ERROR MESSAGES C:\mywork>java hello Exception in thread "main" java.lang.noclassdeffounderror: hello (wrong name: Hello) This run-time error (exception) happens when you mistype a lower case letter for upper case. Normally a class name (e.g., Hello) starts with an upper case letter and the file name should be the same. Under Windows, the command javac hello.java will compile the file Hello.java, but when you try to run it, as above, it reports an exception. It should be: C:\mywork>java Hello C:\mywork>java Hello.java Exception in thread "main" java.lang.noclassdeffounderror: Hello/java or C:\mywork>java Hello.class Exception in thread "main" java.lang.noclassdeffounderror: Hello/class The command to run the Java interpreter should use the class name but should not include any extension, neither.java nor.class. An extension in the file name confuses the interpreter about the location of the source code file (the extension is interpreted as a subfolder). C:\mywork>java Hello Exception in thread "main" java.lang.nosuchmethoderror: main This exception may be reported when the main method is missing or its signature is incorrect. The correct signature is public static void main (String[] args) Possible mistakes:

APPENDIX B ~ COMMON SYNTAX ERROR MESSAGES B-3 private static void main (String[] args) public void main (String[] args) public static int main (String[] args) public static void main (String args) C:\mywork>javac Test.java class Hello is public, should be declared in a file named Hello.java public class Hello A mismatch between the file name (Test) and the class name (Hello) they must be the same. cannot return a value from method whose result type is void return 0; In Java, main is void, so return is not necessary and you can t use return 0 or return "Hello, World!" in it. non-static method printmsg() cannot be referenced from a static context printmsg(); The method printmsg is called directly from main, without any dot-prefix, and the keyword static is missing in the printmsg header: public void printmsg(string msg) should be: public static void printmsg(string msg) Since main is a static method and it calls printmsg with no "something-dot" prefix, printmsg is assumed to be another static method of the same class. Another way of handling this is to create an object of the Hello class in main and call that object s printmsg: Hello test = new Hello(); test.printmsg();

B-4 APPENDIX B ~ COMMON SYNTAX ERROR MESSAGES cannot find symbol symbol : class Scanner location: class Hello Scanner kboard = new Scanner(System.in); The compiler automatically finds classes, either source or compiled, used by your class Hello, as long as they are located in the same folder as Hello.java. Library classes must be properly imported in your class. For example: import java.util.scanner; at the top of your program. Another possible reason for this error message is incorrect or misspelled primitive data type name. For example: gives private bool match(string word, String pattern) cannot find symbol symbol : class bool location: class Hello private bool match(string word, String pattern) It should be boolean. cannot find symbol symbol : method printmessage() location: class Hello test.printmessage(); This error occurs when a method is called incorrectly: either its name is misspelled or upper-lower case is misplaced. Here the method name should be printmsg. The same error is reported when you call a method for a wrong type of object. For example: System.println("Hello"); instead of

APPENDIX B ~ COMMON SYNTAX ERROR MESSAGES B-5 System.out.println("Hello"); You will get: cannot find symbol symbol : method println(java.lang.string) location: class java.lang.system System.println("Hello, World!"); Another example: cannot find symbol symbol : method println(java.lang.string,java.lang.string) location: class java.io.printstream System.out.println("Hello, World!", name); Here a comma is used instead of a + in the println call. This makes it a call with two parameters instead of one and System.out does not have a println method that takes two String parameters. cannot find symbol symbol : variable name location: class Hello name = kboard.next(); A very common error cannot find symbol may result from an undeclared variable or a misspelled local variable or field name. Here it should be String name = kboard.next(); or name should be declared earlier. '}' expected } An extra opening brace or a missing closing brace may produce several errors, including

B-6 APPENDIX B ~ COMMON SYNTAX ERROR MESSAGES illegal start of expression ';' expected and finally '}' expected or reached end of file while parsing } class, interface, or enum expected } This error often results from an extra closing brace (or a missing opening brace) or a method declared outside a class. illegal character: \8220 System.out.println( Hello, World! ); Smart quote characters accidentally left in the source file by a word processor instead of straight single or double quotes may cause this error. The same error is reported when the source file contains any non-ascii character in the code (outside comments). <identifier> expected public name; <identifier> expected is a rather common error message. Here name is a variable, but the compiler thinks it is a class name. Actually, it is the data type designation that is missing. It should be: private String name; The same happens here:

APPENDIX B ~ COMMON SYNTAX ERROR MESSAGES B-7 private nrows, ncols; It gives an error: <identifier> expected static nrows, ncols; thinking that nrows is a data type. Same here: public static void printmsg(msg) {... } a missing type designator for the parameter in a method s header. It produces: <identifier> expected public static void printmsg(msg) It should be: public static void printmsg(string msg) '(' or '[' expected Hello test = new Hello; This error is reported when a parenthesis or square bracket is missing. In the above example it should be: Hello test = new Hello(); variable kboard might not have been initialized String name = kboard.next(); This error happens if you use a local variable before initializing it. Scanner kboard; declares the variable kboard but you also need to initialize it before you use it:

B-8 APPENDIX B ~ COMMON SYNTAX ERROR MESSAGES or Scanner kboard = new Scanner(System.in); Scanner kboard;... kboard = new Scanner(System.in); ')' expected System.out.print(Enter your name: "); unclosed string literal System.out.print(Enter your name: "); 2 errors A missing opening double quote in a literal string produces these two errors. missing return statement } A method, other than void, must return a value. ';' expected System.out.println("Hello, World!" + name) A few compiler error messages are actually self-explanatory! incompatible types found : int required: boolean if (i = 0) It is supposed to be if (i == 0) Single = is assignment operator, which returns an int value (assuming i is an int). The if statement, on the other hand, expects a boolean. Similarly,

APPENDIX B ~ COMMON SYNTAX ERROR MESSAGES B-9 gives: public boolean isinrange(int i) { return i = 0 i > 100; } operator cannot be applied to int,boolean return i = 0 i > 100; incompatible types found : int required: boolean return i = 0 i > 100; 2 errors Another situation with incompatible types is when a literal string is used in place of a char constant or vice-versa. For example: incompatible types found : java.lang.string required: char char letter = "A"; Should be: char letter = 'A'; '[' expected int[] counts = new int(10); An array should be created using brackets, not parentheses: int[] counts = new int[10]; array required, but java.lang.string found char letter = str[k]; Use str.charat(k) method, not [k] with strings.

B-10 APPENDIX B ~ COMMON SYNTAX ERROR MESSAGES possible loss of precision found : double required: int int x = 2.5; This happens when a double value is assigned to an int variable. '.class' expected double y = double(x); not a statement double y = double(x); ';' expected double y = double(x); 3 errors Incorrect syntax in the cast operator causes these errors. Should be: double y = (double)x; actionperformed(java.awt.event.actionevent) in Hello cannot implement actionperformed(java.awt.event.actionevent) in java.awt.event.actionlistener; attempting to assign weaker access privileges; was public void actionperformed(actionevent e) This error is reported when the keyword public is missing in the actionperformed method s header: void actionperformed(actionevent e) Should be: public void actionperformed(actionevent e)

APPENDIX B ~ COMMON SYNTAX ERROR MESSAGES B-11 call to super must be first statement in constructor super("hello"); This error is reported when the call super is not the first statement in a constructor or if it is mistakenly placed in a method. In particular, this happens when you accidentally put void in a constructor s header. invalid method declaration; return type required public hello() // Constructor This error is reported when a constructor s name is misspelled or is different from the name of the class. The compiler then thinks it is a method with a missing return type. It can also happen if indeed a return type is missing in a method header. Hello is not abstract and does not override abstract method compareto(hello) in java.lang.comparable public class Hello implements Comparable<Hello> This error is reported when a class claims to implement an interface (in this case Comparable) but does not supply all the necessary methods or misspells a method name, or has a wrong number or types of parameters in one of the interface methods.