Java方法调用数组 [英] Java Method Call Array

查看:87
本文介绍了Java方法调用数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将数组从主方法传递给另一个方法?我的参数有误.我是否使用main的返回值?而且由于main的返回值是一个数组,所以main调用的参数是否应该带有方括号?这些括号之间应该有一个值吗?

How do I pass an array from my main method to another method? I'm having an error with the parameters. Do I use the return value from main? And since the return value from main is an array, should the parameters for the call of main have brackets? Should there be a value between those brackets?

public class arraysAndMethods {

public void printArray(double[] arr) {
    int x = arraysAndMethods.main(double[i] arr);//error with paremeters
    for (int i = 0; i < studGrades.lenght; i++)
        System.out.print(studGrades[i] + " ");
}// end of printArray method

public static double[] main(String args[]){// double array
    java.util.Scanner input = new java.util.Scanner(System.in); // input scanner
    System.out.println("What is the size of the class?");
    int n = input.nextInt();
    double[] arr = new double[n];// declare and initialize array to have n many elements
    for (int i = 0; i < arr.length;i++) {// input grades for each students
        System.out.println("What is the grade of student #" + (i+1));
        arr[i] = input.nextDouble();
    } // end of for loop
    return arr; 
}// end of main method

}// end of class

推荐答案

这整件事没有多大意义.如果希望将此作为Java程序的main方法,则此方法将无效,因为main方法必须具有void返回类型.无论如何,您在这里有语法错误:

This whole thing doesn't make much sense. If you're hoping to have this as the main method of a Java program, this won't work because the main method must have a void return type. Regardless, you have a syntax error here:

int x = arraysAndMethods.main(double[i] arr);//error with paremeters

应该是

int x = arraysAndMethods.main(arr);//error with paremeters

,因为该变量已被声明.我不确定您要使用double[i]做什么,但是该语法更像是声明,即

as the variable has already been declared. I'm not sure what you were trying to do with double[i], but that syntax is more like a declaration, i.e.

double[] someArrayName = new double[5];

这篇关于Java方法调用数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆