Java Lecture 4
The Args.length thing
- If your parameter to 'main' is Args, then Args.length is an integer
value that is the number of arguments that your program was started with
- So, if your program is started like 'java lab6d 34 6.5 hello',
Args.length will be 3 (the three arguments are 34, 6.5,
and hello)
- You can use this directly in an if statement, like 'if (Args.length
== 1) ...'
If and relational expressions
- p95 (sec 3.5) has a list of them
- Like ML, except equality test is == and not equals
is !=
- Later we will see the logical operators
- p183, sec 5.2
- AND (ML andalso) is &&
- OR (ML orelse) is ||
- NOT (ML not) is !
- && and || act like ML ones, the second side is only evaluated
if it has to be
Block statements and single statements
- A block of statements is a list of statements surrounded by curly braces
- A block can occur anywhere a single statement can occur
- This can lead to subtle bugs, like having a semicolon after an if expression
Examples writing Java programs
- A min3 function
The while loop
- Exact same structure as the if statement, with the word 'while'
- Except, it repeats, instead of just doing the statement(s) once like
an if
- As with recursion, the condition must be getting "smaller"
or closer to false as you go
Keyboard Input
- Have to have the "import java.io.*;" statement
at the top of your program
- Have to have the words "throws IOException"
after main(String args[]) and before the opening curly
brace
- Have to have the line
BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in));
- Have to declare a String variable like "String
line;"
- Now, can do
line = stdin.readLine();
- This will read a line of keyboard input into the String variable
line
- Do it again to read the next line, and so on
- Input is in Strings; if you need numbers, have to convert it
Examples 1 and 2;
and sample runs.