2016-03-13 4 views
0

Я пытаюсь сделать средний калькулятор для детей и в зависимости от того, сколько детей есть, я хочу рассчитать его. Таким образом, вы можете увидеть мой код, максимальное количество детей может быть 10, и есть 10 случаев, но он не позволит мне использовать одни и те же переменные из других случаев.Как устранить проблему с дублирующейся переменной?

Любые советы о том, как решить эту проблему?

package day1.examples; 

import java.util.Scanner; 


public class Practice2 { 

    public static void main(String[] args) { 
     Scanner keyboard = new Scanner(System.in); 
     System.out.println("This program will calculate the average age of children. First we need to know how many children there are before we calculate the average. "); 
     System.out.println("Enter the number of children"); 
     int NumberOfChildren; 
     NumberOfChildren = keyboard.nextInt(); 
     switch (NumberOfChildren) { 
     case 1: 
      System.out.println("What is the age of Child 1"); 
      double one = keyboard.nextDouble(); 
      System.out.println("The average age of child 1 is " + one); 
      break; 
     case 2: 
      System.out.println("What is the age of child 1?"); 
      double one = keyboard.nextDouble(); 
      System.out.println("What is the age of child 2?"); 
      double two = keyboard.nextDouble(); 
      double average = (one + two)/2; 
      System.out.println("The average age of the children is " + average); 
      break; 
     case 3: 
      System.out.println("What is the age of child 1?"); 
      double one = keyboard.nextDouble(); 
      System.out.println("What is the age of child 2?"); 
      double two = keyboard.nextDouble(); 
      System.out.println("What is the age of child 3"); 
      double three = keyboard.nextDouble(); 
      double average = (one + two + three)/3; 
      System.out.println("The average age of the children is " + average); 
      break; 
     case 4: 
      System.out.println("What is the age of child 1?"); 
      double one = keyboard.nextDouble(); 
      System.out.println("What is the age of child 2?"); 
      double two = keyboard.nextDouble(); 
      System.out.println("What is the age of child 3"); 
      double three = keyboard.nextDouble(); 
      System.out.println("What is the age of child 4"); 
      double four = keyboard.nextDouble(); 
      double average = (one + two + three + four)/4; 
      System.out.println("The average age of the children is " + average); 
      break; 
     case 5: 
      System.out.println("What is the age of child 1?"); 
      double one = keyboard.nextDouble(); 
      System.out.println("What is the age of child 2?"); 
      double two = keyboard.nextDouble(); 
      System.out.println("What is the age of child 3"); 
      double three = keyboard.nextDouble(); 
      System.out.println("What is the age of child 4"); 
      double four = keyboard.nextDouble(); 
      System.out.println("What is the age of child 5"); 
      double five = keyboard.nextDouble(); 
      double average = (one + two + three + four + five)/5; 
      System.out.println("The average age of the children is " + average); 
      break; 
     case 6: 
      System.out.println("What is the age of child 1?"); 
      double one = keyboard.nextDouble(); 
      System.out.println("What is the age of child 2?"); 
      double two = keyboard.nextDouble(); 
      System.out.println("What is the age of child 3"); 
      double three = keyboard.nextDouble(); 
      System.out.println("What is the age of child 4"); 
      double four = keyboard.nextDouble(); 
      System.out.println("What is the age of child 5"); 
      double five = keyboard.nextDouble(); 
      System.out.println("What is the age of child 6"); 
      double six = keyboard.nextDouble(); 
      double average = (one + two + three + four + five + six)/6; 
      System.out.println("The average age of the children is " + average); 
      break; 
     case 7: 
      System.out.println("What is the age of child 1?"); 
      double one = keyboard.nextDouble(); 
      System.out.println("What is the age of child 2?"); 
      double two = keyboard.nextDouble(); 
      System.out.println("What is the age of child 3"); 
      double three = keyboard.nextDouble(); 
      System.out.println("What is the age of child 4"); 
      double four = keyboard.nextDouble(); 
      System.out.println("What is the age of child 5"); 
      double five = keyboard.nextDouble(); 
      System.out.println("What is the age of child 6"); 
      double six = keyboard.nextDouble(); 
      System.out.println("What is the age of child 7"); 
      double seven = keyboard.nextDouble(); 
      double average = (one + two + three + four + five + six + seven)/7; 
      System.out.println("The average age of the children is " + average); 
      break; 
     case 8: 
      System.out.println("What is the age of child 1?"); 
      double one = keyboard.nextDouble(); 
      System.out.println("What is the age of child 2?"); 
      double two = keyboard.nextDouble(); 
      System.out.println("What is the age of child 3"); 
      double three = keyboard.nextDouble(); 
      System.out.println("What is the age of child 4"); 
      double four = keyboard.nextDouble(); 
      System.out.println("What is the age of child 5"); 
      double five = keyboard.nextDouble(); 
      System.out.println("What is the age of child 6"); 
      double six = keyboard.nextDouble(); 
      System.out.println("What is the age of child 7"); 
      double seven = keyboard.nextDouble(); 
      System.out.println("What is the age of child 8"); 
      double eight = keyboard.nextDouble(); 
      double average = (one + two + three + four + five + six + seven + eight)/8; 
      System.out.println("The average age of the children is " + average); 
      break; 
     case 9: 
      System.out.println("What is the age of child 1?"); 
      double one = keyboard.nextDouble(); 
      System.out.println("What is the age of child 2?"); 
      double two = keyboard.nextDouble(); 
      System.out.println("What is the age of child 3"); 
      double three = keyboard.nextDouble(); 
      System.out.println("What is the age of child 4"); 
      double four = keyboard.nextDouble(); 
      System.out.println("What is the age of child 5"); 
      double five = keyboard.nextDouble(); 
      System.out.println("What is the age of child 6"); 
      double six = keyboard.nextDouble(); 
      System.out.println("What is the age of child 7"); 
      double seven = keyboard.nextDouble(); 
      System.out.println("What is the age of child 8"); 
      double eight = keyboard.nextDouble(); 
      System.out.println("What is the age of child 9"); 
      double nine = keyboard.nextDouble(); 
      double average = (one + two + three + four + five + six + seven + eight + nine)/9; 
      System.out.println("The average age of the children is " + average); 
      break; 
     case 10: 
      System.out.println("What is the age of child 1?"); 
      double one = keyboard.nextDouble(); 
      System.out.println("What is the age of child 2?"); 
      double two = keyboard.nextDouble(); 
      System.out.println("What is the age of child 3"); 
      double three = keyboard.nextDouble(); 
      System.out.println("What is the age of child 4"); 
      double four = keyboard.nextDouble(); 
      System.out.println("What is the age of child 5"); 
      double five = keyboard.nextDouble(); 
      System.out.println("What is the age of child 6"); 
      double six = keyboard.nextDouble(); 
      System.out.println("What is the age of child 7"); 
      double seven = keyboard.nextDouble(); 
      System.out.println("What is the age of child 8"); 
      double eight = keyboard.nextDouble(); 
      System.out.println("What is the age of child 9"); 
      double nine = keyboard.nextDouble(); 
      System.out.println("What is the age of child 10"); 
      double ten = keyboard.nextDouble(); 
      double average = (one + two + three + four + five + six + seven + eight + nine + ten)/10; 
      System.out.println("The average age of the children is " + average);   
      break; 
     default: 
      System.out.println("Invalid amount of children"); 
      break; 
     } 
    } 
} 
+1

Использование операторов switch для этого является очень грубым подходом. Вы уже учились на циклы и массивы? – paisanco

+0

Это можно решить просто с помощью цикла и * без * любых массивов - [средние значения могут вычисляться «на лету») (http://stackoverflow.com/questions/12636613/how-to-calculate-moving-average- без учета-заместитель-кол-и-данных всего). Каждый раз через цикл просите возраст n-го ребенка и обновите (текущее) среднее значение. (Любое время, когда что-то нужно делать 1..N раз обычно указывает, что цикл будет полезен.) – user2864740

+0

Теперь, если «хотите» сохранить код одинаковым - что я бы * не рекомендовал, так как он чересчур повторяется/brittle - переменные могут быть ограничены с помощью [блока] (https://docs.oracle.com/javase/tutorial/java/nutsandbolts/expressions.html), так как: 'case n: {double one = ../* другие переменные с блочной областью здесь * /} ' – user2864740

ответ

0

Вы пробовали использовать for с массивом? Что-то вроде этого:

int amount = ... 
double[] values = new double[amount]; 
for (int i = 0; i < amount; i++) { 
    System.out.println("What is the age of child 1?"); 
    values[i] = keyboard.nextDouble(); 
} 

Затем вы можете перебирать снова для среднего и т.д.

0

Использование массива является хорошей идеей. Но чтобы исправить вашу фактическую ошибку, поместите фигурные скобки вокруг каждого блока case.

Смежные вопросы