【问题标题】:Creating an array issue创建数组问题
【发布时间】:2015-03-08 17:51:32
【问题描述】:

我写了这段代码,但它说语句 6 是错误的 谁能告诉我有什么问题吗

public class arraytest{
private int a[];
private int noe; //number of elememtos
public arraytest(){
noe=5;
a[5];}
}
public void read(){
a[0]=5;a[1]=3;a[2]=6;a[3]=9;a[4]=2;}
public int sum(){
int sum=0;
for (int i=0; i<a.length();i++)
sum=sum+a[i];
return sum;}

public static void main(String[]args){
arraytest x=new arraytest();
x.read();
System.out.println("The sum is " + x.sum());
}
}

【问题讨论】:

  • 您没有为 a[5] 设置任何值
  • 你应该格式化你的代码,这是一个很好的理解它的练习。

标签: java arrays object-oriented-analysis


【解决方案1】:

啊,菜鸟的错误

他认为他用 a[5] 初始化了数组,这是错误的

我猜他试图这样做

public arraytest(){
 noe=5;
 a = new int[noe];
}

伙计,学习如何缩进你的代码,以便其他试图帮助你的人更容易阅读

public class arraytest{
   private int a[];
   private int noe; //number of elememtos
   public arraytest(){
     noe=5;
     a = new int[noe];
   }

   public void read(){
     a[0]=5;a[1]=3;a[2]=6;a[3]=9;a[4]=2;
   }

   public int sum(){
     int sum=0;
     for (int i=0; i<a.length;i++)
     sum=sum+a[i];
     return sum;
   }

   public static void main(String[]args){
      arraytest x=new arraytest();
      x.read();
      System.out.println("The sum is " + x.sum());
   }
}

【讨论】:

  • 非常感谢,对不起,我还是个菜鸟,您的纠正工作非常感谢您的帮助
  • 仅作记录:考虑删除不再需要的 cmets ;-)
  • @HishamIbrahimRaGe:如果答案对你有用,别忘了接受答案,这将对未来的访客有所帮助
【解决方案2】:
a[5];

不是一个有效的陈述。您需要执行一些任务。

a[5] = 5; //for example

【讨论】:

  • 那我该怎么办兄弟。
  • 这取决于你试图用那行代码完成什么。编译器只是简单地告诉您,您不能只将a[5]; 作为一行代码。你必须用它做点什么。
  • 您的代码中还有其他错误。您有大括号匹配问题,并且数组没有 length() 方法,只有 length 字段。
  • 我试图创建一个数组来读取 5 个元素(noe=number of elements )
  • ok 长度不应该有 () ,jgrasp程序说arraytest.java:6: not a statement a[5];} ^ arraytest.java:8: class, interface, or enum expected public无效读取(){ ^
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-22
  • 1970-01-01
  • 1970-01-01
  • 2018-12-22
  • 2017-12-17
  • 2016-02-24
相关资源
最近更新 更多