2015年4月16日木曜日

入力された整数があらかじめ指定された整数の倍数かどうかを判定するjavaプログラム

Javaバイブルシリーズ Java入門 P140応用課題5.1.1

下記の例は3の倍数かどうかを判定するプログラム
------
import java.io.*;
public class MultipleOfX {
 public static void main(String[] args) throws IOException {
 
  BufferedReader br =
          new BufferedReader(new InputStreamReader(System.in));
  String buf;
 
  System.out.println("終了は[Enter]だけを入力");
  System.out.print("整数入力>");
  while (!(buf = br.readLine()) .equals("")) {
  
   int num = Integer.parseInt(buf);
   int x = 3;
  
   if(num % x == 0){
    System.out.println(num + "は" + x + "の倍数です");
   } else {
    System.out.println(num + "は" + x + "の倍数ではありません");
   }
       System.out.print("整数入力>");
      }
 }
}
------

実行結果
------
>java MultipleOfX
終了は[Enter]だけを入力
整数入力>3
3は3の倍数です
整数入力>4
4は3の倍数ではありません
整数入力>5
5は3の倍数ではありません
整数入力>
 -- Press any key to exit (Input "c" to continue) --
------

0 件のコメント:

コメントを投稿