Casey French
Casey French

Reputation: 139

how to add numbers together in the way you would print with (System.out.println(numbers)); numbers++;

how would i add numbers together in the same manner as if i were to print them for example.

    System.out.println(numbers);
    numbers++;

this would print like so.

    1
    2
    3
    4

etc

how would i add them together as 1+2+3+4

here is my current code on this question. this is the exercise i am working on for my MOOC at the University of Helsinki i live in the US so its hard to ask for help because of the 8 hour time difference.

    public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);

    System.out.print("Until What?:");
    // the user inputs a number here
    int blockExe = 1;
    // the blockExe variable is supposed to store a count of how many times the
    // block has been executed which i belive should be limited to the user input
    int userIn = Integer.parseInt(reader.nextLine());
    int sum = userIn + blockExe;
    // i am supposed to add the number of block executions the user input 
    // each time adding 1 to the execution so 1+2+3
    // then printing the sum of those numbers

    while (blockExe <= userIn) {
        blockExe += 1;
        if (blockExe + userIn == sum) {
            break;
        }
    }
    System.out.println("Sum is:" +sum);

}

}

Upvotes: 0

Views: 3029

Answers (2)

Bakon Jarser
Bakon Jarser

Reputation: 721

System.out.println("Sum is:" +sum);

That line doesn't make sense. I think the number you are trying to output should be blockExe but it isn't really clear what you are trying to do from you description. Try changing that line to:

System.out.println("Sum is:" blockExe);

and see if that gets you closer to your answer.

Upvotes: 0

DnR
DnR

Reputation: 3507

This code is ambiguous:

while (blockExe <= userIn) {
    blockExe += 1;
    if (blockExe + userIn == sum) {
        break;
    }
}

Perhaps you want this:

int sum=0;
for(blockExe = 1;blockExe <= userIn; blockExe ++) {
    sum+=blockExe;
}

Upvotes: 1

Related Questions