在开发程序的时候,经常使用StringBuffer类来进行字符串的拼接。
如果在循环中来反复的做字符串拼接时,会清空stringbuffer中的内容,然后再拼接新的字符串信息。
例如:
stringbuffer sb ;
for (userinfo ui : userinfolist) {
sb = new stringbuffer("");
sb.append("姓名:");
sb.append(ui.getname());
sb.append(" ");
sb.append("年龄:");
sb.append(ui.getage());
system.out.println(sb.tostring());
}
以下为《JAVA语言程序设计》 进阶版 27章 编程题2 本人编写的作业,涉及到以上用法。
1 package Graph_27; 2 3 import java.io.*; 4 5 6 public class Exercise27_2 { 7 public Exercise27_2() { 8 9 } 10 11 public static void main(String[] args) throws Exception { 12 String[] vertices = {"Seattle", "San Francisco", "Los Angeles", 13 "Denver", "Kansas City", "Chicago", "Boston", "New York", 14 "Atlanta", "Miami", "Dallas", "Houston"}; 15 16 int[][] edges = { 17 {0, 1}, {0, 3}, {0, 5}, 18 {1, 0}, {1, 2}, {1, 3}, 19 {2, 1}, {2, 3}, {2, 4}, {2, 10}, 20 {3, 0}, {3, 1}, {3, 2}, {3, 4}, {3, 5}, 21 {4, 2}, {4, 3}, {4, 5}, {4, 7}, {4, 8}, {4, 10}, 22 {5, 0}, {5, 3}, {5, 4}, {5, 6}, {5, 7}, 23 {6, 5}, {6, 7}, 24 {7, 4}, {7, 5}, {7, 6}, {7, 8}, 25 {8, 4}, {8, 7}, {8, 9}, {8, 10}, {8, 11}, 26 {9, 8}, {9, 11}, 27 {10, 2}, {10, 4}, {10, 8}, {10, 11}, 28 {11, 8}, {11, 9}, {11, 10} 29 }; 30 31 Graph<String> graph = new UnweightedGraph<String>(edges, vertices); 32 33 File file = new File("Graph.txt"); 34 if(!file.exists()) { 35 PrintWriter date = new PrintWriter(file); 36 int numberOfVertices = graph.getVertices().size(); 37 date.println(numberOfVertices); 38 StringBuffer s; 39 for(int i = 0; i < numberOfVertices; i++) { 40 s = new StringBuffer(); 41 s.append(i + " "); 42 for(int j = 0; j < graph.getNeighbors(i).size(); j++) { 43 s.append(graph.getNeighbors(i).get(j) + " "); 44 } 45 date.println(s); 46 } 47 date.close(); 48 } 49 else 50 System.out.println("file is existed"); 51 } 52 }