简体   繁体   English

在循环外使用for循环内的变量

[英]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. 我是这里的第一次用户,尽管过去有时试图找到有关我的nooby问题的答案的经验。

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. 我需要找到一个值(epCarbonDi),该值根据大气中的碳含量而变化。 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. 每当碳量发生变化时,我都使用“ for”循环让java来执行方程式,但是bluej不会对其进行编译,它表示该变量可能尚未初始化。 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. 我已经在“ for”循环之前声明了它,但没有给它赋值,因为“ for”循环意味着要在其中用一个值填充变量,然后我需要在循环外使用它。

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. 我在某处读到,如果您只是将循环外的变量初始化为0,则它​​应该以这种方式工作^^,所以我做到了,并且可以编译并且效果很好。 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? 因此,我收集到“ 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! 我需要能够将“ for”循环外的epCarbonDi变量与下一个方程式的循环值一起使用! 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: 我对Java还是很陌生,我已经重新阅读了所有笔记和教科书,并在Google上进行了搜索,但找不到任何可以使它正常工作的东西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); 每次循环中都会替换epCarbon值,因此每次循环完成后,epCarbon中的值将成为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. 正如我上面提到的,它等效于单个语句,因此for循环没有任何意义。 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 告诉我,对于epCarbonDi循环,您真正想要的是在每次迭代结果中将其添加到上一个结果中的情况,在这种情况下,将代码更改为以下内容

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 或者如果您希望整个过程直到system.out每次迭代,然后将整个过程放在1个循环中

//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 如果这不是您想要的,请告诉我您想要从循环中获取什么,因为epCarbonDi的值我会帮助您

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. 您在循环内分配给epCarbonDi ,但编译器无法弄清楚循环始终执行的事实,该条件可能在第一次迭代时为假,因此epCarbonDi可以在未初始化后使用。
  • you use carbonDiox = carbonDiox += 5 as increment condition but it is equivalent to carbonDiox += 5 您使用carbonDiox = carbonDiox += 5作为增量条件,但它等效于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? 在循环内部,您并没有累积任何值,只是将其赋值( epCarbonDi = .. ),从而覆盖了之前的迭代,它是预期的行为还是什么?

@honeyb_93 If overwriting epCarbonDi is not the desired behavior, then you should use an array that stores all the values of epCarbonDi . @ honeyb_93如果不希望覆盖epCarbonDi ,则应使用一个数组,该数组存储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. 每次执行for循环时,都会为期望变量分配一个值。 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. 假设变量分配了值1。在第二次运行中,您正在将另一个值重新分配给同一变量,例如2,依此类推。 So the variable will always have the value computed from the last run of the for loop. 因此,该变量将始终具有从for循环的最后一次运行中计算出的值。

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. 如果要使用for循环中计算出的每个值,请将其存储在数组或列表中,然后根据需要使用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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