教育サーバーのページ
オンラインテキスト目次
ソフトウエア入門演習

標準入出力を使う:解答例

課題

  1. System.out.print("How are you?\nI'm Fine");
  2. 100 + 20 は整数型データ(整数リテラル)と整数型データの加算なので120となる。 "100" + 20 は文字列データと整数値データなので文字列の連結となり、"10020" となる。 100 + "20" は整数値データと文字列データなので文字列の連結となり、"10020" となる。 10 + 100 + "20" は左結合のため、まず 10 + 100 の処理が行われる。これは110となる。 そして、110 + "20" の処理は文字列の連結となるので、"11020" となる。 "10" + 100 + 20 は左結合のため、まず "10" + 100 の処理が行われる。これは"10100" となる。 そして、"10100" + 20 の処理は文字列の連結となるので、"1010020" となる。
  3. System.out.println("100+20=" + (100 + 20)); に書きかえる。

  4. import java.io.*;
    public class InputTwoLines {
        public static void main(String[] args) throws IOException {
            String s1, s2;
            BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
            s1 = buf.readLine();
            s2 = buf.readLine();
            System.out.println(s1);
            System.out.println(s2);
        }
    }
    

  5. import java.io.*;
    public class InputTwoLines {
        public static void main(String[] args) throws IOException {
            String s;
            int a, b;
            BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
            s = buf.readLine();
            a = Integer.parseInt(s);
            s = buf.readLine();
            b = Integer.parseInt(s);
            System.out.println(a + b);
        }
    }
    
  6. Integer.parseInt()の代わりに、Long.parseLong() を使えばよい(もちろん変数はlong型とする)。 また確かめるには、int型では表現できないが、long型で表現できる数を入力してみると良い。

ソフトウエア入門演習
教育サーバーのページ
ohmi@rsch.tuis.ac.jp