好,所以更像是有一种简单的方法输出到
[6, 8, 9, 10]
[1002]
empty array []
Bad input
Bad input
Bad input
Bad input
如果是这样的话?
这更像是挑剔那些最不礼貌的事情,在我开始做某些事情之前,要使输出变得“更细”会花费很多时间
所以我只想简单地知道它是否可以以简单的方式完成,如果是这样的话。
public class String2intArray {
public static void main(String[] args) {
System.out.println(Arrays.toString(str2ia("6,8 ,9 , 10")));
System.out.println(Arrays.toString(str2ia("1002")));
System.out.println(Arrays.toString(str2ia("")));
System.out.println(Arrays.toString(str2ia(", 2")));
System.out.println(Arrays.toString(str2ia("Ett,Två")));
System.out.println(Arrays.toString((str2ia("1,,2"))));
System.out.println(Arrays.toString(str2ia("1 , 2 ,")));
}
public static int[] str2ia(String s) {
int arraylengt = 0;
int arrayindex = 0;
s = s.replaceAll("\\s", "");
Scanner scan = new Scanner(s).useDelimiter(",");
if(s.length() == 0) {
int[] emptyArray = {};
System.out.print("empty array ");
return emptyArray;
}
try {
if(!s.matches("(\\d+,)*\\d+")){
throw new IllegalArgumentException("Bad input");
}
} catch (IllegalArgumentException e) {
System.out.print("Bad input");
int[] emptyArray = {};
return emptyArray;
}
while (scan.hasNext()) {
if (scan.hasNextInt()) {
int nextInt = scan.nextInt();
arraylengt ++;
} else {
// discard next token
scan.next();
}
}
int[] intArray = new int[arraylengt];
Scanner scan2 = new Scanner(s).useDelimiter(",");
try {
while (scan2.hasNext()) {
if (scan2.hasNextInt()) {
intArray[arrayindex] = scan2.nextInt();
arrayindex++;
} else {
// discard next token
throw new IllegalArgumentException("Bad input");
}
}
} catch (IllegalArgumentException e) {
System.out.print("Bad input");
int[] emptyArray = {};
return emptyArray;
}
return intArray;
}
}
答案 0 :(得分:0)
这是通过对现有代码进行 2次更改来获得所需输出的一种方法:
首先:替换以下代码:
$request->query->get('date'); // GET
$request->request->get('date'); // POST
-with-
System.out.println(Arrays.toString(str2ia("6,8 ,9 , 10")));
System.out.println(Arrays.toString(str2ia("1002")));
System.out.println(Arrays.toString(str2ia("")));
System.out.println(Arrays.toString(str2ia(", 2")));
System.out.println(Arrays.toString(str2ia("Ett,Två")));
System.out.println(Arrays.toString((str2ia("1,,2"))));
System.out.println(Arrays.toString(str2ia("1 , 2 ,")));
-AND-
第二:替换以下代码:
// Define the input as an array of input strings and print result
// by iterating the input array elements
String [] inputStrings = {"6,8 ,9 , 10", "1002", "", ", 2", "Ett,Två", "1,,2", "1 , 2 ,"};
for (String input : inputStrings) {
int [] result = str2ia(input);
if (result == null) {
System.out.println("");
}
else {
System.out.println(Arrays.toString(result));
}
}
-with-
...
} catch (IllegalArgumentException e) {
System.out.print("Bad input");
int[] emptyArray = {};
return emptyArray;
}
答案 1 :(得分:-1)
创建您自己的代码以遍历数组:
int[] aArray = str2ia("6,8 ,9 , 10");
for (int number : aArray) {
System.out.print(number);
}
System.out.println();