Salta al contenuto
Note per Studenti Java - Classes, Objects and Scanner Report

Java - Classes, Objects and Scanner

In questa pagina 8

Continues Java - Language BasicsJava (Sun Microsystems, 1991) is an object-oriented language designed to be simple and CPU-independent ("write once, run anywhere"). Every program is made of classes; an executable class needs a main method, and the public class name must match the file name (Hello.java). The source is compiled by javac into bytecode (Hello.class), the machine code of the Java Virtual Machine, which the Java interpreter (java Hello) runs, translating on the fly into real CPU instructions; so Java is both compiled and interpreted, portable at source and bytecode level and of intermediate efficiency. Errors are syntax (found by the compiler) or logical (found only by testing). The grammar has five token types (keywords, identifiers, literals, separators, operators). Complements: loop end tests with less-than, sentinel values and the loop and a half, break and continue, the conditional operator and switch.Java - Language Basics → (first program, compilation, grammar, loops, switch). Here: how a class is written, documented and used through the exercise of a point in the plane, how arguments are passed, how objects are compared, and how Scanner splits text into tokens and reads data. For the idea of functions and methods compare Python - Control Flow, Lists, Functions and FilesA program makes decisions with if, elif and else, whose blocks are defined by the colon and by four-space indentation (an IndentationError otherwise). It repeats statements with while loops (condition, counter, update; infinite loops and sentinel loops) and for loops over range or over a sequence. A list is an ordered mutable container with zero-based indices, len, append, insert, pop, remove, the in operator, slicing, and sorted versus sort. Functions are defined with def, take parameters, return values with return (print is not return; no return gives None), have local variables, must be defined before being called and can live in separate modules imported with import. Text files are opened with the with statement in modes r, w or a with utf-8 encoding and read as strings.Python - Control Flow, Lists, Functions and Files →.

1. Documenting the public interface: javadoc

There is a standard format for documentation comments; if used, the javadoc program automatically generates documentation in HTML.

  • A documentation comment starts with /** and ends with */.
  • One must be written to describe the purpose of each non-private method.
  • Tags inside the comment: @param followed by the name of the argument and its short description; @return followed by a short description of the return value.
  • A short comment can also be written for the class: @author followed by the author's name, @version followed by a version number or a date.
java
/**
   deposits the specified amount of money into this bank account
   @param amount the specified amount of money
*/
public void deposit(double amount)

/**
   withdraws the specified amount of money from this bank account
   @param amount the specified amount of money
*/
public void withdraw(double amount)

Documentation is generated from the command line by giving the file name:

javadoc ClassName.java

which prints messages such as Loading source file ..., Constructing Javadoc information..., Generating index-all.html... and produces a set of HTML files.

2. Exercise: a point in the Cartesian plane (MyPoint2D)

Task. Write the MyPoint2D class representing a point of the plane with two coordinates, with:

  • the distance of two points (a real number): ∣PQ∣=(x−xq)2+(y−yq)2|PQ| = \sqrt{(x - x_q)^2 + (y - y_q)^2};
  • the midpoint of two points (a new point): M=(x+xq2,y+yq2)M = \left(\frac{x + x_q}{2}, \frac{y + y_q}{2}\right);
  • the textual description of the object;
  • a boolean method (a method returning a boolean) telling whether two points coincide: x=xqx = x_q and, at the same time, y=yqy = y_q.

2.1 Method signatures and the implicit argument

java
public double getDistanceFrom(MyPoint2D q) {...}
public MyPoint2D getMidpoint(MyPoint2D q) {...}
public boolean isCoincident(MyPoint2D q) {...}

Used as:

java
MyPoint2D p1 = new MyPoint2D(...);
MyPoint2D p2 = new MyPoint2D(...);
double d = p1.getDistanceFrom(p2);
MyPoint2D m = p1.getMidpoint(p2);
if (p1.isCoincident(p2)) {...}
  • p1 is the implicit argument (the object on which the method is invoked); p2 is the explicit argument (written in the round brackets). The explicit argument here is of reference data type (MyPoint2D).
  • The return type can be a primitive (double), a reference type (MyPoint2D, a new point) or boolean.

2.2 The class

java
/**
 * MyPoint2D
 * represents a point in the Cartesian plane
 */
public class MyPoint2D
{  //instance variables
   private double x;  // x coordinate
   private double y;  // y coordinate

   /**
      Initializes a new point with the specified coordinates
      @param aX x the specified x coordinate
      @param aY y the specified y coordinate
   */
   public MyPoint2D(double aX, double aY)
   {  x = aX;
      y = aY;
   }

   /**
      Computes the distance between this point and the specified point
      @param q the specified point
      @return distance between points
   */
   public double getDistanceFrom(MyPoint2D q)
   {
      double d2 = (x - q.x)*(x - q.x) + (y - q.y)*(y - q.y);

      return Math.sqrt(d2);
   }

   /**
      Computes the midpoint between this point and the specified point
      @param q the specified point
      @return midpoint
   */
   public MyPoint2D getMidpoint(MyPoint2D q)
   {
      double xm = (x + q.x) / 2;
      double ym = (y + q.y) / 2;
      MyPoint2D tmp = new MyPoint2D(xm, ym);
      return tmp;
   }

   /**
      Textual description with format MyPoint2D: x, y
      @return textual description
   */
   public String toString()
   {
      return "MyPoint2D: " + x + ", " + y;
   }

   /**
      Checks if this point and the specified point coincide
      @param q the specified point
      @return true if the points coincide, false otherwise
   */
   public boolean isCoincident(MyPoint2D q)
   {
      return approxEquals(x, q.x) && approxEquals(y, q.y);
   }

   private boolean approxEquals(double a, double b)
   {
      final double EPSILON = 1E-14;
      return Math.abs(a - b) <= EPSILON
            * Math.max(Math.abs(a), Math.abs(b));
   }
} // end of class

Points to remember:

  • Instance variables x and y are private: each object has its own copy. Inside the class the coordinates of another object of the same class are reached as q.x, q.y.
  • The constructor has the same name as the class, no return type, and initialises the instance variables (x = aX; y = aY;). Objects are created with new MyPoint2D(x1, y1).
  • getMidpoint builds and returns a new object: the original points are not modified.
  • toString() returns the textual description in the format MyPoint2D: x, y, built by concatenating strings and numbers with +.
  • isCoincident does not compare the coordinates with ==: floating point numbers are compared with a tolerance by the private helper approxEquals (a final constant EPSILON = 1E-14 multiplied by the larger of the two absolute values). A private method is not part of the public interface, so it does not need a documentation comment.

2.3 The test class

The task also asks for a test class that reads two points from the standard input, computes distance and midpoint and prints them, and requires identifying test cases.

Test cases on the slide: P(1,0)P(1,0), Q(0,1)Q(0,1), R(3,0)R(3,0), S(0,4)S(0,4) with

  • PQ‾=2\overline{PQ} = \sqrt{2} and midpoint MPQ=(12,12)M_{PQ} = \left(\frac{1}{2}, \frac{1}{2}\right);
  • RS‾=5\overline{RS} = 5 and midpoint MRS=(32,2)M_{RS} = \left(\frac{3}{2}, 2\right).
java
/**
 * MyPoint2DTester
 * test class of class MyPoint2D
 */
import java.util.Scanner;
import java.util.Locale;
public class MyPoint2DTester
{  public static void main(String[] args)
   {  Scanner in = new Scanner(System.in);  // opens the input data stream
      in.useLocale(Locale.US);

      System.out.print("Enter x1 e y1 ");
      double x1 = in.nextDouble();
      double y1 = in.nextDouble();
      System.out.print("Enter x2 e y2 ");
      double x2 = in.nextDouble();
      double y2 = in.nextDouble();

      in.close();                             // closes the input data stream

      MyPoint2D p = new MyPoint2D(x1, y1);    // creates new point p
      MyPoint2D r = new MyPoint2D(x2, y2);    // creates new point r

      System.out.println("Distance of point " + p + " from point " + r
                         + " is " + p.getDistanceFrom(r));

      System.out.println("Midpoint of point " + p + " and point " + r
                         + " is " + p.getMidpoint(r));
   }
}
  • import java.util.Scanner; makes the class available; new Scanner(System.in) opens the standard input; in.close() closes it.
  • in.useLocale(Locale.US) sets the locale to the US one for the input; nextDouble() reads the next token as a double.

3. Argument passing

Arguments in Java are always passed by value: when a method is invoked, a copy of each argument, whether it is a value or a reference, is passed to the method.

java
// method that uses MyPoint2D class
MyPoint2D p1 = new MyPoint2D(1,2);
MyPoint2D p2 = new MyPoint2D(2,3);

double d = p1.getDistanceFrom(p2);      // p2: actual argument

// class MyPoint2D - method getDistanceFrom
public double getDistanceFrom(MyPoint2D q)   // q: formal argument
  • The argument in the call is the actual argument; the parameter in the method header is the formal argument.
  • Access to instance variables inside non-static methods: the reference variable p1 is copied into the implicit argument this, and the actual argument p2 is copied into the formal argument q. Then x means this.x and y means this.y, while q.x and q.y are the coordinates of the other point.
  • Since references are copied, q and p2 refer to the same object.

4. Comparison of objects

How comparison is done depends on the type:

  • integers: relational operators, if (n == 0 || n > 5);
  • floating point numbers: with tolerance,
java
final double EPSILON = 1E-14;
if (Math.abs(x - y) <=
    EPSILON * Math.max(Math.abs(x), Math.abs(y)))
  • strings: with the methods equals, equalsIgnoreCase and compareTo, for example if (s1.equals(s2)).

4.1 == compares references

Using == on two object references checks whether the references point to the same object.

java
String s1 = "MyString";
String s2 = s1;
String s3 = "MyStrin";
s3 = s3 + "g"; // s3 contains "MyString"
  • s1 == s2 is true: both point to the same object.
  • s1 == s3 is false: they point to different objects, even if both objects have the same content ("identical"). (Slide diagram: s1 and s2 point to one String object, s3 to another one with the same text.)

4.2 equals() compares the content

s1.equals(s3) is true: they point to two identical String objects.

  • To check whether a reference is null use the equality operator, not equals(): if (s == null).
  • equals() can be applied to any object because it is defined in the Object class, from which all classes derive. But each class must redefine equals() (as String does): otherwise the equals() of Object simply uses the equality operator. The equals() of a class must compare the characteristics (instance variables) of its objects.
  • For now equals() is used only for objects of standard library classes; objects of classes defined by us are not compared unless the method equals is defined in the class itself.

5. Decomposing a string into tokens with Scanner

A token is a substring with well-defined syntactic characteristics, for example delimited by spaces: in "one two three" the tokens are "one", "two", "three". Decomposing strings into tokens is a common problem. The Scanner class of the java.util package (already used to read the standard input) is very useful for it.

  • By default Scanner considers as delimiters spaces, tab characters, "carriage return" and "line feed": these and other characters are called whitespaces and are recognised by the boolean method Character.isWhitespace(char c).
  • Create a Scanner by passing the string to the constructor:
java
String line = "one two three";
Scanner st = new Scanner(line);
  • The number of tokens is generally not known in advance. Successive calls of next() return successive tokens. next() throws java.util.NoSuchElementException if there are no more tokens:
java
String token1 = st.next(); // "one"
String token2 = st.next(); // "two"
String token3 = st.next(); // "three"
String token4 = st.next(); // java.util.NoSuchElementException
  • So before calling next() check with the boolean method hasNext(), true if a subsequent token not yet extracted is present. It is ideal when the number of tokens is unknown:
java
while (st.hasNext())
{
   String token = st.next();
   ...// now process token
}

Trace on "one two three": the first hasNext() finds "one" and returns true, next() acquires it; then "two", then "three"; the next hasNext() finds no token left and returns false, so the loop ends. The original string remains unchanged.

  • Similar boolean methods exist for each fundamental type: hasNextInt(), hasNextDouble(), hasNextLong(), ... and hasNextLine(), useful for reading lines and used when the row structure of the data must be preserved.

6. Reading a sequence from the standard input

With an unknown number of data a sentinel value can be used (see Java - Language BasicsJava (Sun Microsystems, 1991) is an object-oriented language designed to be simple and CPU-independent ("write once, run anywhere"). Every program is made of classes; an executable class needs a main method, and the public class name must match the file name (Hello.java). The source is compiled by javac into bytecode (Hello.class), the machine code of the Java Virtual Machine, which the Java interpreter (java Hello) runs, translating on the fly into real CPU instructions; so Java is both compiled and interpreted, portable at source and bytecode level and of intermediate efficiency. Errors are syntax (found by the compiler) or logical (found only by testing). The grammar has five token types (keywords, identifiers, literals, separators, operators). Complements: loop end tests with less-than, sentinel values and the loop and a half, break and continue, the conditional operator and switch.Java - Language Basics →); the string "Q" below ends the sequence:

java
Scanner in = new Scanner(System.in);
int sum = 0;
boolean done = false;
while (!done)
{  String line = in.nextLine();
   if (line.equalsIgnoreCase("Q"))
      done = true;
   else
      sum += Integer.parseInt(line);
}

The same hasNext() loop works on System.in:

java
while (st.hasNext())
{
   String token = st.next();
   // now we can process token
}
  • Here hasNext() stops the execution and waits for data entry from the standard input. The data is acquired by the program when the operator presses the Enter key; for example typing one two three and Enter delivers the string "one two three" to the standard input, then hasNext() acts on it as in the string decomposition above.
  • At the end of data entry, the operating system is notified that the standard input for the running program is finished with a special key combination:
    • DOS/Windows window: ctrl + z followed by return;
    • Unix shell: ctrl + d. When these are typed, hasNext(), whose execution was interrupted waiting for data, returns false and the reading loop ends.

Example: counting words

java
import java.util.Scanner;
public class WordCounter
{
  public static void main(String[] args)
  {
      Scanner c = new Scanner(System.in);
      int count = 0;
      while (c.hasNext())
      {
          c.next();  // extracts the token!
          count++;
      }

      System.out.println(count + " words");
      c.close();
   }
}

c.next() must be called inside the loop, otherwise hasNext() would always find the same token and never return false.

7. Exercise: complex numbers (MyComplex)

Java has neither a primitive data type nor a ready-to-use class in the platform API for complex numbers. The task is to write the MyComplex class implementing:

  • addition, subtraction, product, division;
  • real and imaginary parts, modulus, complex conjugate, reciprocal (1/z1/z);
  • a textual description in the format "a + ib".

The slides give the signature of the sum as a method with implicit argument z1 and explicit argument z2, returning a new object:

java
/**
   sums this complex number with the specified one
   @param z the specified complex number
   @return sum of the complex numbers
*/
public MyComplex add(MyComplex z) {...}

// if z1 and z2 are references to instances of the MyComplex class
MyComplex z3 = z1.add(z2);

The same pattern (the method returns a new object, the operands are unchanged) applies to the other operations, as with getMidpoint in MyPoint2D.

8. Exam checklist

  • Instance variables private; constructor named as the class; new creates objects; reference variables hold references.
  • In p1.method(p2): p1 is the implicit argument (this inside the method), p2 the explicit one; actual argument in the call, formal argument in the header.
  • Arguments are always passed by value: a copy of the value or of the reference.
  • == on references tests identity (same object), equals() tests content; test null with ==; equals() must be redefined in the class, otherwise it behaves like ==.
  • Floating point comparison: absolute difference below EPSILON times the larger absolute value, never ==.
  • javadoc: /** ... */ with @param, @return (and @author, @version for the class); javadoc ClassName.java makes HTML.
  • Scanner on strings and on System.in: hasNext() before next(); NoSuchElementException otherwise; end of standard input with ctrl+z and return (Windows) or ctrl+d (Unix); hasNextInt, hasNextDouble, hasNextLine.

Versione ripasso

javadoc: a /** ... */ comment before each non-private method, with @param (name and description) and @return; the class may have @author and @version. javadoc ClassName.java generates HTML.

MyPoint2D exercise

  • Private instance variables x and y; the constructor has the class name and no return type.
  • getDistanceFrom(q) returns a double: (x−xq)2+(y−yq)2\sqrt{(x-x_q)^2 + (y-y_q)^2}.
  • getMidpoint(q) returns a new object; the original points are unchanged.
  • toString() returns MyPoint2D: x, y.
  • isCoincident(q) never uses == on doubles: the private approxEquals checks the difference against EPSILON = 1E-14 times the larger absolute value.
  • Test class: reads x1 y1 x2 y2 with Scanner, prints distance and midpoint. Test cases: P(1,0), Q(0,1) gives 2\sqrt{2} and midpoint (1/2,1/2)(1/2, 1/2); R(3,0), S(0,4) gives 5 and midpoint (3/2,2)(3/2, 2).

Arguments

  • In p1.getDistanceFrom(p2), p1 is the implicit argument (this) and p2 the explicit one (q). Inside the method x means this.x, while q.x is the other point's coordinate.
  • Arguments are always passed by value: the method receives a copy of the value or of the reference. Actual argument in the call, formal argument in the header.
  • Return types can be primitive, reference or boolean.

Comparing

  • Integers: relational operators. Floating point: with tolerance. Strings: equals, equalsIgnoreCase, compareTo.
  • == on references tests whether they point to the same object: s1 == s3 is false even with equal content.
  • equals() compares content. It is defined in Object, but each class must redefine it, otherwise it behaves like ==.
  • Test for null with ==: if (s == null).

Scanner on a string

  • Default delimiters are whitespace, recognised by Character.isWhitespace.
  • next() returns successive tokens and throws NoSuchElementException when none are left; call hasNext() first. hasNextInt, hasNextDouble, hasNextLine exist too. The original string is unchanged.

Scanner on System.in

  • hasNext() waits for input; data arrives when Enter is pressed.
  • End of input: ctrl+z then return (Windows), ctrl+d (Unix). Then hasNext() returns false.
  • Counting words: next() must be called inside the loop, or hasNext() keeps finding the same token.

MyComplex exercise: Java has no complex type in its API. Implement add, subtract, product, division, real and imaginary parts, modulus, conjugate, reciprocal, and toString in the form "a + ib". Operations return new objects, as getMidpoint does.

Common mistakes: comparing strings or doubles with ==; forgetting to redefine equals(); expecting arguments to be passed by reference; calling next() without hasNext(); forgetting that hasNext() needs a next() inside the loop.

Teoria collegata