Java - Indian Institute of Technology Bombay

Download Report

Transcript Java - Indian Institute of Technology Bombay

Java
ashishfa@cse
24th sep 2004
7/17/2015
CFILT
1
Today’s menu
• Input
– How to enter number, name to program
without changing the program code
• Loop constructs
– How to do task repetitively
7/17/2015
CFILT
2
input
• Want the program to print a number in
words.
– There is provision in java to give it to program
after running the program
Demo
Addup,
cmdar
g
– 2 ways
• One by passing argument
• One by interactive method(console)
7/17/2015
CFILT
3
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);
}
7/17/2015
CFILT
4
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));
}
7/17/2015
CFILT
5
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…
7/17/2015
CFILT
6
Simple loop - While
int i = 1;
Initialise a counter
is (i <=5) ?
while (i <= 5)
{
NO
YES
System.out.println ("count : " + i);
Print “count “ + i
i  I+1
i++;
}
7/17/2015
CFILT
7
Syntax of while loop
While (boolean expression)
{
Statementes;
.
.
.
}
7/17/2015
CFILT
Demo
whilerepea
t
Whilecoun
t
8
Other loop construct -for
i = 1;
while (i <= 5)
for (i = 1; i <= 5 ; i++)
{
System.out.println ("count : " + i);
i++;
{
System.out.println ("count : " + i);
}
}
7/17/2015
CFILT
9
Syntax of for loop
for (initialisation; boolean expression; update)
{
Statements;
.
.
.
}
Demo
Repeatpri
nt
totalcount
7/17/2015
CFILT
10
more reading
• Learn to prepare flowcharts:
– http://www.nos.org/htm/basic2.htm
– http://www.yale.edu/ynhti/curriculum/units/1981/6/81.0
6.03.x.html#d
• Language(JAVA) basics:
– http://java.sun.com/docs/books/tutorial/java/nutsandb
olts/index.html
7/17/2015
CFILT
11
Problem
See the file
word.java
• Run the code and try to find what it does
and how it does that.
7/17/2015
CFILT
12