0
0

More than 5 years have passed since last update.

JAVA 14.5練習問題(P558) trim()メソッド

Last updated at Posted at 2015-11-12

■練習問題14-1
独自に書式を指定して「2015年11月11日16時」の様な文字列を生成の面倒なやり方(処理が冗長)

■練習問題14-1 解答

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Test03 {
    public static void main(String[] args) {
        // ①現在の日時をDate型で取得する
        Date now = new Date();
        Calendar c = Calendar.getInstance();

        // ②取得した日時情報をCalendarにセットする
        c.setTime(now);

        // ③Calendarから「日」の数値を取得する
        int day = c.get(Calendar.DAY_OF_MONTH);

        // ④取得した値に100を足した値をCalendarの「日」にセットする
        day += 100;
        c.set(Calendar.DAY_OF_MONTH, day);

        // ⑤Calendarの日付情報をDate型に変換する
        Date now2 = c.getTime();

        // ⑥SimpleDateFormatを用いて、Dateインスタンスの内容を表示する
        SimpleDateFormat f = new SimpleDateFormat("西暦yyyy年MM月dd日");
        System.out.println(f.format(now2));
    }

}

練習問題14-1 解答 実行結果
西暦2016年02月20日

■練習問題14-2 解答

■Account.java

public class Account {
    String accountNumber; // 口座番号
    int balance; // 残高

    public String toString() {
        return "\\" + this.balance + "(口座番号=" + this.accountNumber + ")";
    }

}

■Test03.java

public class Test03 {
    public static void main(String[] args) {
        // P558 練習問題14.5
        // ①
        Account a = new Account();
        a.accountNumber = "4649";
        a.balance = 1592;
        System.out.println(a);
    }
}

■練習問題14-2 解答 実行結果
\1592(口座番号=4649)

■練習問題14-2 解答 補足
\は、なぜかQiitaでは¥が全角で表示されないので、
\は¥マークの半角と思って下さい。


■trim()メソッド
文字列の前後の空白を除去したいときは、Stringクラスのtrim()が使える

■例 trim()

String val = " 左側に半角スペース、右側に全角スペース  ";
        System.out.println("trimして出力⇒" + val.trim());
        System.out.println("trimしないで出力⇒" +val);

■実行結果
trimして出力⇒左側に半角スペース、右側に全角スペース  
trimしないで出力⇒ 左側に半角スペース、右側に全角スペース  

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0