Java 创建字符串格式的数字对象数组
Java create object array of numbers in string format
我正在为程序编写一个函数,我需要在 Object[]
中生成一个数字列表
例如
Object[] possibilities = functionName(13);
应该生成
Object[] possibilities = {"1", "2", "3","4","5","6","7","8","9","10","11","12","13"};
我应该如何实现这一目标?
试试这个方法。
private Object[] function(int size) {
Object[] result = new String[size];
for (int i = 0; i < size; i++) {
result[i] = Integer.toString(i + 1);
}
return result;
}
}
String functionName(int number){
StringBuilder str = new StringBuilder("{");
for(int i = 1; i <= number; i++){
str.append(Integer.toString(i)).append(", ");}
String string = str.toString().trim();
string = string.substring(0, str.length()-1);
string += "}";
return string;
}
这应该会为您提供所需的字符串,您只需打印它即可。
首先,您需要一种方法来 print
来自 functionName
的结果(即设定目标 post)。像,
public static void main(String[] args) {
Object[] possibilities = functionName(13);
System.out.println(Arrays.toString(possibilities));
}
然后你可以用一个基本的for
循环来实现functionName
,比如
static Object[] functionName(int c) {
Object[] ret = new String[c];
for (int i = 0; i < c; i++) {
StringBuilder sb = new StringBuilder();
sb.append("\"").append(i + 1).append("\"");
ret[i] = sb.toString();
}
return ret;
}
当我 运行 以上时,我得到(请求的)
["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13"]
我正在为程序编写一个函数,我需要在 Object[]
例如
Object[] possibilities = functionName(13);
应该生成
Object[] possibilities = {"1", "2", "3","4","5","6","7","8","9","10","11","12","13"};
我应该如何实现这一目标?
试试这个方法。
private Object[] function(int size) {
Object[] result = new String[size];
for (int i = 0; i < size; i++) {
result[i] = Integer.toString(i + 1);
}
return result;
}
}
String functionName(int number){
StringBuilder str = new StringBuilder("{");
for(int i = 1; i <= number; i++){
str.append(Integer.toString(i)).append(", ");}
String string = str.toString().trim();
string = string.substring(0, str.length()-1);
string += "}";
return string;
}
这应该会为您提供所需的字符串,您只需打印它即可。
首先,您需要一种方法来 print
来自 functionName
的结果(即设定目标 post)。像,
public static void main(String[] args) {
Object[] possibilities = functionName(13);
System.out.println(Arrays.toString(possibilities));
}
然后你可以用一个基本的for
循环来实现functionName
,比如
static Object[] functionName(int c) {
Object[] ret = new String[c];
for (int i = 0; i < c; i++) {
StringBuilder sb = new StringBuilder();
sb.append("\"").append(i + 1).append("\"");
ret[i] = sb.toString();
}
return ret;
}
当我 运行 以上时,我得到(请求的)
["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13"]