数组—将for循环移到另一个方法中,并将其连接到主java

oxf4rvwz  于 2021-07-12  发布在  Java
关注(0)|答案(2)|浏览(340)

我正在用java编写一个程序,计算输入的数字之和;我把这部分弄明白了。但是,我想将for循环移到另一个名为“sum”的方法中,但是我不断地出现错误,我不知道该怎么办。
下面是只在main方法中使用的代码(它工作得非常好):

import java.util.Scanner;
public class testing {
   public static void main(String args[]){
      System.out.println("Enter the size of the array: ");
      Scanner in = new Scanner(System.in);
      int size = in.nextInt();
      int myArray[] = new int [size];
      int sum = 0;
      System.out.println("Enter the elements of the array one by one: ");

      for(int i=0; i<size; i++){
         myArray[i] = in.nextInt();
         sum = sum + myArray[i];
      }
      System.out.println("Sum of the elements of the array: "+ sum);
   }
}

但是,当我将for循环移到称为print的方法中时,会出现一系列错误:

import java.util.Scanner;
public class MPA4 {
        public static void main(String[] args) {
            System.out.println("Enter the size of the array: ");
              Scanner in = new Scanner(System.in);
              int size = in.nextInt();
              int myArray[] = new int [size];
              int sum = 0;
              System.out.println("Enter the elements of the array one by one: ");
            }
             print(sum);
    }
        public static void print (double []sum){
            Scanner in = new Scanner(System.in);
            int myArray[] = new int [size];
            for(int i=0; i<size; i++){
                 myArray[i] = in.nextInt();
                 sum = sum + myArray[i];
        }
            System.out.println("Sum of the elements of the array: "+ sum);
    }
}

以下是红色下划线的所有错误:

我不知道我做错了什么,任何帮助都将不胜感激!

mm5n2pyu

mm5n2pyu1#

我改变了它如下,它是工作。

import java.util.Scanner;

public class MP4 {
public static void main(String[] args) {
    System.out.println("Enter the size of the array: ");
    Scanner in = new Scanner(System.in);
    int size = in.nextInt();
    int myArray[] = new int[size];
    System.out.println("Enter the elements of the array one by one: ");

    for (int i = 0; i < size; i++) {
        myArray[i] = in.nextInt();
    }
    print(myArray, size);
}

public static void print(int[] myArray, int size) {
    int sum = 0;
    Scanner in = new Scanner(System.in);
    for (int i = 0; i < size; i++) {

        sum = sum + myArray[i];
    }
    System.out.println("Sum of the elements of the array: " + sum);
}
}
cu6pst1q

cu6pst1q2#

print()方法不在类范围内。把它移到教室里,它应该会起作用。在java中,所有函数都将出现在一个类或一个接口中以工作,否则我们不能调用它们。另外,print()调用应该在main()方法中。

相关问题