等差数列の合計を求めるプログラム

横へなの問題をプログラムにした

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


class ArithmeticalProgression{
	/**
	 * 人数
	 */
	private Integer num;

	/**
	 * 合計
	 */
	private Integer sum;

	/**
	 * 差額
	 */
	private Integer diff;

	/**
	 * 初項
	 */
	private Integer a;



	public Integer getNum() {

		return num;
	}


	public void setNum(Integer num) {
		this.num = num;
	}


	public Integer getSum() {
		return sum;
	}


	public void setSum(Integer sum) {
		this.sum = sum;
	}


	public Integer getDiff() {
		return diff;
	}


	public void setDiff(Integer diff) {
		this.diff = diff;
	}


	public Integer getA() {
		if( this.a == null){
			if( this.diff != null && this.num != null && this.sum != null ){
				a = calcA();
			}else{
				System.out.println("aを求めることはできません。");
			}
		}
		return a;
	}


	public void setA(Integer startVal) {
		this.a = startVal;
	}

	/**
	 * コンストラクタ
	 */
	public ArithmeticalProgression() {
	}


	/**
	 *
	 */
	public static  boolean isNumeric(String input){
		Pattern pattern = Pattern.compile("[^0-9]", Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(input);
		return !matcher.find();
	}

	/**
	 * 初項を求める
	 * @return
	 */
	public Integer calcA(){
		// a = { 2s - n( n - 1 )d } / 2n
		Integer a = ( ( 2 * this.sum ) - ( this.num * ( this.num - 1 ) * this.diff ) )  / ( 2 * this.num );
		return a;
	}
}


public class MathMain {

	public static boolean isNumeric(String input){
		Pattern pattern = Pattern.compile("[^0-9]", Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(input);
		return !matcher.find();
	}

	public static void displayInputError(){
		System.out.println("入力値が正しくないです。");
	}


	/**
	 * @param args
	 */
	public static void main(String[] args) {
		final String[] inputMessage = {"人数", "合計", "差額" };
		ArithmeticalProgression ap = new ArithmeticalProgression();
		String input = null;
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		try{
			for( int i = 0; i < inputMessage.length; ){

				//人数
				System.out.print( inputMessage[i] + ": ");
				input = br.readLine();
				if( isNumeric(input) ){
					switch(i){
					case 0:
						ap.setNum(Integer.parseInt(input));
						break;

					case 1:
						ap.setSum(Integer.parseInt(input));
						break;

					case 2:
						ap.setDiff(Integer.parseInt(input));
						break;

					}

					i++;
				}else{
					displayInputError();
				}
			}
		}catch( Exception e){
			e.printStackTrace();
		}

		for(int i = 0; i < ap.getNum(); i++){
			System.out.println(i + 1 + ": " + ( ap.getA() + ap.getDiff() * i ));
		}
	}
}

switch文が不愉快なので変更
変更点

  • メソッドの呼び出しを動的にする
  • 埋め込み型だったのでそれぞれ外だしオブジェクトにする
  • プロパティを全てint型に変更 (なぜか、Integer型だと実行エラーになる)

ArithmeticalProgression

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ArithmeticalProgression {
	/**
	 * 人数
	 */
	private int num;

	/**
	 * 合計
	 */
	private int sum;

	/**
	 * 差額
	 */
	private int diff;

	/**
	 * 初項
	 */
	private int a;

	public Integer getNum() {
		return num;
	}

	public void setNum(int num) {
		this.num = num;
	}

	public int getSum() {
		return sum;
	}

	public void setSum(int sum) {
		this.sum = sum;
	}

	public int getDiff() {
		return diff;
	}

	public void setDiff(int diff) {
		this.diff = diff;
	}


	public int getA() {
		this.a = updateA();
		return this.a;
	}

	public void setA(Integer startVal) {
		this.a = startVal;
	}

	/**
	 * コンストラクタ
	 */
	public ArithmeticalProgression() {
	}


	/**
	 *
	 */
	public static  boolean isNumeric(String input){
		Pattern pattern = Pattern.compile("[^0-9]", Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(input);
		return !matcher.find();
	}

	/**
	 * 初項を求める
	 * @return
	 */
	public Integer updateA(){
		// a = { 2s - n( n - 1 )d } / 2n
		Integer a = ( ( 2 * this.sum ) - ( this.num * ( this.num - 1 ) * this.diff ) )  / ( 2 * this.num );
		return a;
	}
}


ArithManager

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ArithManager {
	private final String[] inputMessage = {"人数", "合計", "差額" };
	private final String[] setFuncStr = {"setNum", "setSum", "setDiff" };
	private final String[] getFuncStr = {"getNum", "getSum", "getDiff" };
	private static final String className = "ArithmeticalProgression";
	private ArithmeticalProgression ap;
	private Method[] setFuncs;
	private Method[] getFuncs;

	public ArithManager(){
		this.ap = new ArithmeticalProgression();
		setFuncs = new Method[3];
		getFuncs = new Method[3];
		createFuncs();
	}

	@SuppressWarnings("unchecked")
	public void createFuncs(){
		try {
			Class[] type_null = new Class[0];
			Class[] type_int = new Class[1];
	        type_int[0] = Integer.TYPE;

			Class cls = Class.forName(className);
			for( int i = 0; i < setFuncStr.length; i++){
				setFuncs[i] = cls.getMethod(setFuncStr[i], type_int);
				getFuncs[i] = cls.getMethod(getFuncStr[i], type_null);
			}

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static boolean isNumeric(String input){
		Pattern pattern = Pattern.compile("[^0-9]", Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(input);
		return !matcher.find();
	}

	public static void displayInputError(){
		System.out.println("\n入力値が正しくないです。");
	}

	/**
	 * 出題
	 * @return
	 */
	public void  question(){
		String input = null;
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		try{
			for( int i = 0; i < inputMessage.length; ){
				//人数
				System.out.print( inputMessage[i] + ": ");
				input = br.readLine();
				if( isNumeric(input) ){
					this.setFuncs[i].invoke( this.ap, Integer.parseInt(input) );
					i++;
				}else{
					displayInputError();
				}
			}
		}catch(Exception e){
			if( br != null){
				try {
					br.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			e.printStackTrace();
		}
	}

	public void showAnswer(){
		for(int i = 0; i < ap.getNum(); i++){
			System.out.println(i + 1 + ": " + ( ap.getA() + ap.getDiff() * i ));
		}
	}

	public void funcsTest(){
		for( int i = 0; i < setFuncStr.length; i++){
			invokeTest(i, i * 10);
		}
	}

	@SuppressWarnings("unchecked")
	public void invokeTest(int i, int val){
		Class[] type_null = new Class[0];
		try {
			setFuncs[i].invoke(this.ap, new Integer(val));
			System.out.println(getFuncs[i].invoke(this.ap, type_null));
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}

}

クライアント

public class RefTest {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ArithManager arithMgr = new ArithManager();
		arithMgr.question();
		arithMgr.showAnswer();
	}
}

ソースが肥大化して、かえって分かりづらくなった・・・orz