如何将用户输入传递给方法然后让该方法返回整数或双精度?我一直得到一个错误,我必须返回一个整数,但我不明白如何。
import java.util.Scanner;
public class Q7_8 {
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter 10 integers:");
int[] a = new int[10];
for(int i =0; i < a.length; i++){
a[i] = sc.nextInt();
}
average(a);
}
public static int average(int [] array){
int sum =0;
for(int i = 0; i < array.length; i++){
sum += array[i];
int finalAvr = array[i] /10;
}
}
public static double average(double [] array){
int sum =0;
for(int i = 0; i < array.length; i++){
sum += array[i];
double finalAvr = array[i] /10;
}
}
}
答案 0 :(得分:0)
警告我不仅仅是一个C ++人,但它仍然应该是类似的:
public static int average(int [] array){
int sum =0;
for(int i = 0; i < array.length; i++){
sum += array[i];
int finalAvr = array[i] /10;
}
return sum / 10; // you need to return the average you calculated
}
双倍的平均值相同。你错过了这一行:
return sum / 10.0;
答案 1 :(得分:-1)
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter 10 integers:");
int[] a = new int[10];
for(int i =0; i < a.length; i++){
a[i] = sc.nextInt();
}
double avg = average(a); //if average return something, then you must assign the value return somwhere.
System.out.println(avg); // print the valued return - avg
}
public static int average(int [] array){
int sum =0;
for(int i = 0; i < array.length; i++){
sum += array[i];
}
return (int)(sum/array.length); //must return if you specify return type
}
public static double average(double [] array){
double sum =0;
for(int i = 0; i < array.length; i++){
sum += array[i];
}
return sum/array.length; //must return if you specify return type
}
参考文献: https://docs.oracle.com/javase/tutorial/java/javaOO/returnvalue.html