2013-11-20 3 views
0

Я пытаюсь преобразовать температуру массива в цельсию, но они продолжают выводить как 16.0, как я могу преобразовать все значения массива и распечатать их отдельно? Все они в порядке в зависимости от месяца, значения массива необходимо преобразовать, а затем распечатать в соответствии с месяцем.Печать массивов после изменения их значения

Ниже мой код:

import java.util.Scanner; 

class AnnualClimate 
{ 
    public static void main(String[] args) 
    { 
     // Declare and intialize variables - programmer to provide initial values 
     Scanner in = new Scanner(System.in); 
     String city = "Daytona Beach"; 
     String state = "Florida"; 
     int o = 0; 
     double celsius = 0; 
     int index = 0; 

     String month[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; 
     double temperature[] = { 58.4, 60.0, 64.7, 68.9, 74.8, 79.7, 81.7, 81.5, 79.9, 74.0, 67.0, 60.8 }; 
     double precipitation[] = { 3.1, 2.7, 3.8, 2.5, 3.3, 5.7, 5.2, 6.1, 6.6, 4.5, 3.0, 2.7 }; 
     String tempLabel = "F"; // initialize to F 
     String precipLabel = "inch"; // initialize to inch 

     // INPUT - ask user for temp and preciptation scale choice 
     System.out.print("Choose the temperature scale (F = Fahrenheit, C = Celsius): "); 
     String tempChoice = in.next(); 
     System.out.print("Choose the precipitation scale (i = inches, c = centimeteres): "); 
     String precipChoice = in.next(); 

     // PROCESSING - convert from F to C and in to cm based on user's choices 

     // remember 5/9 = 0, 5.0/9 = .5555 

     if (tempChoice.equalsIgnoreCase("C")) 
     { 
      tempLabel = "(C)"; 
      for (index = 0; index < temperature.length;) 
      { 
       celsius = (temperature[ index ] - 32) * 5/9; 
       index++; 
      } 
     } 

     // Convert in values to cm; replace the current values in precipitation 
     if (precipChoice.equalsIgnoreCase("c")) 
     { 
      precipLabel = "(cm)"; 
      for (int i = 0; i < precipitation.length; i++) 
      { 
       double centimeters = precipitation[ i ] * 2.54; 
      } 
     } 

     // OUTPUT - print table using printf to format and align data 

     System.out.println(); 
     System.out.println("Climate Data"); 
     System.out.println("Location: " + city + ", " + state); 
     System.out.printf("%5s %18s %s %18s %s", "Month", "Temperature", tempLabel, "Precipitation", precipLabel); 
     System.out.printf("%n"); 
     System.out.printf("***************************************************"); 

     while (o < month.length) 
     { 
      if (tempChoice.equalsIgnoreCase("C")) 
      { 
       System.out.printf("%n"); 
       System.out.printf(month[ o ]); 
       System.out.printf("%20.2f", celsius); 
       System.out.printf("%25.2f%n", precipitation[ o ]); 
       o++; 
      } 
     } 
     System.out.println(); 
     System.out.printf("***************************************************"); 
     System.out.println(); 
    }// end main 
} 

ответ

0

У вас есть массив результатов для хранения преобразованного значения.

Здесь Модифицированная версия вашего сегмента кода:

double[] celsius = new double[ temperature.length ]; // added!!! 
if (tempChoice.equalsIgnoreCase("C")) 
{ 
    tempLabel = "(C)"; 
    for (index = 0; index < temperature.length;) 
    { 
     celsius[ index ] = (temperature[ index ] - 32) * 5/9; // modified!!! 
     index++; 
    } 
} 

// Convert in values to cm; replace the current values in precipitation 
double[] centimeters = new double[ precipitation.length ]; // added!!! 
if (precipChoice.equalsIgnoreCase("c")) 
{ 
    precipLabel = "(cm)"; 
    for (int i = 0; i < precipitation.length; i++) 
    { 
     centimeters[ i ] = precipitation[ i ] * 2.54; // modified!!! 
    } 
} 

И изменить сегмент выходного кода:

while (o < month.length) 
{ 
    if(tempChoice.equalsIgnoreCase("C")) 
    { 
     System.out.printf("%n"); 
     System.out.printf(month[o]); 
     System.out.printf("%20.2f", celsius[ o ]); // modified 
     System.out.printf("%25.2f%n", precipitation[ o ]); // modified 
     o++; 
    } 
} 
1
for(index = 0; index < temperature.length;) 
      { 
       celsius= (temperature[index]-32)*5/9; 
       index++; 

      } 

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

Вы можете сделать celsius в массив такого же размера, как температура, чтобы удерживать каждое преобразованное значение.

+0

Кроме того, вы всегда показывает ту же температуру: System.out.printf («% 20,2f», по Цельсию); Это должен быть соответствующий индекс массива. – user3001267

2

вы печатаете только переменная цельсию. Но то, что вам действительно нужно для печати, - это важная величина температуры. Поэтому создайте массив и поместите значения temprature при их вычислении и распечатайте их. Просто создайте массив.

Double[] celsius_temp=new Double[temperature.length]; 

` И ценности хранят при расчете

if(tempChoice.equalsIgnoreCase("C")) 
    { 
     tempLabel="(C)"; 


     for(index = 0; index < temperature.length;) 
     { 
      celsius= (temperature[index]-32)*5/9; 

      celsius_temp[index]=celsius; 
      index++; 

     } 

    } 

и вывести таблицу

System.out.println(); 
    System.out.println("Climate Data"); 
    System.out.println("Location: " + city +", " + state); 
    System.out.printf("%5s %18s %s %18s %s","Month","Temperature",tempLabel,"Precipitation",precipLabel); 
    System.out.printf("%n"); 
    System.out.printf("***************************************************"); 


    while (o< month.length) 
    { 

    if(tempChoice.equalsIgnoreCase("C")) 
    { 
     System.out.printf("%n"); 
     System.out.printf(month[o]); 
     System.out.printf("%20.2f", celsius_temp[o]); 
     System.out.printf("%25.2f%n", precipitation[o]); 
     o++; 


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