Download System.out.println() - Department of Computer Science and

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
SOFTWARE AND PROGRAMMING 1
Advert: NO TEST1 on 7/02: TEST1 will be 14/02
Lab: SH131, BBK536
6:00-7:30 (from 24.01.07)
[each student must have obtained access to Birkbeck computing, and
those whose surnames start with A-L, to SCSIS computing too]
Lecture: Gor B4
7:40-9:00 (from 24.01.07)
Lab SH131: students whose family names (surnames) begin A-L
Instructor:
Ms Marie-Helene Ng
SCSIS, room NG26, tel. 020 7631 6725
E-mail: [email protected]
Lab BBK536 : students whose family names (surnames) begin M-Y
Instructor:
Prof. Boris Mirkin
Webpages
The course web page
webct.bbk.ac.uk
is used for announcements and
assignments. Those who have
problems with accessing the course
module should contact Marie-Helene
([email protected]).
An open-to-all web-site with lecture
notes, schedule and files:
www.dcs.bbk.ac.uk/~mirkin/sp105
2
Test1 14/2/7 awareness
Open-book in-class Test1 14/2/7 subjects:
• Variable: type, declaration, initialisation
• Expression
• Loop for
• Loop while
• if( )… else if( ) ... else
• Method
3
Contents
•
•
•
•
•
Leftovers (conditional operator)
Ticket Machine
Method; Accessor, Mutator
Double loop
Input data from keyboard: TextIO,
Scanner
4
Precedence table
5
Conditional operator
• Used for assigning a value depending on a
condition:
A= Condition ? ResultIfTrue :ResultIfFalse
Example:
int b=2; int c= 7;
int A=(b < c) ? b : c; %put min(b,c) into A
How this can be done with if/else:
int b=2; int c= 7;
int A;
if (b<c) {A=b;}
else {A=c;}
6
Ticket Machine (1)
/* * TicketMachine models a ticket machine that issues
* flat-fare tickets. */
public class TicketMachine{
private int price;
private int balance;
private int total;
public TicketMachine(int ticketCost) //constructor
{ price = ticketCost;
balance = 0;
total = 0; }
public int getPrice()
{
return price; }
public int getBalance()
{ return balance; }
// see next page for continuation
7
Ticket Machine (2)
// TicketMachine’s continuation
public void insertMoney(int amount)
{
if(amount > 0)
balance = balance + amount;
else {
System.out.println("Use a positive amount: " +
amount);
}
}
public int refundBalance()
{ int amountToRefund;
amountToRefund = balance;
balance = 0;
return amountToRefund;
}
// continued on the next page
8
Ticket Machine (3)
// TicketMachine’s end
public void printTicket()
{
if(balance >= price) {
// Simulate the printing of a ticket.
System.out.println("##################");
System.out.println("# The BlueJ Line");
System.out.println("# Ticket");
System.out.println("# " + price + " pence.");
System.out.println("##################");
System.out.println();
total = total + price; // Update the total
balance = balance - price; // Update the balance
}
else { System.out.println("You must insert at least: " +
(price - balance) + " more pence."); }
}
}//end of class
9
A comment
I consider printTicket()method as
somewhat inconsistent:
printing (an accessing activity) is mixed
up with
changing the balance and total (mutating
activities)
Any suggestions?
10
Questions
• How many methods are in TicketMachine? five
• If there is any syntactic difference between
a method and constructor? – two: absence
of the output type, compulsory name
• Which of the methods are accessors and
which are mutators? Two in the beginning are accessors, three in
the end are mutators
11
Accessor methods
• Accessors provide information about the state
of an object.
• Methods have a structure consisting of a
header and a body.
• The header defines the method’s signature.
public int getPrice()
• The body encloses the method’s statements.
12
Accessor methods
return type
visibility modifier
method name
parameter list
(empty)
public int getPrice()
{
return price;
return statement
}
start and end of method body (block)
13
Mutator methods
• Have a similar method structure: header
and body.
• Used to mutate (i.e. change) an object’s
state.
• Achieved through changing the value of
one or more fields.
– Typically contain assignment statements.
– Typically receive parameters.
14
Mutator methods
visibility modifier return type (void)
method name
parameter
public void insertMoney(int amount)
{
balance = balance + amount;
}
field being changed
assignment statement
15
Printing method
public void printTicket()
{
// Simulate the printing of a ticket.
System.out.println("##################");
System.out.println("# The BlueJ Line");
System.out.println("# Ticket");
System.out.println("# " + price + " cents.");
System.out.println("##################");
System.out.println();
// Update the total collected with the balance.
total = total + balance;
// Clear the balance.
balance = 0;
}
16
Passing data via parameters
17
Double loop (1)
class AddTable {
public static void main(String[ ] args){
int sum;
for (int ite1=1;ite1<3; ite1++) {//loop1
for (int ite2=1;ite2<5; ite2++) {//loop2
sum=ite1+ite2;
System.out.print(sum +" ");}//loop2
System.out.println();}//loop1
} //method main ends
} //class ends
18
Double loop (2)
This prints
2 3 4 5
3 4 5 6
Why?
A better printing ? Such as:
Addition Table
+1 2 3 4
12 3 4 5
23 4 5 6
19
Double loop (3)
class AddTable {
public static void main (String[] args)
{int sum;
for (int i1=1;i1<3; i1++){
System.out.print(i1 + " ! ");
for (int i2=1;i2<5; i2++){
sum=i1+i2;
System.out.print(sum +" ");}
System.out.println();}
}
}
20
Double loop (4): with method
class AddTableMeth {
public static void main (String[] args)
{ PrintTable(2,4); }\\end main
public static PrinTable(int rowsize, int
columnsize){
for (int i1=1;i1<rowsize+1; i1++){
System.out.print(i1 + " ! ");
for (int i2=1;i2<columnsize+1; i2++){
sum=i1+i2;
System.out.print(sum +" ");}
System.out.println();}
}
}\\end class
21
Double loop (5)
produces
1! 2 3 4 5
2! 3 4 5 6
3! 4 5 6 7
Q: How to make it look better? (See
printing method in TicketMachine.)
Q: How to modify it to other ranges?
Q: Make a MULTIPLICATION TABLE?
22
Input/Output TextIO class
TextIO.java, added to the directory that
contains your class, eases input of data
from the keyboard
To input an integer:
int UsInput = TextIO.getInt();
Computer will wait for the user to type in
an integer value to UsInput.
23
Input/Output TextIO class (2)
public class PrintSquare {
public static void main(String[] args) {
int uInput;
// the number to be input by the user
int Squared;
// the userInput, multiplied by itself
System.out.print("Please type a number: ");
uInput = TextIO.getInt();
Squared = uInputuInput; //why product?
System.out.print("The square is "+Squared);
} // end of main()
} //end of class PrintSquare
24
Input/Output TextIO class (3)
Other TextIO methods:
b = TextIO.getByte(); // value read is a byte
i = TextIO.getShort(); // value read is a short
j = TextIO.getInt(); // value read is an int
k = TextIO.getLong(); // value read is a long
x = TextIO.getFloat(); // value read is a float
y = TextIO.getDouble(); // value read is a double
a = TextIO.getBoolean(); // value read is a
boolean
c = TextIO.getChar(); // value read is a char
w = TextIO.getWord(); // value read is a String
s = TextIO.getln(); // value read is a String 25
Input/Output in Java
The TextIO class contains static member
methods TextIO.put() and TextIO.putln(),
the same as System.out.print() and
System.out.println().
TextIO can only be used in a program if
TextIO is available to that program. It is
not built into Java.
From Java 1.5.0 version on, there is a
similar class in Systems.in:
Scanner
26
Input with Scanner class(1)
From Java 1.5.0 version on, there is a
similar class in System.in.
Scanner(System.in):
- import the java.util package in a line
preceding the class,
- then declare an instance of Scanner and
- then use it for prompting the user to
enter data (of a specified data type,
preferably int or double) from keyboard
27
Input with Scanner class (2)
import java.util.*
class PrintDot{
int num=0;
public static void main(String[ ] args){
Scanner scap = new Scanner(System.in);
System.out.println(“How many dots to print? “);
num=scap.nextInt();
for (int ik=0; ik<num; ik++)
System.out.print(‘.’);
System.out.println();
} \\end of main
} \\end of class
28
Using method with Scanner
import java.util.*
class PrintDot{
int number=0;
public static void main(String[ ] args){
Scanner scap = new Scanner(System.in);
System.out.println(“How many ampersands to print? “);
number=scap.nextInt();
ppp(number);
} \\end of main
void ppp(nnn)
{ for (ik=0; ik<nnn; ik++)
System.out.print(‘&’);
System.out.println();
} \\end of ppp
} \\end of class
29