130 likes | 225 Views
Java. ashishfa@cse 24 th sep 2004. Today’s menu. Input How to enter number, name to program without changing the program code Loop constructs How to do task repetitively. input. Want the program to print a number in words.
E N D
Java ashishfa@cse 24th sep 2004 CFILT
Today’s menu • Input • How to enter number, name to program without changing the program code • Loop constructs • How to do task repetitively CFILT
input • Want the program to print a number in words. • There is provision in java to give it to program after running the program • 2 ways • One by passing argument • One by interactive method(console) Demo Addup, cmdarg CFILT
Sample code (passing argument) static public void main(String args[]) { int total = 0; int i,j; i = Integer.parseInt(args[0]); j = Integer.parseInt(args[1]); total = i + j ; System.out.println("total = " + total); } CFILT
Sample code (interactive console) static public void main(String args[]) { BufferedReader console = new BufferedReader( new InputStreamReader(System.in)); int i = 0, j = 0; try { System.out.print("Enter first number "); i=Integer.parseInt(console.readLine()); System.out.print("Enter second number "); j=Integer.parseInt(console.readLine()); } catch (Exception e) { } System.out.println(i + " + " + j + " = " + (i+j)); } CFILT
Loop or iterations • How to print same line 4 times This is sentence 1. This is sentence 2. This is sentence 3. This is sentence 4. • How to calculate values like 1+2+3+4+5+6+7… • How to count number of words in a sentence… CFILT
Simple loop - While int i = 1; while (i <= 5) { System.out.println ("count : " + i); i++; } Initialise a counter is (i <=5) ? NO YES Print “count “ + i i I + 1 CFILT
Syntax of while loop While (boolean expression) { Statementes; . . . } Demo whilerepeat Whilecount CFILT
Other loop construct -for for (i = 1; i <= 5 ; i++) { System.out.println ("count : " + i); } i = 1; while (i <= 5) { System.out.println ("count : " + i); i++; } CFILT
Syntax of for loop for(initialisation; boolean expression; update) { Statements; . . . } Demo Repeatprint totalcount CFILT
more reading • Learn to prepare flowcharts: • http://www.nos.org/htm/basic2.htm • http://www.yale.edu/ynhti/curriculum/units/1981/6/81.06.03.x.html#d • Language(JAVA) basics: • http://java.sun.com/docs/books/tutorial/java/nutsandbolts/index.html CFILT
Problem See the file word.java • Run the code and try to find what it does and how it does that. CFILT