Programming with Java, part 2

記事
IT・テクノロジー

1.About stdin

Triangle.java I created yesterday could only calculate
the area of a triangle with a base of 6 and a height of 4.
Let's improve it so that we can calculate the area
regardless of the value of the base and height.
The improved program is as follows.

----------------------------- Triangle.java ------------------------------
import java.util.Scanner;

public class Triangle {
    public static void main(String[] args) throws Exception {
        System.out.println("How long is the bottom?");
        Scanner sc = new Scanner(System.in);
        int iBottom = sc.nextInt();           // Input the bottom.
        System.out.println("How long is the height?");
        int iHeight = sc.nextInt();            // Input the height.
        // Calculate the area of the triangle.
        int iArea = iBottom * iHeight / 2;
        System.out.println("Area = " + iArea);
    }
}
------------------------------------------------------------------------------

When you run this program, it first says
"How long is the bottom?". The next line is
"Scanner sc = new Scanner (System.in);", which is the
process of accepting standard input (usually keyboard input)
called System.in. The entered content is read as a numerical
value by the process of "int iBottom = sc.nextInt ();". In this
program, if a non-numeric value such as a character or symbol
is input, an error will occur, so the originally input value is
checked. I will explain it later, so I will omit the check this time.

Next is about "import java.util.Scanner;" on the first line.
I used a class called Scanner for standard input just now.
This is one of the utility classes provided by java. It is provided
in a package called "java.util", so you need to write one line
"import java.util.Scanner;" when you use it. By the way, if you
want to be able to use all the utility classes in the "java.util"
package, write "import java.util.*;". This one line is convenient.


2.About constructors and methods

The program below is a further improvement of Triangle.java.

-------------------------------- Main.java ------------------------------
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("How long is the bottom?");
        Scanner sc = new Scanner(System.in);
        int iBottom = sc.nextInt();           // Input the bottom.
        System.out.println("How long is the height?");
        int iHeight = sc.nextInt();            // Input the height.

        Triangle triangle = new Triangle(iBottom, iHeight);
        int iArea = triangle.getArea();
        System.out.println("Area = " + iArea);
    }
}
-----------------------------------------------------------------------------

----------------------------- Triangle.java ------------------------------
public class Triangle {
    // Member variables
    private int iBottom;
    private int iHeight;
    private int iArea;

    // Constructor
    public Triangle(int bottom, int height) {
        this.iBottom = bottom;
        this.iHeight = height;
        this.iArea = calculateArea(bottom, height);
    }

    // Calculate the area of the triangle.
    private int calculateArea(int bottom, int height) {
        return bottom * height / 2;
    }

    // getter
    public int getArea() {
        return this.iArea;
    }
}
------------------------------------------------------------------------------

I divided the file in two. The "main(String[] args)" part of the
Main.java file is called the method. Processing starts from
this method. The part marked void indicates that the method
returns no value. The line "Triangle triangle = new Triangle
(iBottom, iHeight);" is the part that has been improved this time.
If you new the Triangle class, you will have an object. I think
this explanation is difficult to understand, so I will paraphrase it.
It means "The blueprint of Triangle is written in Triangle.java,
so please embody it based on this." You can't use it just by
preparing Triangle.java, so you will be able to use it by
writing "new".

Next, the processing performed by this new is the
"public Triangle (int bottom, int height)" part of Triangle.java.
This is called a constructor. The constructor mainly initializes
variables used in the class. The constructor created this time
receives bottom and height as parameters. The member
variables declared in "private int iBottom;" and
"private int iHeight;" are initialized using these. A member variable
is the data that is retained in the object after the class is made
into an object by "new". Member variables are usually used with
"private". You can write "public int iBottom;", but it is not preferable
to make it public because anyone can rewrite the data.

And I also defined the calculateArea method with "private".
This method returns an int instead of void. The result of
calculating the area of the triangle will be returned as int type
data. It may not be necessary to make it a method because
the processing content is small, but it will be easier to understand
what processing is from the method name. Finally, there is the
"public int getArea()" part. If you want to access the data in
Triangle from outside the Triangle object, define the method
in public. This is called a getter. The getArea method can be
called like "int iArea = triangle.getArea();" in Main.java because
getArea method is defined in public. This allows the Main class
to get the area of the triangle.


Next time, I will try to calculate areas other than triangles.


[Japanese]

1.標準入力について

昨日作成したTriangle.javaは、底辺が6、高さが4の三角形の面積しか計算できませんでした。底辺や高さがどんな値であろうと面積を計算できるように、汎用的にしていきましょう。改良したものが下記のプログラムです。

----------------------------- Triangle.java ------------------------------
import java.util.Scanner;

public class Triangle {
    public static void main(String[] args) throws Exception {
        System.out.println("How long is the bottom?");
        Scanner sc = new Scanner(System.in);
        int iBottom = sc.nextInt();               // Input the bottom.
        System.out.println("How long is the height?");
        int iHeight = sc.nextInt();                // Input the height.
        // Calculate the area of the triangle.
        int iArea = iBottom * iHeight / 2;
        System.out.println("Area = " + iArea);
    }
}
------------------------------------------------------------------------------

このプログラムを実行すると、最初に「How long is the bottom?」と表示されます。次の行の「Scanner sc = new Scanner(System.in);」ですが、これは
System.inという標準入力(通常はキーボードからの入力)を受けつける処理です。入力した内容を「int iBottom = sc.nextInt(); 」の処理で数値として読み込みます。このプログラムでは、文字や記号など数値以外が入力されてしまうとエラーになってしまいますので、本来は入力された値のチェックを行います。それについては後日触れることにして、今回はチェックを省きます。

続いて1行目の「import java.util.Scanner;」についてです。先程、標準入力で
Scannerというクラスを利用しましたが、これはjavaが提供しているユーティリティクラスの1つです。「java.util」というパッケージに用意されていますので、利用するときには「import java.util.Scanner;」という1行を記述する必要があります。ちなみに、「java.util」パッケージのユーティリティクラスを全て利用できるようにしたい場合は、「import java.util.*;」と記述します。この1行で済むので便利です。


2.コンストラクタとメソッドについて

下記のプログラムは、Triangle.javaをさらに改良したものです。

-------------------------------- Main.java ------------------------------
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("How long is the bottom?");
        Scanner sc = new Scanner(System.in);
        int iBottom = sc.nextInt();                // Input the bottom.
        System.out.println("How long is the height?");
        int iHeight = sc.nextInt();                 // Input the height.

        Triangle triangle = new Triangle(iBottom, iHeight);
        int iArea = triangle.getArea();
        System.out.println("Area = " + iArea);
    }
}
-----------------------------------------------------------------------------

----------------------------- Triangle.java ------------------------------
public class Triangle {
    // Member variables
    private int iBottom;
    private int iHeight;
    private int iArea;

    // Constructor
    public Triangle(int bottom, int height) {
        this.iBottom = bottom;
        this.iHeight = height;
        this.iArea = calculateArea(bottom, height);
    }

    // Calculate the area of the triangle.
    private int calculateArea(int bottom, int height) {
        return bottom * height / 2;
    }

    // getter
    public int getArea() {
        return this.iArea;
    }
}
------------------------------------------------------------------------------

ファイルを2つに分けました。Main.javaファイルにある、
「main(String[] args)」の部分はメソッドといいます。ここから処理が始まります。voidと書いてある部分は、メソッドが何も値を返さないことを表します。「Triangle triangle = new Triangle(iBottom, iHeight);」の行は今回改良してできた部分です。Triangleクラスをnewすると、オブジェクトが出来上がります。この説明だと分かりにくいと思いますので、言い換えますと、
「Triangleの設計図はTriangle.javaに書いてあるので、これを基に具現化してください。」という意味です。Triangle.javaを用意しただけでは利用できないので、newすることで利用可能になります。

続いて、このnewによって行われる処理が、Triangle.javaの
「public Triangle(int bottom, int height) 」の部分です。これをコンストラクタといいます。コンストラクタは、主にクラス内で使われる変数の初期化などを行います。今回作成したコンストラクタは、パラメータでbottomとheightを受け取ります。これらを使って初期化しているのが、「private int iBottom;」と「private int iHeight;」で宣言したメンバ変数です。メンバ変数とは、newでクラスをオブジェクト化した後に、オブジェクト内で保持しておくデータのことです。メンバ変数は、通常はprivateで使います。「public int iBottom;」と書くこともできますが、publicにすると誰でもデータを書き変えてしまうことができるので、好ましくありません。

そして、calculateAreaメソッドもprivateで定義しました。このメソッドは戻り値をvoidではなくintにしています。三角形の面積を計算した結果を、int型のデータで返すことになります。処理内容が少ないのでメソッドにする必要は無いかもしれませんが、メソッド名から何をしているかが分かりやすくなるでしょう。最後に「public int getArea()」の部分です。Triangleオブジェクトの外部から、Triangle内のデータにアクセスさせたい場合に、publicでメソッドを定義します。これをgetterといいます。Main.javaの中で
「int iArea = triangle.getArea();」のようにgetAreaメソッドを呼び出せるのは、publicで定義したからです。これによって、Mainクラスは三角形の面積を取得することができるのです。


次回は三角形以外の面積も計算してみます。
サービス数40万件のスキルマーケット、あなたにぴったりのサービスを探す