2

サンドボックス:

    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) に入れようとしています。私はこのコードを書きましたが、次のエラーが発生します: エラー: /Users/bobgalt/Construct.java:41: '.class' expected. ご覧のとおり、私はJavaの初心者ですが、intの文字列をintの配列に入れる方法がわかりません。ありがとう

4

2 に答える 2

3

あなたの質問は、「文字列「3、2、1、0」を一連の整数に解析するにはどうすればよいですか?」だと思います。

最も簡単な答えは String.split() です。

例 (未テスト):

  String s = "3, 2, 1, 0";
  String a[] = s.split(",");
  int[] nums = new int[a.length];
  for (int i=0; i < a.length; i++)
     nums[i] = Integer.parseInt(a[i]);
于 2013-03-17T05:28:29.297 に答える
1

次のようなことを試すことができます:-

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) {};
}
于 2013-03-17T05:28:36.797 に答える