我如何添加一個passStringBuilder()方法來創建一個和passString()一樣工作的新方法?我需要使用StringBuilder對象而不是String對象。問候。用StringBuilder替換字符串?
import intertech.MyDate;
public class PassByExperiment {
public static void main(String[] args) {
MyDate date = new MyDate(1, 20, 2008);
System.out.println("Before passing an object " + date);
passObject(date);
System.out.println("After passing an object " + date);
System.out.println("Before passing a primitive " +
date.year);
passPrimitive(date.year);
System.out.println("After passing a primitive " +
date.year);
String x = date.toString();
System.out.println("Before passing a String " + x);
passString(x);
System.out.println("After passing a String " + x);
}
public static void passObject(MyDate d) {
d.year = 2009;
}
public static void passPrimitive(int i) {
i = 2010;
}
public static void passString(String s)
{
int yearSlash = s.lastIndexOf('/');
s = s.substring(0, yearSlash + 1);
s += "2012";
System.out.println("New date string: " + s);
}
}
這是我的嘗試:
public static void passStringBuilder(StringBuilder sb) {
int yearSlashSB = sb.lastIndexOf('/');
sb = sb.substring(0, yearSlashSB + 1);
sb.append("2012");
System.out.println("New date string: " + sb);
}
第一*格式*代碼正確 – Lino
檢查'StringBuilder'的Javadoc。你會發現稱爲'lastIndexOf','delete'和'append'的方法可以使用。 –
我試過但沒有,如果有人有我的例子將是完美的...順便說一句,這是我的第一個帖子抱歉的第一個格式的代碼。 –