はじめに
今回変更した部分としては、力技で書いていたものをクラス化、メソッド化してすっきりさせる、というものです。
#1-1では、全てをtestクラスで記述していましたが、今回Storyクラスを作成しました。
また、ファイルの内容を格納するのに、普通の配列を使っていたところを、ArrayListというものを使うようにしました。これは、配列宣言時に要素数を指定せずに使えて、中身を入れるたびに自動で要素数を増やしてくれる優れもののようです。
使い方はこちらのサイトを参考にさせていただきました。
改良コード
test.java
import java.io.*;
import java.util.ArrayList;
class Story
{
String fileName;
ArrayList <String> story = new ArrayList<>();
public void readFile(String fn) throws IOException
{
fileName = fn;
BufferedReader br = new BufferedReader(new FileReader(fileName));
String str1;
while((str1 = br.readLine()) != null)
{
story.add(str1);
}
}
public void showText() //全部出力
{
for(int i=0; i<story.size(); i++)
{
System.out.println(story.get(i));
}
}
public void showText(int s) //要素番号sから最後まで
{
for(int i=s; i<story.size(); i++)
{
System.out.println(story.get(i));
}
}
public void showText(int s, int g) //要素番号sからgまで
{
if(g<story.size())
{
for(int i=s; i<=g; i++)
{
System.out.println(story.get(i));
}
}
else
{
System.out.println("2つ目の引数が要素数を超えています");
}
}
}
class test
{
public static void main(String[] args) throws IOException
{
Story story1 = new Story();
story1.readFile("test1.txt");
story1.showText(0,5);
BufferedReader ibr = new BufferedReader(new InputStreamReader(System.in));
String option = ibr.readLine();
int option1 = Integer.parseInt(option);
if(option1 == 1)
{
story1.showText(6, 7);
}
else if(option1 == 2)
{
story1.showText(8,9);
}
else
{
System.out.println("無効な選択肢です");
}
System.out.println("おしまい");
}
}
実行結果は#1-1と全く同じです。
クラスやオーバーロードを使ったことで、mainの中がかなりすっきりしました。
選択肢分岐のところももう少しきれいになりそうですが、今回はいったんこれでおしまい。