Lecture 4.1: More on Scanner, Methods, and Codingbat Michael Hsu CSULA.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

CIT 590 Intro to Programming Java lecture 3. Hashmaps The equivalent of python dictionaries. With both ArrayLists and Hashmaps, the syntax only allows.
CS 106 Introduction to Computer Science I 02 / 04 / 2008 Instructor: Michael Eckmann.
Evan Korth Scanner class Evan Korth NYU. Evan Korth Java 1.5 (5.0)’s Scanner class Prior to Java 1.5 getting input from the console involved multiple.
Scanner Pepper With credits to Dr. Siegfried. The Scanner Class Most programs will need some form of input. At the beginning, all of our input will come.
© 2006 Pearson Addison-Wesley. All rights reserved2-1 Console Input Using the Scanner Class Starting with version 5.0, Java includes a class for doing.
CS 106 Introduction to Computer Science I 09 / 18 / 2006 Instructor: Michael Eckmann.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: IO *Standard Output *Formatting Decimal.
1 Scanning Tokens. 2 Tokens When a Scanner reads input, it separates it into “tokens”  … at least when using methods like nextInt()  nextInt() takes.
Scanner & Stepwise Refinement Pepper With credit to Dr. Siegfried.
1 CSE 142 Lecture Notes Interactive Programs with Scanner Chapter 4 Suggested reading: Suggested self-checks: Section 4.10 #1-4 These lecture.
1 Interactive Applications (CLI) Interactive Applications Command Line Interfaces Project 1: Calculating BMI Example: Factoring the Solution Reading for.
Intro to Java Programming  A computer follows the instruction precisely and exactly.  Anything has to be declared and defined before it can be used.
Conditional If Week 3. Lecture outcomes Boolean operators – == (equal ) – OR (||) – AND (&&) If statements User input vs command line arguments.
Simple Programs from Chapter 2 Putting the Building Blocks All Together (corresponds with Chapter 2)
Recitation 1 CS0445 Data Structures Mehmud Abliz.
Console Input & Output CSS 161: Fundamentals of Computing Joe McCarthy 1.
Sahar Mosleh California State University San MarcosPage 1 System.out.println for console output System.out is an object that is part of the Java language.
Slides prepared by Rose Williams, Binghamton University Chapter 2 Console Input and Output.
Computer Programming 2 Lab(1) I.Fatimah Alzahrani.
Math class services (functions) Primitive vs reference data types Scanner class Math class services (functions) Primitive vs reference data types Scanner.
CS 106 Introduction to Computer Science I 01 / 31 / 2007 Instructor: Michael Eckmann.
Can we talk?. In Hello World we already saw how to do Standard Output. You simply use the command line System.out.println(“text”); There are different.
CMSC 202 Java Console I/O. July 25, Introduction Displaying text to the user and allowing the user to enter text are fundamental operations performed.
Unix Environment Input Output 2  List Content (ls) ◦ ls (list current directory) ◦ ls –all (include hidden files/folders)  Make directory (mkdir) ◦
String and Scanner CS 21a: Introduction to Computing I First Semester,
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
FUNDAMENTALS 2 CHAPTER 2. OPERATORS  Operators are special symbols used for:  mathematical functions  assignment statements  logical comparisons 
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
Introduction Chapter 1 8/31 & 9/1 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010.
Style guide in JAVA From a lecture by Dr. Rahman.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CS 106 Introduction to Computer Science I 02 / 01 / 2008 Instructor: Michael Eckmann.
CSC 142 Computer Science II Zhen Jiang West Chester University
Martin T. Press.  Main Method and Class Name  Printing To Screen  Scanner.
Strings and I/O. Lotsa String Stuff… There are close to 50 methods defined in the String class. We will introduce several of them here: charAt, substring,
COP 2551 Introduction to Object Oriented Programming with Java Topics –Introduction to the Java language –Code Commenting –Java Program Structure –Identifiers.
Chapter 2 Console Input and Output Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Slides prepared by Rose Williams, Binghamton University Console Input and Output.
Keyboard and Screen I/O (Input/Output). Screen Output  System.out is an object that is part of the Java language. (Don’t worry yet about why there is.
© 2007 Lawrenceville Press Slide 1 Chapter 4 Review Assignment Statement An assignment statement gives a value to a variable. Assignment can take several.
Interactive Programs Programs that get input from the user 1 In PowerPoint, click on the speaker icon then click the "Play" button to hear the narration.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
Lab 04-2 Objectives:  Understand what a file is.  Learn how to use the File class  Learn how to use the Scanner class to read from files  Learn about.
1 Arrays Chapter 8. Objectives You will be able to Use arrays in your Java programs to hold a large number of data items of the same type. Initialize.
Introduction to programming in java
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CompSci 230 S Programming Techniques
Lecture 2 D&D Chapter 2 & Intro to Eclipse IDE Date.
CS 160 Final Review.
Input/Output.
TemperatureConversion
Project 1.
CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II
CSC 1051 – Data Structures and Algorithms I
Chapter 3 Java Input/Output.
Topic 11 Scanner object, conditional execution
BIT115: Introduction to Programming
Introduction to Classes and Methods
Unit 1: Intro Lesson 3: Input.
Chapter 3 Input/Output.
Building Java Programs
Object Oriented Programming
Building Java Programs
មជ្ឈមណ្ឌលកូរ៉េ សហ្វវែរ អេច អ ឌី
CSC 1051 – Data Structures and Algorithms I
Math class services (functions)
Presentation transcript:

Lecture 4.1: More on Scanner, Methods, and Codingbat Michael Hsu CSULA

From Lecture 4: How to Use java.util.Scanner 1. import java.util.Scanner; 2. Create an instance of the Scanner class, a Scanner object: Scanner scanner = new Scanner(System.in); //We set up Scanner object with the name “scanner” 3. Do Stuff with it 4. Close it to free up resources: scanner.close();

From Lecture 4: Scanner Input Methods   Since most of the the methods are instance methods, you have to create the scanner object before you can use it  The main method is not an instance method because of the keyword “static”  For example, methods in String and Math are static methods  You can read an entire line, a String, a double, an int, etc.  Read the documentation and lecture code examples to learn more about Scanner methods

Unsatisfying Conclusion From Lecture 4: How to Read an entire line?  ??????????????????????????????  See Scanner lecture code example

Debugging a Tricky Logical Error 1. Identify the bug behavior 2. Identify how the “bug” occurred 1. What was the program doing at the moment 2. What was the program doing prior 3. What was the program after 3. Read documentation 1. Make sure it is not something as simple as using the method wrong 4. If you can’t figure it out, google it or ask your friend for help

Debugging nextLine() Skipping 1. Identify the bug behavior 1. nextLine() doesn’t read the and seems to be skipped 2. Identify how the “bug” occurred 1. What was the program doing at the moment: 1. Trying to read an entire line 2. What was the program doing prior 1. Read in an int using nextInt 3. What was the program doing after 1. Suppose to print out the result

Taking a Deeper Look at Scanner.nextInt()  Reading the documentation:  public int nextInt()  Scans the next token of the input as an int.  What is a token?  “A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.”  When you type a number, then press ENTER, nextInt() reads your number as an integer, but it didn’t read the carriage return (remember /r?)

So How to Mitigate the Issue? 1. Call nextLine() after reading a token using nextInt(), nextDouble(), etc to consume the /r character 2. Use static parsing methods (not instance methods) provided by the various classes, and just read in the entire line then convert it. 1. Integer.parseInt() 2. Double.parseDouble()

Useful Scanner Methods  nextInt(): reads the next token as an int  next(): reads the next token as a string  nextLine(): reads the entire line, consumes end of line(carriage return)  nextDouble(): reads the next token as a double  nextBoolean(): reads in the next token as a boolean

What Exactly Are Methods?  We talked about the main method, we also used methods from Scanner  Methods:  A block of code that can be called using the identifier  It can do things without any input/output, like System.out.println()  You can pass in parameters as inputs  You can also specify the method return type, and return a value of that type using the return keyword.

Example Method: public double calculateTriangleArea(double base, double height) { double area = base * height / 2; return area; } Return type Method Name/Identifier Parameters Return a value with type matching the return type specified

Another Example Method: public void calculateTriangleArea(double base, double height) { System.out.println("I'm just printing out stuff"); } Return type is void, so not returning anything

Using Methods  Recall the differences between static and instance methods:  Static methods belong to the class  Has the “static” keyword between “public” and the return type  Using static methods:  CLASSNAME.STATIC_METHOD_NAME()  Example: Integer.parseInt(“23456”);  Instance methods belong to the objects that are instances of the class  Does not have the “static” keyword  Using instance methods:  Create an object first  OBJECT_NAME.METHOD_NAME()  Example: scanner.nextInt()

What Do I Use In CS201 When I Write My Own Methods?  If I don’t specify, make the methods static.  For example, you have a class MyColor, with a static method that prints out the color passed in. In the main method, you will do MyColor.printColor(“blue”)  For Codingbat assignements, use instance methods because how they test your code.

Codingbat   Free interactive learning site created by Nick Parlante at Stanford  Gives you immediate feedback on your code  Tests your method using different inputs  IMPORTANT: Sign up for an account to do the problems assigned in the labs  Use your real name so I know which student you are  Add my to the Share To field under Preferences so I know you did the   Otherwise you won’t get credit for it  Remember to login every time you do an assignment on codingbat

More on Codingbat  Solutions for all problems are widely available online  I encourage you to NOT copy solutions, as there will be problems on the quiz/midterm/final that are modeled after codingbat problems.

System.out.println() and System.out.print()  println writes the string literal you passed in, then write a new line character at the end  print does not add a new line character at the end