Loops do not keep values

Asked

Viewed 67 times

0

Hello! I am trying to develop a simple program that does an automatic accounting calculation, however, the condition within the for(while, while, if / Else, either) does not maintain its values. The repetition is executed 12~13 times and in all of them the output value is not changed. Because exactly the values within the loops are zeroed and displayed as if only one account had been made?

public static void main(String[] args) 
    {
      int x;
      double percentual=0.005, ValorSaida, ValorPercentual=0;
      x=Integer.parseInt(JOptionPane.showInputDialog("Digite o valor depositado mensalmente"));

      for(int meses=0; meses<=12; meses++)
      {  

       ValorPercentual=x*percentual;
       ValorSaida=x+ValorPercentual;
       JOptionPane.showMessageDialog(null, ""+ValorSaida+" "+ValorPercentual);

      }     


    }
  • You have the same x to something, or you’ll never get out...

  • Clarifying Cesarmiguel’s Commission: Following JOptionsPane.ShowMess..... equals x to ValorSaida

1 answer

2

Every time the code executes the loop, it under-writes the values try so:

public static void main(String[] args) 
    {
      int x;
      double percentual=0.005, ValorSaida, ValorPercentual=0;
      x=Integer.parseInt(JOptionPane.showInputDialog("Digite o valor depositado mensalmente"));

      for(int meses=0; meses<=12; meses++){  

          ValorPercentual += x*percentual;
          ValorSaida += x+ValorPercentual;

      }     
      JOptionPane.showMessageDialog(null, ""+ValorSaida+" "+ValorPercentual);

    }

You have to sum the values --> with the +=

  • The problem with putting the display outside the Loop is that it will only display the 12-month one. Keep the display inside if you need to display each month. I also suggest starting with 1 instead of 0.

  • 1

    I even agree with showMessage outside the loop - and I’m sorry for that. But if it starts the valuePercentual with 1 it will change the final value. Example: 1st time q enters the loop the valuePercentual will be-> 1 +(x*0.005) and the result would be wrong.

  • Well noted... my failure to have targeted only the months and the exhibition.

  • Thank you! That was just "+=", I tried many codes/methods and that was it. It’s a problem created by myself, the location of the exhibition is not that important, nor have I decided where to put it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.