将声明的字符串转换为数组

时间:2013-11-28 05:11:48

标签: java arrays jgrasp

在我的程序中,用户声明了一串我想要变成数组的数字。
示例:

  

WeeklyFiber week2 = new WeeklyFiber(“CS4567”,“11/24/13”,32,“27,26,   28" );

我试图找出如何将该字符串添加到我的类实例变量中 这就是我所拥有的:

   private String sampleID;
   private String weekOfTest;
   private int engineerID;
   private String[] strengths = new String[20];
   private static int count; 

  public WeeklyFiber(String sampleID, String weekOfTest, int engineerID, String strengths) 
   {
      this.sampleID = sampleID;
      this.weekOfTest = weekOfTest;
      this.engineerID = engineerID;
      this.strengths = strengths;
      count++;
   }

我的编译错误消息显示不兼容的类型,必需:String [],found:String

4 个答案:

答案 0 :(得分:0)

这是因为你声明了String []的优势是一个数组。

声明你的构造函数:

public WeeklyFiber(String sampleID, String weekOfTest, int engineerID, String[] strengths) 
   {
      this.sampleID = sampleID;
      this.weekOfTest = weekOfTest;
      this.engineerID = engineerID;
      this.strengths = strengths;
      count++;
   }

拨打电话:

WeeklyFiber week2 = new WeeklyFiber("CS4567", "11/24/13", 32, new String[] {"27","26", "28"});

答案 1 :(得分:0)

像这样传递:

WeeklyFiber week2 = new WeeklyFiber("CS4567", "11/24/13", 32, 
                          new String[] { "27", "26", "28" });

答案 2 :(得分:0)

您需要将String个数字解析为多个String。例如,

this.strengths = strengths.split(",");

答案 3 :(得分:0)

您不能说this.strengths = strengths,因为strengths参数的类型为String,而不是String[]。这就是你的错误来自哪里。