2014-12-09 3 views
-2

Я пытаюсь сделать код, чтобы вернуть значение обратно в класс Main, однако, когда я возвращаю ответ, как 0.0 Почему это и как я его исправить?Возврат значения из метода

BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
String[]temp = new String[7]; 
int[] arr = new int[7]; 
for (int i = 0; i < 7; i++) { 
    System.out.println("Please enter the temperature for the " + (i + 1)+" day of the week"); 
    //Not the most gramatically correct. But i did what i could while using the loop. 
    temp[i] = br.readLine(); 
} 

System.out.println("The temperature for Monday is: " + temp[0]); 
System.out.println("The temperature for Tuesday is: " + temp[1]); 
System.out.println("The temperature for Wednesday is: " + temp[2]); 
System.out.println("The temperature for Thursday is: " + temp[3]); 
System.out.println("The temperature for Friday is: " + temp[4]); 
System.out.println("The temperature for Saturday is: " + temp[5]); 
System.out.println("The temperature for Sunday is: " + temp[6]); 

double avg = averageValue(arr); 
System.out.println("Avg Temp for the week is: \t\t " + avg); 

public static double averageValue(int[] arr) { 
    double average = 0; 
    for (int i = 0; i< arr.length; i++) { 
     average += arr[i] 
    } 
    return average/arr.length; 
} 
+0

обр не инициализирован в коде. – Rndm

+0

Могу ли я переключить его на temp, поскольку это мой массив? – dappers

ответ

0

Следующий код, похоже, исправил его. Вам нужно было поместить значения в объект arr.

public static void main(String[] args) { 
    try { 
     BufferedReader br = new BufferedReader 
       (new InputStreamReader(System.in)); 

     String[] temp = new String[7]; 
     int[] arr = new int[7]; 
     for (int i = 0; i < 7; i++) { 
      System.out.println("Please enter the temperature for the " + (i + 1) + " day of the week"); //Not the most gramatically correct. But i did what i could while using the loop. 
      temp[i] = br.readLine(); 
      arr[i] = Integer.parseInt(temp[i]); // ** 
     } 

     System.out.println("The temperature for Monday is: " + temp[0]); 
     System.out.println("The temperature for Tuesday is: " + temp[1]); 
     System.out.println("The temperature for Wednesday is: " + temp[2]); 
     System.out.println("The temperature for Thursday is: " + temp[3]); 
     System.out.println("The temperature for Friday is: " + temp[4]); 
     System.out.println("The temperature for Saturday is: " + temp[5]); 
     System.out.println("The temperature for Sunday is: " + temp[6]); 

     double avg = averageValue(arr); 
     System.out.println("Avg Temp for the week is: \t\t " + avg); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

public static double averageValue(int[] arr) { 
    double average = 0; 
    for (int i = 0; i < arr.length; i++) { 
     average += arr[i]; 
    } 
    return average/arr.length; 
} 

Выход

Please enter the temperature for the 1 day of the week 
1 
Please enter the temperature for the 2 day of the week 
2 
Please enter the temperature for the 3 day of the week 
3 
Please enter the temperature for the 4 day of the week 
6 
Please enter the temperature for the 5 day of the week 
7 
Please enter the temperature for the 6 day of the week 
8 
Please enter the temperature for the 7 day of the week 
9 
The temperature for Monday is: 1 
The temperature for Tuesday is: 2 
The temperature for Wednesday is: 3 
The temperature for Thursday is: 6 
The temperature for Friday is: 7 
The temperature for Saturday is: 8 
The temperature for Sunday is: 9 
Avg Temp for the week is:  5.142857142857143 
0

Вы получаете информацию от пользователя для температур в String[] temp массива, но при расчете среднего вы передаете массив int[] arr, который не имеет никакого значения. Поэтому он оказывается равным нулю.

Значения, которые вы получаете по br.readLine(), представлены в строковой форме. Если вы хотите рассчитать их среднее значение, вам нужно либо преобразовать все значения в temp[] в целое число, и сохранить их в arr[] перед вызовом метода.

Или вместо этого вы можете использовать сканер для непосредственного ввода значений int. Подсказка:

Scanner sc = new Scanner(System.in); 
arr[0] = sc.nextInt(); 
Смежные вопросы