【问题标题】:How to put a String of ints into an array of ints?如何将整数字符串放入整数数组中?
【发布时间】:2013-03-17 05:23:02
【问题描述】:

沙盒:

    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();
    }

  }

}

我正在尝试将一串整数 (s) 放入整数数组 (nums) 中。我写了这段代码,但我收到了这个错误:错误:/Users/bobgalt/Construct.java:41: '.class' expected。如您所见,我是java的新手,但我似乎无法弄清楚如何将整数字符串放入整数数组中。谢谢

【问题讨论】:

    标签: java compilation compiler-errors


    【解决方案1】:

    我认为您的问题是“如何将字符串“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]);
    

    【讨论】:

      【解决方案2】:

      你可以试试这样的:-

      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-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多