-1

I am writing a program that asks the user to input a positive integer and to calculate the sum from 1 to that number. Need some tips on what i'm doing wrong.

Here is the code:

public static void main(String[] args){
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Enter a positive integer");
    int getNumber=keyboard.nextInt();
    int x;
    int total = 0;
    for (x=1;x<=getNumber;x++) {
        total=x+1;
    }
    System.out.println(total);
}
Naman
  • 27,789
  • 26
  • 218
  • 353
Mariusz
  • 19
  • 1
  • 1
  • 1

5 Answers5

1

Try below code:

public static void main(String[] args){
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Enter a positive integer");
        int getNumber = keyboard.nextInt();
        int x;
        int total = 0;
        for (x=1;x <= getNumber;x++) {
            total += x;
        }
        System.out.println(total);
    }
Atul Kamani
  • 105
  • 6
0

The logic should be changed from

total=x+1;  // you evaluate total each iteration to initialize it with x+1

to

total=total+x; // you keep adding to the existing value of total in each iteration
Naman
  • 27,789
  • 26
  • 218
  • 353
0

to get the sum from 1 to the input number you want to increment total by each time with the new number x.

so do total = total + x.

also a tip:

you want to declare int x with your for loop. delete int x and do the following:

for (int x=1; x<=getNumber; x++) {
    total = total + x;
}
OLIVER.KOO
  • 5,654
  • 3
  • 30
  • 62
0

Your issue is:

your total value is wrong, Because of this line:

total=x+1;

It should be:

total = total + x;
Fady Saad
  • 1,169
  • 8
  • 13
0

Change this:

total=x+1;

to this:

total=total+x;
msagala25
  • 1,806
  • 2
  • 17
  • 24