LoginSignup
1
0

More than 3 years have passed since last update.

StringBufferの練習

Posted at

”う”と”み”を交互に繰り返す処理

メソッド1は繰り返し処理のところで毎回new StringBufferで文章が追加されるため
メソッド2に比べて処理時間がかかる。

StringBuffer.java
package javaStudy;

public class StringBufferExam {
    public static String answer = "";

    public static void main(String[] args) {
        System.out.println(method1(50));
        System.out.println(method2(50));        
    }

    public static String method1(int n) {
        for(int i = 0 ; i < n; i++) {
            answer += ((i%2==0)?"う":"み");   
        }
        return answer;
    }

    public static String method2(int n) {
        StringBuffer sb = new StringBuffer();
        for(int i = 0 ; i < n; i++) {
            sb.append(((i%2==0)?"う":"み"));  
        }
        answer = sb.toString();
        return answer;
    }
}
1
0
2

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
1
0