Presentation is loading. Please wait.

Presentation is loading. Please wait.

C OMP 110 M AIN & C ONSOLE I NPUT Instructor: Jason Carter.

Similar presentations


Presentation on theme: "C OMP 110 M AIN & C ONSOLE I NPUT Instructor: Jason Carter."— Presentation transcript:

1 C OMP 110 M AIN & C ONSOLE I NPUT Instructor: Jason Carter

2 2 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

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

4 4 H ELLO W ORLD

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

6 6 M AIN A RGUMENTS

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

8 8 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

9 9 S TRING I NPUT

10 10 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()); } }

11 11 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

12 12 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

13 13 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

14 14 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

15 15 I NTEGER I NPUT

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

17 17 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; }

18 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 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

19 19 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; }

20 20 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

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

22 22 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?

23 23 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

24 24 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) …   24.57 getWeight()  70 setWeight(77)  getWeight()  77 impure function getWeight()  77 5 4 1 readNextNumber ()  5 readNextNumber ()  4 impure function with side effects

25 25 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

26 26 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; }

27 27 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

28 28 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

29 29 S EPARATE C LASS Console readIntpause readDoublereadBoolean readCharreadString

30 30 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 }

31 31 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 ""; }

32 32 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()); }

33 33 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!

34 34 M ULTIPLE I NTEGER I NPUT

35 35 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())); }

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

37 37 C OMPUTING P OLAR C OORDINATES

38 38 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

39 39 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

40 40 E QUIVALENT U SER I NTERFACES

41 41 E QUIVALENT U SER I NTERFACES

42 42 A LGORITHM ( EDIT )

43 43 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

44 44 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

45 45 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

46 46 READ C AR L OAN ()

47 47 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()); }

48 48 P RINTING A L OAN P AIR

49 49 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

50 50 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

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

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

53 53 R UNNING M AIN

54 54 I NSERTING A B REAK P OINT

55 55 S INGLE -S TEPPING

56 56 S TEP I NTO VS. S TEP O VER

57 57 I NSPECTING V ARIABLES

58 58 C ONDITIONALS public static void printPassFailStatus( int score) { if (score < PASS_CUTOFF) System.out.println("FAILED"); else System.out.println("PASSED"); } printPassFailStatus(95) printPassFailStatus(25) Passed Failed

59 59 I F -E LSE S TATEMENT if ( ) ; else ;

60 60 I F -E LSE S TATEMENT true false

61 61 C OMPOUND S TATEMENT public void fancyPrintGrade( int score) { if (score < PASS_CUTOFF) { System.out.println("**************"); System.out.println("FAILED"); System.out.println("**************"); } else { System.out.println("**************"); System.out.println("PASSED"); System.out.println("Congratulations!"); System.out.println("**************"); }

62 62 C OMPOUND S TATEMENT – { } C ONVENTION public void fancyPrintGrade( int score) { if (score < PASS_CUTOFF) { System.out.println("**************"); System.out.println("FAILED"); System.out.println("**************"); } else { System.out.println("**************"); System.out.println("PASSED"); System.out.println("Congratulations!"); System.out.println("**************"); }

63 63 A VOIDING C ODE D UPLICATION IN I F -E LSE (E DIT ) public void fancyPrintGrade( int score) { if (score < PASS_CUTOFF) { System.out.println("**************"); System.out.println("FAILED"); System.out.println("**************"); } else { System.out.println("**************"); System.out.println("PASSED"); System.out.println("Congratulations!"); System.out.println("**************"); }

64 64 A VOIDING C ODE D UPLICATION IN I F -E LSE public void fancyPrintGrade( int score) { System.out.println("**************"); if (score < PASS_CUTOFF) System.out.println("FAILED"); else { System.out.println("PASSED"); System.out.println("Congratulations!"); } System.out.println("**************"); }

65 65 I F S TATEMENT if (score == MAX_SCORE) System.out.println ("Perfect Score! Congratulations!"); if ( ) ;

66 66 I F S TATEMENT true false

67 67 E LSE -I F public static char toLetterGrade ( int score) { if (score >= A_CUTOFF) return 'A'; else if (score >= B_CUTOFF) return 'B'; else if (score >= C_CUTOFF) return 'C'; else if (score >= D_CUTOFF) return 'D'; else return 'F'; }

68 68 N ESTED I F -E LSE if (score >= A_CUTOFF) return 'A'; else if (score >= B_CUTOFF) return 'B'; else if (score >= C_CUTOFF) return 'C'; else if (score >= D_CUTOFF) return 'D'; else return 'F';

69 69 N ESTED I F -E LSE

70 70 L OOPING printHello(2); printHello(3); hello

71 71 L OOPS public static void printHello(int n) { } int counter = 0; if (counter < n) { counter = counter + 1; System.out.println (“hello”); }

72 72 L OOPS public static void printHello(int n) { } int counter = 0; while (counter < n) { counter = counter + 1; System.out.println (“hello”); }

73 73 I F VS. W HILE S TATEMENT while ( ) ; if ( ) ;

74 74 I F S TATEMENT true false

75 75 W HILE S TATEMENT true false

76 76 W HILE L OOP true false

77 77 S ENTINEL -B ASED F OLDING

78 78 A DDING F IXED N UMBER OF L OANS Loan loan1 = readLoan(); Loan loan2 = readLoan(); Loan loan3 = readLoan(); Loan loan4 = readLoan(); Loan sumLoan = ALoan.add( loan1, ALoan.add(loan2, ALoan.add(loan3, loan4)) ); print(sumLoan);

79 79 G ENERALIZING TO V ARIABLE N UMBER OF L OANS Loan loan1 = readLoan(); Loan loan2 = readLoan(); Loan loan3 = readLoan(); Loan loan4 = readLoan(); … Loan loanN = readLoan(); Loan sumLoan = ALoan.add(loan1, ALoan.add(loan2, ALoan.add(loan3, ALoan.add(loan4, ……( ALoan.add(loanN-1, loanN)*; print (sumLoan); Variable Number of Statements Variable Number of Subexpressions (function calls) Recursion Loops and Arrays

80 80 S PACE -E FFICIENT A DDING OF F IXED N UMBER OF L OANS Loan loan1 = readLoan(); Loan loan2 = readLoan(); Loan sumLoan = ALoan.add(loan1, loan2); loan1 = readLoan(); // 3rd loan sumLoan = ALoan.add(sumLoan, loan1); loan1 = readLoan(); // 4th loan sumLoan = ALoan.add(sumLoan, loan1); print (sumLoan);

81 81 M ORE S PACE -E FFICIENT A DDING OF F IXED N UMBER OF L OANS Loan sumLoan = readLoan(); //first loan Loan nextLoan = readLoan(); //second loan sumLoan = Aloan.add(nextLoan, sumLoan); nextLoan = readLoan(); // 3rd loan sumLoan = ALoan.add(sumLoan, nextLoan); nextLoan = readLoan(); // 4th loan sumLoan = ALoan.add(sumLoan, nextLoan); print (sumLoan);

82 82 M ORE S PACE -E FFICIENT A DDING OF V ARIABLE N UMBER OF L OANS Loan sumLoan = readLoan(); //first loan Loan nextLoan = readLoan(); //second loan sumLoan = Aloan.add(nextLoan, sumLoan); nextLoan = readLoan(); // 3rd loan sumLoan = ALoan.add(sumLoan, nextLoan); nextLoan = readLoan(); // 4th loan sumLoan = ALoan.add(sumLoan, nextLoan); nextLoan = readLoan(); //Nth loan sumLoan = ALoan.add(sumLoan, nextLoan); nextLoan = readLoan(); //sentinel print (sumLoan); N-1 Repetitions

83 83 W HILE L OOP Loan sumLoan = readLoan(); //first loan Loan nextLoan = readLoan(); //second loan while (nextLoan().getPrincipal() >= 0) { sumLoan = ALoan.add(nextLoan, sumLoan); nextLoan = readLoan(); // next loan or sentinel } print (sumLoan); Input Result Program waits forever for second loan Boundary Condition

84 84 C ORRECT S OLUTION Loan sumLoan = new ALoan(0); //initial value Loan nextLoan = readLoan(); //second loan while (nextLoan().getPrincipal() >= 0) { sumLoan = ALoan.add(nextLoan, sumLoan); nextLoan = readLoan(); // next loan or sentinel } print (sumLoan); ALoan.add(new ALoan(0), add(loan1, add (…., loanN) Identity

85 85 A S INGLE S ENTINEL V ALUE Loan sumLoan = new ALoan(0); //initial value Loan nextLoan = readLoan(); //second loan while (nextLoan().getPrincipal() >= 0) { sumLoan = ALoan.add(nextLoan, sumLoan); nextLoan = readLoan(); // next loan or sentinel } print (sumLoan);

86 86 A S INGLE L OAN Loan sumLoan = new ALoan(0); //initial value Loan nextLoan = readLoan(); //second loan while (nextLoan().getPrincipal() >= 0) { sumLoan = ALoan.add(nextLoan, sumLoan); nextLoan = readLoan(); // next loan or sentinel } print (sumLoan);

87 87 T WO L OANS Loan sumLoan = new ALoan(0); //initial value Loan nextLoan = readLoan(); //second loan while (nextLoan().getPrincipal() >= 0) { sumLoan = ALoan.add(nextLoan, sumLoan); nextLoan = readLoan(); // next loan or sentinel } print (sumLoan);

88 88 M ULTIPLYING N UMBERS (E DIT ) public class ANumberMultiplier { public static void main(String[] args) { int product = 1; int nextInt = Console.readInt(); while (nextInt >= 0) { product = product * nextInt; nextInt = Console.readInt(); } System.out.println(product); }

89 89 M ULTIPLYING N UMBERS int product = 1; int num = Console.readInt(); while (num >= 0) { product = product*num; num = Console.readInt(); } print (product); 1 * 20 * 2 * 3 Identify

90 90 C OMPARING T WO S OLUTIONS int product = 1; int num = Console.readInt(); while (num >= 0) { product = product*num; num = Console.readInt(); } print (product); Loan sumLoan = new ALoan(0); //initial value Loan nextLoan = readLoan(); //second loan while (nextLoan().getPrincipal() >= 0) { sumLoan = ALoan.add(nextLoan, sumLoan); nextLoan = readLoan(); // next loan or sentinel } print (sumLoan); result nextVal Read first value Read other value Identity Binary folding function !isSentinel(nextVal)

91 91 G ENERALIZED F OLDING OF A S ENTINEL - T ERMINATED L IST a1a1 a2a2 a3a3 anan a1a1 a1a1 a1a1 f: T, T  T F(x, I)  x

92 92 G ENERALIZED F OLDING F UNCTION T result = I; T nextValue = getNextValue() while (!isSentinel(nextValue)) { result = f(result, nextValue); nextValue = getNextValue(..); } ≥ 0ALoan.add(), * Loan, intnew ALoan(0), 1

93 93 C OMPARING T WO S OLUTIONS (C OMMENTS ) int product = 1; //identity int num = Console.readInt(); // read next list value while (num >= 0) { // sentinel checking product = product*num; // binary folding function num = Console.readInt(); // read next value } print (product);// print value Loan sumLoan = new ALoan(0); //identity Loan nextLoan = readLoan(); // read next list value while (nextLoan().getPrincipal() >= 0) {// sentinel checking sumLoan = Aloan.add(nextLoan, sumLoan); // binary folding function nextLoan = readLoan(); // read next list value } print (sumLoan); // print value


Download ppt "C OMP 110 M AIN & C ONSOLE I NPUT Instructor: Jason Carter."

Similar presentations


Ads by Google