scanner logic box
Download
Report
Transcript scanner logic box
CSC 211 Java I
Tools for implementing a
game: Rock, Paper, Scissors
The usual drill
Go to COL and download the Material For Lab 5
zip file from the Documents or Assignments
Unzip
it
Rename it YourLastName_L5
Open CSC211_L5 and L5
Open Classroom presenter
Please remember to remove the files from the
computer AND PLUG IT IN when you return it to
the cart
Today’s plan
Assignment Q/A
Midterm
Looping review
Increment and decrement operators
Tools for implementing Rock, Paper, Scissors
Writing JEnglish
Logical operators
Fancy input/output
Loop practice
Today’s plan
Assignment Q/A
Midterm
Looping review
Increment and decrement operators
Tools for implementing Rock, Paper, Scissors
Writing JEnglish
Logical operators
Fancy input/output
Loop practice
Midterm
The midterm is Monday, May 4th, 1:30-4:45.
Location TBA, but most likely in this room – I will
e-mail you.
You must work alone
There are two parts:
Pen/pencil
and paper questions
Computer-based questions
You can bring 2 sheets (single-sided) of notes
A midterm study guide has been posted
Today’s plan
Assignment Q/A
Midterm
Looping review
Increment and decrement operators
Tools for implementing Rock, Paper, Scissors
Writing JEnglish
Logical operators
Fancy input/output
Loop practice
Logic of a while loop
condition
evaluated
true
statement
7
false
Features of the while loop
Note that if the condition of a while loop is
false initially, the body of the loop is never
executed
i.e.
The body of a loop executes 0 or more
times
Notice that you do NOT have to know in
advance how many times you will execute
the loop
Are you with me?
What is wrong with this loop? Trace it and write an explanation
import java.util.Scanner;
public class LoopExample1
{
public static void main(String [] args)
{
int sum = 0;
int count = 1;
Scanner numScan = new Scanner(System.in);
System.out.print("Enter the largest number to print: ");
int high = numScan.nextInt();
while (count <= high)
{
System.out.println(count);
}
}
}
Let me out of here!
10
The body of the loop MUST contain one or more
statements that affect the loop condition, making
it eventually false
Otherwise we enter an infinite loop
The machine will go on forever….
The needed statement in our example is an
increment of the variable count
count = count + 1;
Today’s plan
Assignment Q/A
Midterm
Looping review
Increment and decrement operators
Tools for implementing Rock, Paper, Scissors
Writing JEnglish
Logical operators
Fancy input/output
Loop practice
A couple of random but very
important reminders:
Textpad or BlueJ?
If you are working with a project with multiple
files, use BlueJ
If you are using a single java class (most of
the time in 211), Textpad is probably much
better.
A class to practice with:
This class (or something like it) should be open EVERY time you are
learning / practicing Java…
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
//do your learning / practicing here...
input.close();
} //end method main()
} //end class
The right (and wiser) way to
program
1.
2.
3.
Algorithm
JEnglish
Code
Period.
Example – section 5 of asst #5:
1.
Algorithm
1.
2.
3.
2.
JEnglish
1.
2.
3.
4.
3.
Display menu of choices (# runs, total mileage, length,
etc, quit)
If user quits, end program
If user doesn’t quit, display menu and repeat
SOP( menu)
while (user does not enter quit) { display menu }
SOP(any final info if necessary)
End program
Code
1.
Probably a good idea to begin by taking sections from
JEnglish and writing them in as comments to delineate
sections of your code.
Note: Any parts of these steps can and should be revised as you go through!!!!!!
Increment and Decrement
Operators
Java allows us to write the statement
count = count + 1;
in a compact form as follows
count++;
The ++ is called the increment operator
The increment operator ++ adds one to its
operand
17
Increment and Decrement
Operators
There is a corresponding decrement
operator --
The decrement operator -- subtracts one
from its operand
18
Increment and Decrement
Operators
The increment and decrement operators can be applied
in postfix form (i.e. after the variable, as in count++) or
in prefix form (i.e. before the variable as in ++count )
Postfix form is preferred. Stick with it.
When used ALONE in a statement, the prefix and postfix
forms are equivalent. That is,
count++;
is equivalent to
++count;
19
Increment and Decrement
Operators
When used in a larger expression, for
example in assignment statement as in
total = count++;
total = ++count;
the prefix and postfix forms have a
different effect
20
Increment and Decrement
Operators
21
In both cases the variable is incremented
(decremented) but AFTER (count++) or
BEFORE (++count) the assignment
statement
Increment and Decrement
Operators
If count currently contains 45, then
total = count++;
assigns 45 to total and 46 to count
FIRST do the assignment
THEN do the increment
22
Increment and Decrement
Operators
If count currently contains 45, then
total = ++count;
assigns the value 46 to both total and
count
FIRST do the increment
THEN do the assignment
23
Assignment Operators
Often we perform an operation then store
the result back into that variable
Java provides more special operators,
besides ++ and -- that are a combination
of arithmetic AND assignment
24
Assignment Operators
For example, the statement
count += 2;
is equivalent to
count = count + 2;
25
Assignment Operators
There are many assignment operators,
including the following:
Operator
+=
-=
*=
/=
%=
26
Example
Equivalent To
x
x
x
x
x
x
x
x
x
x
+=
-=
*=
/=
%=
y
y
y
y
y
=
=
=
=
=
x
x
x
x
x
+
*
/
%
y
y
y
y
y
Are you with me?
Ink the value of x and y after each line of
code
x | y
int x = 5, y = 10;
x = --y;
___|___
x %= y;
___|___
Today’s plan
Assignment Q/A
Midterm
Looping review
Increment and decrement operators
Tools for implementing Rock, Paper, Scissors
Writing JEnglish
Logical operators
Fancy input/output
Loop practice
Rock, Paper, Scissors
Go to the lab materials and open the
project RPS
Read
the code and understand it
Run the program several times
Now we want to fill in the missing pieces
Before
coding, what do we do?
Yes, JEnglish (only for the inside of the while loop)
Go to CSC211_Lab5 and work on Part 1.1
Machine generates a random number
between 1 and 3.
1 = Paper stored as a char ‘P’
2 = Rock stored as a char ‘R’
3 = Scissors stored as a char ‘S’
Ask user to enter “P” or “R” or “S”
Keep asking as long as the user has not
entered one of the above (e.g. if user
enters ‘w’)
Need a while loop and a compound condition
While input is not equal P and not equal R and not
equal S
If machine weapon is the same as the
user weapon
Print
“it’s a tie”
Otherwise
If
one of the following conditions is true the
machine wins:
Machine: P and User: R
Machine: R and User: S
Machine: S and User: P
Else
the user wins
Ask the user if she wants to play again
Today’s plan
Assignment Q/A
Midterm
Looping review
Increment and decrement operators
Tools for implementing Rock, Paper, Scissors
Writing JEnglish
Logical operators
Fancy input/output
Loop practice
Logical AND and logical OR
The logical AND a && b is true if and only if
both a and b are true, false otherwise
The logical OR a || b is true as long as one
of the two is true.
a
b
a&&b
a||b
T
T
T
T
T
F
F
T
F
T
F
T
F
F
F
F
&& and ||
Takes 2 boolean values
Return a boolean value
Are you with me?
Ink whether the following conditions are T or F
char x = ‘p’ ; char y = ‘P’; int z = 3; int q = ++z;
A. x == y && z == q
T
F
B. x == y || z == q
T
F
C. q > 4 && x != y
T
F
D. z < 2 || q>1 || x != y
T
F
Short circuiting
The two operands of && and || are
evaluated in order (left to right)
If the first operand for && is false, the
second is never evaluated
If the first operand for || is true, the
second is never evaluated
This can be very tricky if your operands
change state – Be careful!
Exercise
It is time to start coding the RPS game
Do Parts 1.2 and 1.3 of Lab 5
For
Part 1.2, hard code the machine’s choice
(no randomness) and ask the user to enter a
choice of weapons
For Part 1.3, validate the user’s choice of
weapon, repeatedly re-prompting in the case
of invalid input
String answer;
char machine, player;
while (answer.toLowerCase().charAt(0) == 'y' ||
answer.toLowerCase().equals("yes"))
{
machine = 'P'; //Hard-Coded the machine’s weapon
System.out.println("I have picked my weapon “ +
"\n now pick yours P,R,S");
player = console.next().toUpperCase().charAt(0);
System.out.println("Player choice: "+ player);
while (player != 'R' && player !='P' && player !='S')
{
System.out.println("You entered an invalid character.
Please try again (P, R, or S):");
player = console.next().toUpperCase().charAt(0);
}
System.out.println(“Would you like to play again ?
(yes/no): ");
answer = console.next();
}
Exercise
Work more on the RPS game
Do Parts 1.4 (and time permitting, 1.5) of
Lab 5
For
Part 1.4 add code that reports the
outcome of the round
Program’s choice of weapon still fixed for ease of
testing
(Challenge)
rounds
For Part 1.5 keep statistics for all
Today’s plan
Assignment Q/A
Midterm
Looping review
Increment and decrement operators
Tools for implementing Rock, Paper, Scissors
Writing JEnglish
Logical operators
Fancy input/output
Loop practice
Fancier input/ouput
So far we have done input/output using
the terminal window,
System.out.print() and Scanner
Today we’ll look at graphical input/output
using the JOptionPane class
JOptionPane
JOptionPane is a predefined graphic
class. (API http://java.sun.com/javase/6/docs/api/ )
It allows you to use dialog windows
It has a series of method for graphic
input and output.
It is part of set of classes grouped in the
Swing library (package)
i.e.
import javax.swing.JOptionPane;
Packages
The classes of the Java standard class library
are organized into packages
Package
Purpose
java.lang
General support
java.applet Creating applets for the WEB
java.awt
Graphics and GUI
javax.swing Additional graphics capabilities
java.net
Network communications
java.util
Utilities
Packages
import javax.swing.*;
The classes of the Java standard class library
are organized into packages
Package
Purpose
java.lang
General support
java.applet Creating applets for the WEB
java.awt
Graphics and GUI
javax.swing Additional graphics capabilities
java.net
Network communications
java.util
Utilities
I/O (input/output) with
JOptionPane
The primary methods we will use for input
and output are
showMessageDialog used for output,
equivalent to print, displays a String in a dialog
box
I/O with JOptionPane
The primary methods we will use for input
and output are
showMessageDialog() used for output,
equivalent to the print methods we’ve been
using, displays a String in a dialog box
showInputDialog() used for input, equivalent
to .next() from the Scanner class, collects
data from the user in the form of Strings in a
dialog box, allows you to also display a String
JOptionPane output
String to be shown
import javax.swing.*;
JOptionPane.showMessageDialog (null, “Hello”);
Class name
(swing package)
Class Output method
(JOptionPane class)
System.exit(0);
Component containing the output:
null is the default window frame
The dialog window disappears when we click ok, but
the program is still managing the window.
Use the exit method of the System class to stop it.
The number 0 means normal termination
Only do so at the very end of your program
JOptionPane input
import javax.swing.*;
Variable declaration (inputs are Strings)
String fName;
fName =JOptionPane.showInputDialog(“Type in your name”);
Save the input in a
variable (String)
Input method of the
JOPtionPane class
System.exit(0);
//don’t forget this line!
Message displayed in the
dialog window
Exercise – “fancify” I/O
Do Part 2.1 of Lab 5
From Strings to Numbers
Input from a dialog window is always a string.
What if you are trying to read in a number???
There are certain classes that have methods to
convert strings to numbers.
These
methods will only work if the strings contain
numbers (and only numbers!)
String to Integer
Integer.parseInt(variable_name);
String to Double
Double.parseDouble(variable_name);
Exercise – “fancify” I/O
Do Part 2.2 of Lab 5
Today’s plan
Assignment Q/A
Midterm
Looping review
Increment and decrement operators
Tools for implementing Rock, Paper, Scissors
Writing JEnglish
Logical operators
Fancy input/output
Loop practice
Are you with me? – Loop practice
I will post one simple problem on the
screen
You ink/type a quick solution
Ignore
the headers
Give just variable declarations and control
structures (while loop header and body)
52
When you think you’ve got it, submit it
Are you with me?
53
Print all odd numbers from 1 to 1001 in decreasing order
(1001, 999, 997,…)
Are you with me?
54
Assume you have gotten a String uData filled with
information from the user. Print all its characters in
reverse order.
Ex: uData is Amber, your code should print rebmA
You can’t assume what is in the String; Also, don’t
overwrite what is in the String
Are you with me?
Write code that print to the console window the following
picture:
*
**
***
****
*****
55
Cleaning up
Upload your lab document to COL
Remove all files from the computer
Return the computer to the cart AND
PLUG IT IN
Thanks!