Java 如何将整数字符串放入整数数组中?
沙盒:Java 如何将整数字符串放入整数数组中?,java,compilation,compiler-errors,Java,Compilation,Compiler Errors,沙盒: import java.util.Arrays; import java.util.Scanner; import static java.lang.System.*; import static java.util.Arrays.*; public class Sandboxx { public static void main( String args[] ) { Construct ion = new Constru
import java.util.Arrays;
import java.util.Scanner;
import static java.lang.System.*;
import static java.util.Arrays.*;
public class Sandboxx
{
public static void main( String args[] )
{
Construct ion = new Construct(3, "3, 2, 1, 0");
}
}
构造:
import java.util.Arrays;
import java.util.Scanner;
import static java.lang.System.*;
import static java.util.Arrays.*;
public class Construct
{
int length;
String s;
public Construct() {
}
public Construct(int _length) {
}
public Construct(String _s) {
}
public Construct(int _length, String _s) {
length = _length;
s = _s;
Scanner chopper = new Scanner(s);
int[] nums = new int[3];
while (chopper.hasNextInt()) {
nums = chopper.nextInt();
}
}
}
我试图将一串int,s放入一个int num数组中。我写了这段代码,但我得到了以下错误:error:/Users/bobgalt/Construct.java:41:“.class”应为。正如您所看到的,我是java新手,但我似乎不知道如何将int字符串放入int数组中。谢谢我想你的问题是如何将字符串3、2、1、0解析为一组整数 最简单的答案是String.split 未经测试的示例:
我想你的问题是如何将字符串3,2,1,0解析成一组整数 最简单的答案是String.split 未经测试的示例:
您可以尝试以下方法:-
String s= "{3,2,1,0}";
String[] x= s.replaceAll("\\{", "").replaceAll("\\}", "").split(",");
int[] s= new int[x.length];
for (int i = 0; i < x.length; i++) {
try {
s[i] = Integer.parseInt(x[i]);
} catch (Exception e) {};
}
您可以尝试以下方法:-
String s= "{3,2,1,0}";
String[] x= s.replaceAll("\\{", "").replaceAll("\\}", "").split(",");
int[] s= new int[x.length];
for (int i = 0; i < x.length; i++) {
try {
s[i] = Integer.parseInt(x[i]);
} catch (Exception e) {};
}