| 12345678910111213141516171819202122232425262728293031 |
- import java.util.Scanner;
-
- /**
- * Sum of the Numbers
- */
- public class Main {
- /**
- * Prompts user to enter an integer. Then calculates the sum of numbers from 1 to entered value.
- */
- public int getNumber(){
- Scanner scanner = new Scanner(System.in);
-
- System.out.println("Enter an integer."); //Prompt
- int input = scanner.nextInt(); //User supplies a value which is assigned to 'input'
- return input;
- }
-
- public int sumNumbers(int n){
- int x = 0;
- //Loop runs n times
- for (int i = 0; i <= n; i++){
- x += i; //adds current value of x to i and sets that as the new x
- }
- return x;
- }
-
- public void solutionBasedOnInput(){
- int answer = sumNumbers(getNumber()); //runs sumNumbers() with the number supplied by the user from getNumber()
- System.out.print(answer); //Prints the solution
- }
- }
|