Java2024/src/chapter5/demo51/OrderID.java

48 lines
1.4 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package chapter5.demo51;
public class OrderID {
public static void main(String[] args) {
System.out.println("====String实现====");
int[] time = {2024, 1107, 1040};
String orderID = arrayToString(time);
System.out.println("订单号 " + orderID);
System.out.println("\n====StringBuffer实现====");
int[] time2 = {2023, 1006, 1200};
String orderID2 = arrayToString(time2);
System.out.println("订单号 " + orderID2);
}
/**
* 将数组拼接成字符串,并在首尾添加`OID:[]`
* 注意使用String实现
* @param arr 存放数字的数组
* @return 拼接后的字符串,格式为`[202411071040]`
*/
public static String arrayToString(int[] arr) {
String s = "";
s += "OID:[";
for (int c : arr) {
s += c;
}
s += ']';
return s;
}
/**
* 将数组拼接成字符串,并在首尾添加`OID:[]`
* 注使用StringBuffer实现
* @param arr 存放数字的数组
* @return 拼接后的字符串,格式为`[202411071040]`
*/
public static String arrayToStringUsingBuffer(int[] arr) {
StringBuffer sb = new StringBuffer();
sb.append("OID:[");
for (int c : arr) {
sb.append(c);
}
sb.append("]");
return sb.toString();
}
}