実験課題4
Exercise 4(課題4) See the section 1.7.1. "About Iteration". Then create the calculator program by creating the project chapter1kadai4. The term "calculator" here is that show the calculating result by inputting from keyboard such as + 10 2. In the input string separated by space, first term shows the operations: +(addition), -(subtraction), *(multiplication), /(division), and e(termination of the calculator). Second and third terms are operands. The calculator should use infinity loop. To get each term value from input string, should use split method in String class.
(1.7.1.節をよく読み、プロジェクト名chapter1kadai4のJavaアプリケーションプロジェクトを作成して、電卓を作成しなさい。そしてソースコードと実行結果を示すこと。ここで電卓とは記号 整数 整数として半角スペースで区切られた文字列がキーボードから入力され、それに対して計算結果を出力するプログラムである。例えばキーボードから+ 10 2のように入力された際には、12を返却する。この電卓は記号として+、-、*、/、eを受け付ける。受け付けられた記号ごとに、加算、減算、乗算、割り算を実行する。このプログラムは無限ループで処理が構成され、記号としてeが与えられた際には、無限ループを終了する。)
ここで、文字列から記号や数字などを個別に取得するためには、区切り文字で文字列を分割するStringクラスのsplitメソッドを使う。以下にsplitメソッドの利用例を示す。
String str = "あ い う え お"; // 変数strに文字列型オブジェクト"あ い う え お"を代入する。
String[] chars = str.split(" "); // 変数strの文字列を元に半角スペース" "にて区切った複数の文字列型オブジェクトを配列として変換する。
System.out.println("2番目の文字を表示: " + chars[1]);
また、文字列の比較をする際には、Stringクラスのequalsメソッドを使う。以下にequalsメソッドの利用例を示す。
String str = "あ";
if ("い".equals(str)) { // strの文字列オブジェクトと文字列オブジェクト"い"を比較する。
System.out.println("いです。");
} else if ("あ".equals(str)) { // strの文字列オブジェクトと文字列オブジェクト"あ"を比較する。
System.out.println("あです。");
)