Download 1 What we know

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
1 What we know
We have previously seen examples of input from the console window.
This example contains several aspects of using classes and objects
import java.util.*;
public class KeyboardReading
{
public static void main(String [] arg)
{
Scanner keyb = new Scanner(System.in);
System.out.println("How many dollar coins?");
int nDollars;
nDollars = keyb.nextInt();
System.out.println("So you have "+nDollars+" coins.");
}
}
Firstly we define our own class, Line 3, namned KeyboardReading containing (a member in
KeyboardReading) a static method main(…). main defines our entry point, by convention.
We use the class Scanner on line 7. Line 7 can be rewritten as
Scanner keyb;
keyb = new Scanner(System.in);
The rewrite is made to illustrate the point that the creation of a Scanner object requires two steps. Step
1: the declaration of a Scanner reference, an identifier to reference a particular object. This
declaration alone doesn’t make any features of Scanner available at all, it only provides us with a
name. The statement keyb = new Scanner( System.in) is required to create the scanner object. The
new operator initiates the creation and the assignment is required for us to later be able to use the
scanner object. A new operator hence evaluates as a reference to the type created.
(Scanner)=(Scanner). The constructor itself does not return anything (not even void).
nDollars = keyb.nextInt();
Object construction:
new Scanner(System.in)
Call a method:
keyb.nextInt()
We are taking advantage of a static member(not belonging to an object) on line 8. Line 8 can
be rewritten as
PrintWriter myPrinter = System.out;
myPrinter.println("How many dollar coins?");
The first declaration and assignment (initialization) provides us with an identifier that is
identical to the class member System.out. The difference between this scenario and the
previous scenario (keyb = new Scanner(… )) is that the System.out member have already
been created. The creation of this member happens when the java runtime starts. Step 2 is a
method call in exactly the same way as keyb.nextInt().
1.1 Important parts of a class
A class consists of members. A member can be a constructor, an attribute (value) or a method. A
member can also be static or non-static. A static member belongs to the class, while a non-static
member belongs to an object; the default being non-static, or instance member.
The previous example is a typical way to instantiate a class to create an object, and then at a
later stage use, or call, the objects methods to perform certain operations.
- Construction: new Scanner()
- Method call keyb.nextInt()
- Static member/ class member, System.out
The forms of the different operations are as follows:
Construction:
o = new ClassName( argument list );
o is required to be declared with the correct type. o is referencing an object, or instance. o is
often described as “the object o”. (Formally the declaration of o, needs to be of class
ClassName or a superclass of o as defined by inheritance)
E.g. Scanner myKeyboardObject = new Scanner();
Here the argument list is the empty list.
Method call:
object.method( argument list)
E.g. myKeyboardObject.nextInt()
A method always has a return type.
nextInt() is evaluated as a value of int type, which makes the following a natural statement:
int nDollars = keyb.nextInt();
Static members
ClassName.memberName
E.g.
System.out
Member name is out.
A brief discussion about the member public static void main
When the java runtime starts our java program there is no instance of our class, (no object of
type KeyboardReading. Because there are no instance available we need to have made an
agreement on what constitutes the entry point of out application. The agreement being a call
similar to
KeyboardReader.main( argument list );
This is the reason for the static keyword in the main declaration. KeyboardReader.main(…)
is a call to a static member.
1.2 Javadocs
The java API reference is organized by classes, each class give its own page. There are
besides the class pages also a summary and description of all packages.
The starting index page is shown below:
We can identify the division of packages, and a list of all classes in the standard edition. This
is a very long list.
If the class name is known, as is usually the case, you can search for that class by bringing
focus to the class list, and pressing Ctrl+f (find IE/firefox/Opera). We try searching for
Scanner (match whole word only, is a good option).
Click the hyperlink for the scanner class.
All classes are documented in this way:
- Class name and its inheritance (treated later).
- A fairly detailed description illustrating special cases as well as typical examples.
- Summary of attributes; this is linked as FIELDS
- Summary of constructors; linked as CONSTR
- Summary of methods; linked as METHOD
- Detailed information about attributes, constructors and methods.
The Scanner class contains no public attributes, hence the FIELDS link is inactive, and the
first summary section being the constructor summary.
We have previously used constructor number 3. Scanner(InputStream source) because of the
fact that System.in is of type InputStream. Later on in the method summary section we find
the nextInt() method call.
Our no argument method call to nextInt() is method number three in the list. The number four
version makes it possible to specify the number base of the conversion. To convert e.g.
hexadecimal number one could use
// read a hexadecimal value typed on the console
int hexValue = keyb.nextInt( 16 );
The user can now input a hex value, like FF, the integer hexValue then represents the value
255. (Or FF if you think in base 16).
The detail link for method nextInt(int ) provides additional details.
1.2.1 Other important classes
-String
-Math
Example: Calculate the number of characters given as input:
import java.util.*;
public class StringLength {
public static void main(String[] args) {
Scanner keyb = new Scanner(System.in);
System.out.println("Your given name:");
String input = keyb.next();
// A String member is length():int
int inputLength = input.length();
System.out.println("Your name contains "+inputLength+
" characters");
}
}
A major part in solving any typical problem is finding the right class for the problem, and
then applying the correct methods, to an object of that class.
Example: How far can you throw a ball
Formula
x = 2*v*v*cos(a)*sin(a)/g
Where x is the length of the throw, v is the initial velocity (throwing strength), a – initial
throwing angle, g is the gravitational acceleration constant 9.81m/s².
import java.util.*;
public class ThrowLength {
public static void main(String[] args) {
final double g = 9.81; // final, makes this a constant
Scanner keyb = new Scanner(System.in);
// inputs
System.out.println("How fast can you throw? (m/s)");
double speed = keyb.nextDouble();
System.out.println("At what angle? (0-90 degrees)");
double angle = keyb.nextDouble();
angle *= Math.PI/180.0; // degrees needs conversion to radians
// for sin and cos
// result
double length = 2*speed*speed*Math.cos(angle)*Math.sin(angle)/g;
System.out.println("Your throw is "+length+" meters.");
}
}
Find the different methods in the java api specification used in the two examples.
The difference between the String class and the Math class is the String class represents an
object, whereas the Math class represents a collection of methods and fields (constants). The
state of the String object is its text. Math is not represented by a state. Hence the Math
methods are static, belonging to the class; while the String methods belong to the object. A
Math object cannot be created.
String object = "Hello";
object.member
double myPi = Math.PI;
Class.member