简体   繁体   中英

use a variable from inside a for loop, outside of the loop

I'm a first time user here, though trying to find answers to my nooby question have sometimes led me here in the past.

So basically, I have this code I'm using to find the surface temperature of the planet Earth, implementing a few forumlas I've been provided with. I need to find a value (epCarbonDi) which changes depending on the carbon levels in the atmosphere. I used a "for" loop to get java to do the equation each time the amount of carbon changes, but bluej wouldnt compile it, it said that the variable might not have been initialised. I had declared it before the "for" loop but not assigned it a value as the "for" loop is meant to be there to fill the variable with a value, which I then need to use outside the loop afterwards.

I read somewhere that if you just initialise the variable outside the loop with 0, it should work that way^^, so I did it, and it compiles and that great. i go to execute it, and all my lines of info come out fine but lo and behold, all the answers are the SAME!!

So i gather that the "for" loop has executed once and found the answer but then not done it for all the other values that i need it to do it for?

I really really need some advice if anyone has any..I'd be so super grateful. I need to be able to use the epCarbonDi variable outside the "for" loop with the loop value/s for the next equation! If somebody could point me in the right direction that would be fantastic. I'm very new to java, i've re-read all my notes and the textbook i have and I've google searched it and i cant find anything that makes it work D:

This is my whole code

import java.text.DecimalFormat;
import java.math.RoundingMode;

/**
 * A program to calculate the surface temperature of Earth 
 * based on a range of carbon dioxide levels.
 * 
 * @author Lyssa ------ - Student #--------- 
 * @version ----------
 */
public class Stage4
{
    public static void main(String[] args)
    {
        //define constants for calculating emissivity
        final double EP_WATER = 0.65;           //component of emissivity due to water
        final double A = 0.1;                   //component of emissivity due to carbon dioxide
        final double B = 0.06;                  //component of emissivity due to carbon dioxide
        final double PREINDUST_CARBONDI = 280;  //pre-industrial level of carbon dioxide in Earth's atmosphere

        //define surface temperature constants
        final double SOLAR_CONSTANT = 1367;
        final double ALBEDO = 0.3;
        final double STEFANB_CONSTANT = 5.67E-8;
        final double ORBIT_RAD = 1.0;           //the orbital radius of Earth.
        final double KELV_CELS_DIFF = 273.15;   //the difference between kelvin and celsius.

        //declare variables to hold answer values
        double epsilon;                         //emissivity of the planet
        double epCarbonDi = 0.0;                //component of emissivity due to carbon dioxide
        double surfaceTemp;
        double surfaceTempCelsius;

        //formula to calcluate value of emissivity due to carbon dioxide
        for(double carbonDiox = 280.0; carbonDiox <= 400.0; carbonDiox = carbonDiox += 5)
        {
            epCarbonDi = A + B*Math.log(carbonDiox/PREINDUST_CARBONDI);
        }

        //formula to calculate emissivity
        epsilon = 1.0 - (EP_WATER + epCarbonDi/2);

        //write calculation to find surface temperature
        surfaceTemp = 
              Math.pow((SOLAR_CONSTANT/4)*(1.0 - ALBEDO)
              /(STEFANB_CONSTANT*epsilon*ORBIT_RAD*ORBIT_RAD), 0.25);

        //convert answer from kelvin to celcius
        surfaceTempCelsius = surfaceTemp - KELV_CELS_DIFF;

        //enable answer to be truncated to 2 decimal places
        DecimalFormat df = new DecimalFormat("####0.00");
        df.setRoundingMode(RoundingMode.FLOOR);

        for(double carbonDiox = 280.0; carbonDiox <= 400.0; carbonDiox = carbonDiox += 5)
        {
            System.out.print("For a carbon level of " + carbonDiox + 
                            " the surface temperature is: "
                            + df.format(surfaceTempCelsius) 
                            + " \u00b0" + "C");
            System.out.print("\n");
        }
    }
}

and this is where im having issues:

//declare variables to hold answer values
        double epsilon;                         //emissivity of the planet
        double epCarbonDi = 0.0;                //component of emissivity due to carbon dioxide
        double surfaceTemp;
        double surfaceTempCelsius;

        //formula to calcluate value of emissivity due to carbon dioxide
        for(double carbonDiox = 280.0; carbonDiox <= 400.0; carbonDiox = carbonDiox += 5)
        {
            epCarbonDi = A + B*Math.log(carbonDiox/PREINDUST_CARBONDI);
        }

        //formula to calculate emissivity
        epsilon = 1.0 - (EP_WATER + epCarbonDi/2);

        //write calculation to find surface temperature
        surfaceTemp = 
              Math.pow((SOLAR_CONSTANT/4)*(1.0 - ALBEDO)
              /(STEFANB_CONSTANT*epsilon*ORBIT_RAD*ORBIT_RAD), 0.25);

in your loop evertime the epCarbon value is replaced so ever time once the loop completed the value in epCarbon will be the reult of A + B*Math.log(400/PREINDUST_CARBONDI); it is equivalent of a single statement as i mentioned above so the for loop doesnt make any sense. Tell me what exactly you want inside the loop for epCarbonDi is it that for every iteration result you want it to add to the previous result in that case change your code to following

for(double carbonDiox = 280.0; carbonDiox <= 400.0; carbonDiox = carbonDiox += 5)
    {
        epCarbonDi = epCarbonDi+(A + B*Math.log(carbonDiox/PREINDUST_CARBONDI));
    }

or if you want the whole thing till the system.out for each iteration then put the whole thing in 1 loop

//formula to calcluate value of emissivity due to carbon dioxide
    for(double carbonDiox = 280.0; carbonDiox <= 400.0; carbonDiox = carbonDiox += 5)
    {
        epCarbonDi = A + B*Math.log(carbonDiox/PREINDUST_CARBONDI);       

       //formula to calculate emissivity
       epsilon = 1.0 - (EP_WATER + epCarbonDi/2);

       //write calculation to find surface temperature
        surfaceTemp = 
          Math.pow((SOLAR_CONSTANT/4)*(1.0 - ALBEDO)
          /(STEFANB_CONSTANT*epsilon*ORBIT_RAD*ORBIT_RAD), 0.25);

        //convert answer from kelvin to celcius
        surfaceTempCelsius = surfaceTemp - KELV_CELS_DIFF;

        //enable answer to be truncated to 2 decimal places
        DecimalFormat df = new DecimalFormat("####0.00");
        df.setRoundingMode(RoundingMode.FLOOR);       
        System.out.print("For a carbon level of " + carbonDiox + 
                        " the surface temperature is: "
                        + df.format(surfaceTempCelsius) 
                        + " \u00b0" + "C");
        System.out.print("\n");
}

if this not what you want then tell me what you want out of that loop as the value for epCarbonDi i will help you

Some issues I see

  • you are assigning to epCarbonDi inside the loop but the compiler can't figure the fact that the loop is always executed, the condition could be false from the first iteration hence epCarbonDi could be used afterwards uninitialised.
  • you use carbonDiox = carbonDiox += 5 as increment condition but it is equivalent to carbonDiox += 5
  • inside your loop you are not accumulating any value, just assigning to it ( epCarbonDi = .. ), thus overwriting the previous iteration, is it intended behavior or what?

@honeyb_93 If overwriting epCarbonDi is not the desired behavior, then you should use an array that stores all the values of epCarbonDi .

        double epsilon;                         //emissivity of the planet
        double epCarbonDi[] = new double[ /*NO. OF VALUES TO BE STORED*/ ];                //component of emissivity due to carbon dioxide
        double surfaceTemp;
        double surfaceTempCelsius;

        //formula to calcluate value of emissivity due to carbon dioxide
        int i = 0;
        for(double carbonDiox = 280.0; carbonDiox <= 400.0; carbonDiox = carbonDiox += 5)
        {
            epCarbonDi[i] = A + B*Math.log(carbonDiox/PREINDUST_CARBONDI);
            i = i+1;
        }

Check this out.

The variable that you have used is a double. Every time the for loop is executed, it assigns a value to the desire variable. But on each iteration, the value is re-written. ie In the first run of the loop. say the variable is assigned value 1. On the second run, you are re-assigning another value to the same variable, say 2 and so on. So the variable will always have the value computed from the last run of the for loop.

If you want to use each and every value computed in the for loop, store it in an array or a list and later use them as you wish.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM