-1

I'm learning Java from a MOOC and am stuck on this one exercise:

Exercise

Really having trouble with this one. I'm able to create a program that counts up to the user's chosen number (below) but stuck on how to add all the numbers up to variable n.

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

    int start = 0;

    System.out.println("Until which number? ");
    int n = Integer.parseInt(reader.nextLine());

    System.out.println("Counting begins now...");

    while (start <= (n - 1)) {
        System.out.println(start += 1);
    }

}

Any help is appreciated.

Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
nylo
  • 11
  • 3
  • what is wrong with your code? Hint; by explaining what you want and what you expect you may solve your own problem – Scary Wombat Jan 15 '18 at 01:44
  • I suggest running your code with the examples given in the assignment. It will also help to step through your code to see what it is doing. This will give clues to the flaws in your logic and help you figure out how to fix them. https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems and https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ both have some great tips to help you debug your code. – Code-Apprentice Jan 15 '18 at 02:59

2 Answers2

0
int sum = 0;

while (start <= n) {
    sum += start;
    ++start;
}

System.out.println(sum);

According to your guidelines you need to keep a record of the number of iterations start and you need to calculate the sum stored in its own variable sum.

start needs to increment every iteration

sum needs to be its previous value plus the current value of start

bboll
  • 84
  • 6
0

You on the right track, firstly to get input on the same line (like in the expected output of your task) use print rather than println.

Then basically just keep track of two "helper" variables count and sum and only print the value of the variable sum once outside the while loop:

import java.util.Scanner;

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

    System.out.print("Until what?");
    int n = scanner.nextInt();

    int count = 0;
    int sum = 0;
    while(count <= n) {
      sum += count; // increment the sum variable by the value of count
      count++; // increment the count variable by 1
    }

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

N.B. Also above I have made use of the Scanner method nextInt() rather than your Integer.parseInt solution, in the future you may want to look into pairing this with hasNextInt() that returns a boolean to ensure your program does not crash if the user inputs something other than an Integer.

Example Usage 1:

Until what? 3
Sum is 6

Example Usage 2:

Until what? 7
Sum is 28

Try it here!

Sash Sinha
  • 18,743
  • 3
  • 23
  • 40