一般クラスを作成し、そのインスタンスの入った配列を作ってみよう。
この記事の対象者
Javaでオブジェクト指向を学び始めた人。
お題
(一般クラス)ColorPencilクラスと(アプリケーションクラス)ColorPencilAppクラスを作成し、以下の処理を作成せよ
[実行例] 何本作成しますか>>3 1本目の色>>赤 1本目の長さ>>5 2本目の色>>青 2本目の長さ>>2 3本目の色>>黄 3本目の長さ>>6 --操作を入力-- 0.赤----> 1.青--> 2.黄------> 3.終了 >>1 赤で書いた! --操作を入力-- 0.赤---> 1.青--> 2.黄------> 3.終了 >>1 青で書いた! --操作を入力-- 0.赤---> 1.青-> 2.黄------> 3.終了 >>1 青で書いた! --操作を入力-- 0.赤---> 1.青> 2.黄------> 3.終了 >>1 青はもうかけません! --操作を入力-- 0.赤---> 1.青> 2.黄------> 3.終了 >>3 アプリケーションを終了します
作成の手順
ColorPencilクラスの作成
//インスタンスフィールド String Color;//色 int len;//長さ //引数二個のコンストラクタ //インスタンスメソッド void write() //書くメソッド 長さが0の場合はもうかけません表示 そうでなければ、**で書いた!と出力して、長さを1減らす void showInfo() //現在の状態を表示するメソッド 長さが5の場合は 赤-----> のように表示する。
public class ColorPencil{
String color;
int len;
ColorPencil(String color,int len){
this.color=color;
this.len=len;
}
void write(){
if(this.len<=0){
System.out.printf("%sはもう書けません!%n",this.color);
return;
}
System.out.printf("%sで書いた!%n",this.color);
this.len--;
}
void showInfo(){
System.out.print(this.color);
for(int i=0;i<this.len;i++){
System.out.print("-");
}
System.out.println(">");
}
}
ColorPencilAppクラスの作成
//Scannerインスタンスを作成 //何本作成するか聞く //本数を変数nに代入 //ColorPencil型の配列を本数nをもとに作成 //forループを回しながら質問を行いColorPencilインスタンスを作成し、配列にいれていく //無限ループ //操作リストを出力し、番号を変数selectに代入 //変数selectが終了を意味する番号だったらスキャナーを閉じてreturn //そうでなければその色鉛筆でwriteメソッドを実行する
import java.util.*;
public class ColorPencilApp{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
System.out.print("何本作成しますか>>");
int n=sc.nextInt();
ColorPencil[] cps= new ColorPencil[n];
for(int i=0;i<cps.length;i++){
System.out.printf("%d本目の色>>",i+1);
String color=sc.next();
System.out.printf("%d本目の長さ>>",i+1);
int len=sc.nextInt();
cps[i]=new ColorPencil(color,len);
}
while(true){
System.out.println("--操作を入力--");
for(int i=0;i<=cps.length;i++){
System.out.printf("%d.",i);
if(i==cps.length){
System.out.println("終了");
}else{
cps[i].showInfo();
}
}
System.out.print(">>");
int select=sc.nextInt();
if(select >= cps.length){
System.out.println("アプリケーションを終了します");
sc.close();
return;
}
cps[select].write();
}
}
}
コメント