複数結果の受け渡し

  Java にアドレスを参照する方法がありませんので,変数 res に対して配列を使用しています.以下に示すプログラムにおいては,要素数が 1 である配列を定義し,除算の結果だけを配列に入れて返していますが,要素数 2 の配列を定義し,ind の値もその中に入れて返すことも可能です.その際は,関数 sub は.void 型の関数になります.

  なお,このプログラムでは,throws というキーワードを使用していますが,その意味については後ほど説明します.内容的には,今までのように,try と catch を用いた場合と同じです.
/****************************/
/* 複数結果の受け渡し       */
/*      coded by Y.Suganuma */
/****************************/
import java.io.*;

public class Test {

	static int n;    // 以下の関数にすべて有効

	public static void main(String args[]) throws IOException
	{
		int a, b, ind;
		int res[] = new int [1];
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
	/*
		 データの入力
	*/
		System.out.print("aの値は? ");
		a = Integer.parseInt(in.readLine());
		System.out.print("bの値は? ");
		b = Integer.parseInt(in.readLine());
		System.out.print("nの値は? ");
		n = Integer.parseInt(in.readLine());
	/*
		 関数の呼び出し
	*/
		ind = sub(a, b, res);   // 変数resは配列で渡す
	/*
		 結果の出力
	*/
		if (ind == 0)
			System.out.println("n " + n + " result " + res[0]);
		else
			System.out.println("n < 0 (n " + n + ")");
	}

	/*****************************/
	/* (a+b)/nの計算             */
	/*      a,b : データ         */
	/*      res : 計算結果       */
	/*      return : =0 : normal */
	/*               =1 : n < 0  */
	/*****************************/
	static int sub(int a, int b, int res[])
	{
		int ind;
	
		if (n == 0) {
			ind = 1;
			n   = 100;
		}
		else {
			ind    = 0;
			res[0] = (a + b) / n;
		}
	
		return ind;
	}
}
		

戻る