C OMP 110 M AIN & C ONSOLE I NPUT Instructor: Sasa Junuzovic.

Slides:



Advertisements
Similar presentations
Computer Programming w/ Eng. Applications
Advertisements

C++ Basics March 10th. A C++ program //if necessary include headers //#include void main() { //variable declaration //read values input from user //computation.
Java Programming, 3e Concepts and Techniques Chapter 3 Section 63 – Manipulating Data Using Methods – Day 2.
C OMP 110 S TATE Instructor: Jason Carter. 2 O UTLINE Instance Variables Procedures Properties Print Statements Println vs. Print Overloading.
C OMP 401 C LASS S TATE Instructor: Prasun Dewan.
C OMP 110 C ONDITIONALS Instructor: Jason Carter.
C OMP 401 O BJECTS Instructor: Prasun Dewan 2 C OMPUTER VS. P ROGRAM M ODEL Processor Compiler Program (source code)
C OMP 110 L OAN C ASE S TUDY Instructor: Jason Carter.
C OMP 110 O BJECTS Instructor: Jason Carter. 2 C OMPUTER VS. P ROGRAM M ODEL Processor Compiler Program (source code)
C OMP 110 M AIN & C ONSOLE I NPUT Instructor: Jason Carter.
Object-based Programming Intuitive explanation Using objects to read input Creating objects Style rules.
1 LECTURE#7: Console Input Overview l Introduction to Wrapper classes. l Introduction to Exceptions (Java run-time errors). l Console input using the BufferedReader.
Object-based Programming Intuitive explanation Using objects to read input Creating objects Style rules.
Class Variables & Methods More on dependencies Representation and representation errors Primitive vs. Object Properties Class Variables/Methods Primitive.
Exceptions Problems with error reporting so far –Either ignored exceptions or terminated program on first error. –Error handling and regular code mixed.
Main and Control Flow Programming without ObjectEditor Main Class Control Flow “Real” Programming Linear Branching Looping Programmer-Defined Overloading.
Programmer-Defined Types Object Types as Programmer-defined Types Two-way Dependencies Representation Errors Primitive Vs Object Properties Constructors.
More on Conditionals Miscellaneous (Side effects) Style issues Early returns.
Object Types Primitive types Primitive Vs Object Types Types Classes ABMISpreadsheet AnotherBMISpreadsheet Interfaces BMISpreadsheet Loan Stringdoubleint.
Exceptions Problems with error reporting so far –Either ignored exceptions or terminated program on first error. –Error handling and regular code mixed.
Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs1 Programming in Java Objects, Classes, Program Constructs.
1 Introduction to Console Input  Primitive Type Wrapper Classes  Converting Strings to Numbers  System.in Stream  Wrapping System.in in a Buffered.
Class Variables & Methods More on dependencies Representation and representation errors Primitive vs. Object Properties Class Variables/Methods Primitive.
Chapter 3b Standard Input and Output Sample Development.
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: self-check: #16-19.
State Instance Variables Procedures Properties Print Statements Println Vs Print Overloading J++
Hello, world! Dissect HelloWorld.java Compile it Run it.
INLS 560 – V ARIABLES, E XPRESSIONS, AND S TATEMENTS Instructor: Jason Carter.
C OMP 110 L OOPS A DVANCED Instructor: Prasun Dewan.
C OMP 401 C LASS S TATE Instructor: Prasun Dewan.
Console Input. So far… All the inputs for our programs have been hard-coded in the main method or inputted using the dialog boxes of BlueJ It’s time to.
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
Java means Coffee Java Coffee Beans The name “JAVA” was taken from a cup of coffee.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
C OMP 110/401 A PPENDIX : I NSTALLING AND U SING B ARE B ONES D EVELOPMENT E NVIRONMENT ON U NIX Instructor: Prasun Dewan (FB 150,
C OMP 110/401 A PPENDIX : I NSTALLING AND U SING E CLIPSE Instructor: Prasun Dewan (FB 150,
C OMP 401: C ONSTRUCTORS AND P OINTERS Instructor: Prasun Dewan (FB 150,
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Chapter 2 Using Objects. Types A type defines a set of values and the operations that can be carried out on the values Examples: 13 has type int "Hello,
C OMP 110/401 D OCUMENTATION : C OMMENTS Instructor: Prasun Dewan.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
OOP (pre) Basic Programming. Writing to Screen print will display the string to the screen, the following print statement will be appended to the previous.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
1 Basic Java Constructs and Data Types – Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C.
Introduction to Computing Concepts Note Set 15. JOptionPane.showMessageDialog Message Dialog Allows you to give a brief message to the user Can be used.
Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.
Component 4: Introduction to Information and Computer Science Unit 5: Overview of Programming Languages, Including Basic Programming Concepts Lecture 3.
Java Variables, Types, and Math Getting Started Complete and Turn in Address/Poem.
INLS 560 – F UNCTIONS Instructor: Jason Carter.
C OMP 401 U SER -I NTERFACE VS. M AIN T HREADS Instructor: Prasun Dewan.
C OMP 401 E XCEPTIONS -R EMAINDER Instructor: Prasun Dewan.
Java Input and Output. Java Input  Input is any information needed by your program to complete its execution  So far we have been using InputBox for.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
C OMP 110/401 D OCUMENTATION : A NNOTATIONS Instructor: Prasun Dewan.
IAS 1313: OBJECT ORIENTED PROGRAMMING Week 3: Data Type, Control Structure and Array Prepared by: Mrs Sivabalan1.
CPSC 233 Tutorial January 21 st /22 nd, Linux Commands.
CompSci 230 S Programming Techniques
Objectives You should be able to describe: Interactive Keyboard Input
Yanal Alahmad Java Workshop Yanal Alahmad
Objects, Classes, Program Constructs
Java 24th sep /19/2018 CFILT.
INPUT STATEMENTS GC 201.
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
IFS410 Advanced Analysis and Design
Scope of variables class scopeofvars {
Building Java Programs
Exception Handling Contents
LCC 6310 Computation as an Expressive Medium
CS100A Lect. 10, 1 Oct Input/Output & Program Schema
Presentation transcript:

C OMP 110 M AIN & C ONSOLE I NPUT Instructor: Sasa Junuzovic

2 P REREQUISITES Loops Static State Types Char String.

3 R EMOVING T RAINING W HEELS Compiler ALoanPair Source Code ALoanPair Object (byte) Code Notepad creates reads writes Interpreter calls ObjectEditor main instantiates getTotalLoan() calls ALoanPairInstance MainClass Object Code MainClass Source Code

4 M AIN & C ONSOLE I NPUT Programming without ObjectEditor Main Class Programmer-Defined Overloading Console Input Programmer-Defined Library Class

5 H ELLO W ORLD

6 public class AHelloWorldGreeter { public static void main (String[] args) { System.out.println ("Hello World"); } main header List of user-supplied arguments

7 M AIN A RGUMENTS

8 public class AnArgPrinter { public static void main (String[] args) { System.out.println (args[0]); } args[0] args[1] 1 st Argument 2 nd Argument … …

9 M AIN A RGUMENTS public class AnArgPrinter { public static void main (String[] args) { System.out.println (args[0]); } Program refers to argument User does not supply argument  Exception

10 S TRING I NPUT

11 S TRING I NPUT import java.io.BufferedReader; import java.io.InputStreamReader; public class AnInputPrinter { public static void main (String[] args) { System.out.println("Please enter the line to be printed"); System.out.println ("The input was: " + readString()); } }

12 R EADING A S TRING static BufferedReader inputStream = new BufferedReader(new InputStreamReader(System.in)); public static String readString() { try { return inputStream.readLine(); } catch (Exception e) { System.out.println(e); return ""; } Wait for the user to enter a string (of digits) on the next line In case the user terminates input before entring a string, return “” and print an error message

13 S TRING I NPUT import java.io.BufferedReader; import java.io.InputStreamReader; public class AnInputPrinter { public static void main (String[] args) { System.out.println("Please enter the line to be printed"); System.out.println ("The input was: " + readString()); } static BufferedReader inputStream = new BufferedReader( new InputStreamReader(System.in)); public static String readString() { try { return inputStream.readLine(); } catch (Exception e) { System.out.println(e); return ""; } Global variables referred to by static readString must be static static main() can call only static methods

14 I MPORTING A P ACKAGE public class AnInputPrinter { … new BufferedReader (System.in) … } public class AnInputPrinter { … new java.io. BufferedReader (System.in) … } package java.io; public class BufferedReader { …. } Short name Full name import java.io. BufferedReader ; Import declaration

15 T RY -C ATCH B LOCK try { return inputStream.readLine(); } catch (Exception e) { System.out.println(e); return ""; } Program fragment that can cause an exception Exception handlerException object

16 I NTEGER I NPUT

17 I NTEGER I NPUT import java.io.BufferedReader; import java.io.InputStreamReader; public class AnInputSquarer { public static void main (String[] args) { System.out.println("Please enter the integer to be squared:"); int num = readInt(); System.out.println ("The square is: " + num*num); }

18 READ I NT () Wait for the user to enter a string (of digits) on the next line Return the int represented by the string In case the user makes an error or terminates input before entring a valid int, return 0 and print an error message public static int readInt() { try { return Integer.parseInt(inputStream.readLine()); } catch ( Exception e) { System.out.println(e); return 0; }

19 READ I NT () Wait for the user to enter a string (of digits) on the next line Return the int represented by the string In case the user makes an error or terminates input before entring a valid int, return 0 and print an error message static BufferedReader inputStream = new BufferedReader( new InputStreamReader(System.in)); public static int readInt() { try { return new Integer(inputStream.readLine()).intValue(); } catch ( Exception e) { System.out.println(e); return 0; } Less efficient and not clear that parsing occurs

20 I NTEGER I NPUT import java.io.BufferedReader; import java.io.InputStreamReader; public class AnInputSquarer { public static void main (String[] args) { System.out.println("Please enter the integer to be squared:"); int num = readInt(); System.out.println ("The square is: " + num*num); } static BufferedReader inputStream = new BufferedReader( new InputStreamReader(System.in)); public static int readInt() { try { return Integer.parseInt(inputStream.readLine()); } catch (Exception e) { System.out.println(e); return 0; }

21 R EADING O THER P RIMITIVE V ALUES new Double (inputStream.readLine()).doubleValue()); new Boolean (inputStream.readLine()).booleanValue()); new T (inputStream.readLine()).tValue()); General pattern for reading primitive value of type t

22 P AUSING A P ROGRAM TO V IEW O UTPUT IN AN I NTERACTIVE P ROGRAMMING E NVIRONMENT

23 P AUSING A P ROGRAM TO V IEW O UTPUT IN AN I NTERACTIVE P ROGRAMMING E NVIRONMENT public class AHelloWorldGreeterWithPause { public static void main (String[] args) { System.out.println ("Hello World"); pause(); } public static void pause() { try { System.in.read(); } catch (Exception e) { } Wait for the user to enter a character and return it Legal?

24 public static void pause() { try { 5 + 3; } catch (Exception e) { System.out.println( System.out.println(“hello”)); } E XPRESSION VS. S TATEMENT Expression cannot be used as statement Statement cannot be used as expression

25 F OUR K INDS OF M ETHODS public void setWeight (double newVal) { weight = newVal; } public static double calculatBMI( double weight, double height) { return weight/(height*height); } public int getWeight() { return weight; } public static int readNextNumber() { System.out.println(”Next Number:"); return Console.readInt(); } procedure functionpure function setWeight(70); calculateBMI(70, 1.77) …   getWeight()  70 setWeight(77)  getWeight()  77 impure function getWeight()  readNextNumber ()  5 readNextNumber ()  4 impure function with side effects

26 S IDE E FFECTS public int getWeight() { System.out.println(“get Weight called” ); return weight; } public static int readNextNumber() { System.out.println(”Next Number:"); return new Console.readInt(); } public int increment() { counter++; return counter; } Effect other than computing the return value Printing something Reading input Changing global variable

27 A LTERNATIVE TO C HANGING A G LOBAL V ARIABLE public int increment() { counter++; return counter; } public void incrementCounter() { counter++; } public int getCounter() { return counter; }

28 F UNCTION C ALLS Can be used as expression Can be used as statement When return value is to be ignored Rarely happens Check program to see all return values being used as expressions Other expressions not statements Procedure calls never expressions

29 P AUSING A P ROGRAM TO V IEW O UTPUT IN AN I NTERACTIVE P ROGRAMMING E NVIRONMENT public class AHelloWorldGreeterWithPause { public static void main (String[] args) { System.out.println ("Hello World"); pause(); } public static void pause() { try { System.in.read(); } catch (Exception e) { } Legal expression and statement We do not care about the return value

30 S EPARATE C LASS Console readIntpause readDoublereadBoolean readCharreadString

31 S EPARATE C LASS FOR I NPUT import java.io.BufferedReader; import java.io.InputStreamReader; public class Console { static BufferedReader inputStream = new BufferedReader( new InputStreamReader(System.in)); public static int readInt() { try { return Integer.parseInt(inputStream.readLine()); } catch (Exception e) { System.out.println(e); return 0; } public static String readString() { try { return inputStream.readLine(); } catch (Exception e) { System.out.println(e); return ""; }... //other methods }

32 W ITHOUT C ONSOLE import java.io.BufferedReader; import java.io.InputStreamReader; public class AnInputPrinter { public static void main (String[] args) { System.out.println("Please enter the line to be printed"); System.out.println ("The input was: " + readString()); } static BufferedReader inputStream = new BufferedReader(new InputStreamReader(System.in)); public static String readString() { try { return inputStream.readLine(); } catch (Exception e) { System.out.println(e); return ""; }

33 U SING C ONSOLE public class AnInputPrinter { public static void main (String[] args) { System.out.println("Please enter the line to be printed"); System.out.println ("The input was: " + Console.readString()); }

34 S EPARATION OF C ONCERNS Make independent piece of code as separate method Make independent set of methods as separate class Use operation and data abstraction!

35 M ULTIPLE I NTEGER I NPUT

36 M ULTIPLE I NTEGER I NPUT public class AnInputSummer { public static void main (String[] args) { System.out.println( "Please enter the numbers to be added on separate lines:"); System.out.println ( "Their sum is: " + (Console.readInt() + Console.readInt())); }

37 M ULTIPLE I NTEGER I NPUT Entire line read as string and then parsed as int

38 C OMPUTING P OLAR C OORDINATES

39 C OMPUTING P OLAR C OORDINATES public class AMonolithicPolarCoordinatesComputer { public static void main (String args[]) { int x = readX(); int y = readY(); print (x, y, Math.sqrt(x*x + y*y), Math.atan(y/x)); Console.pause(); } public static int readX() { System.out.println("Please enter x coordinate:"); return Console.readInt(); } public static int readY() { System.out.println("Please enter y coordinate:"); return Console.readInt(); } public static void print( int x, int y, double radius, double angle) { System.out.println("radius: " + radius); System.out.println("angle: " + angle); } Not reusing previous implementation

40 C OMPUTING P OLAR C OORDINATES public class APolarCoordinatesComputer { public static void main (String args[]) { print(readPoint()); Console.pause(); } public static Point readPoint() { System.out.println("Please enter x coordinate:"); int x = Console.readInt(); System.out.println("Please enter y coordinate:"); return new ACartesianPoint(x, Console.readInt()); } public static void print(Point p) { /* System.out.println("x: " + p.getX()); System.out.println("y: " + p.getY()); */ System.out.println("radius: " + p.getRadius()); System.out.println("angle: " + p.getAngle()); } Reusing previous implementation

41 E QUIVALENT U SER I NTERFACES

42 E QUIVALENT U SER I NTERFACES

43 A LGORITHM ( EDIT )

44 A LGORITHM Create ALoanPair instance based on the two values entered by the user in the console window Print the properties of the loan pair object in the console window

45 M AIN M ETHOD public static void main (String[] args) { LoanPair loanPair = new ALoanPair( readCarLoan(), readHouseLoan()); print(loanPair); bus.uigen.ObjectEditor.edit(loanPair); pause(); } Method chaining

46 M AIN M ETHOD W ITHOUT M ETHOD C HAINING public static void main (String[] args) { Loan carLoan = readCarLoan(); Loan houseLoan = readHouseLoan(); LoanPair loanPair = new ALoanPair(carLoan, houseLoan); print (loanPair); bus.uigen.ObjectEditor.edit(loanPair); pause(); } Undefined

47 READ C AR L OAN ()

48 READ C AR L OAN () Prompt user Return an instance of ALoan constructed from the principal public static Loan readCarLoan() { System.out.println("Please enter car principal:"); return new ALoan(Console.readInt()); }

49 P RINTING A L OAN P AIR

50 P RINTING A L OAN P AIR public static void print (LoanPair loanPair) { System.out.println("****Car Loan*****"); print(loanPair.getCarLoan()); System.out.println("****House Loan****"); print(loanPair.getHouseLoan()); System.out.println("****Total Loan****"); print(loanPair.getTotalLoan()); } public static void print (Loan loan) { System.out.println("Principal:" + loan.getPrincipal()); System.out.println("Yearly Interest:" + loan.getYearlyInterest()); System.out.println("Monthly Interest:" + loan.getMonthlyInterest()); } Programmer-defined overloading

51 O BJECT E DITOR. EDIT bus.uigen.ObjectEditor.edit(loanPair); Displays an edit window for the object passed as parameter Full name of the ObjectEditor class

52 C LASS -L EVEL D ECOMPOSITION Monolithic Main Class (Loan User Interface and Loan Computation) ObjectEditor Programmer-defined Class (ALoanPair) Programmer-defined Class (ALoanPair) Driver (ALoanPairDriver) Driver (ALoanPairDriver)

53 M ULTI -L EVEL A LGORITHM /C ODE main readCarLoanreadHouseLoanprint(LoanPair)Console.pause Console.readIntprint(Loan)

54 R UNNING M AIN

55 I NSERTING A B REAK P OINT

56 S INGLE -S TEPPING

57 S TEP I NTO VS. S TEP O VER

58 I NSPECTING V ARIABLES