Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How to add numbers over time?

Tags:

java

<pre> import java.util.*;

public class Test {
private static int StartingMoney = 1000;
private static int MaxMoney = 10000;
private static int Add = 100;
static Scanner question = new Scanner(System.in);
    public static void main(String[] args) {
        while(StartingMoney != MaxMoney){
            System.out.println("1:Add Money");
            int userInput = question.nextInt();
                if(userInput == 1){
                    System.out.println(StartingMoney + Add);
                }

        }
    }

}
 <code>

The goal of this code is to add a number until it reaches a certain amount, and the user will be able to choose whether or not he or she can add numbers to their current amount they have. The output is always 1100

like image 376
MooseReic Avatar asked Dec 29 '25 13:12

MooseReic


1 Answers

By doing System.out.println(StartingMoney + Add); you are only printing the value to the console and not changing your actual StartingMoney variable and this will still be 1000.

Your program will go in an infinite loop as the condition StartingMoney != MaxMoney will never be reached.

You should be doing this instead:

StartingMoney += Add;
System.out.println(StartingMoney);

Here is the corrected code snippet:

import java.util.*;

public class Test {
    private static int StartingMoney = 1000;
    private static int MaxMoney = 10000;
    private static int Add = 100;
    private static Scanner question = new Scanner(System.in);

    public static void main(String[] args) {
        while(StartingMoney != MaxMoney){
            System.out.println("1: Add Money");
            int userInput = question.nextInt();
            if(userInput == 1) {
                /* Note the change here */
                StartingMoney += Add;
                System.out.println(StartingMoney);
            }
        }
    }
}
like image 143
user2004685 Avatar answered Dec 31 '25 03:12

user2004685



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!