50.7k views
4 votes
Consider the following program. Modify the given SumNumbers code to use a Scanner to prompt the user for the values of low and high. The following is a sample execution in which the user asks for the sum of the values 1 through 10.

User Captastic
by
7.2k points

1 Answer

7 votes

This program uses the Scanner class to prompt the user for the low and high values, calculates the sum of the numbers within that range using the calculateSum method, and then displays the result.

What happens to the code?

If the user enters "1" for low and "10" for high, the program will output:

Enter the low value:

1

Enter the high value:

10

The sum of numbers from 1 to 10 is: 55

This revised program allows the user to input any range of numbers and calculate the sum accordingly.

The Complete Program

Consider the following program. Modify the given SumNumbers code to use a Scanner to prompt the user for the values of low and high. The following is a sample execution in which the user asks for the sum of the values 1 through 10.

import java.util.Scanner;

public class SumNumbers {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter low and high values: ");

int low = scanner.nextInt();

int high = scanner.nextInt();

int sum = 0;

for (int i = low; i <= high; i++) {

sum += i;

}

System.out.println("Sum of numbers from " + low + " to " + high + ": " + sum);

scanner.close();

}

}

User Michael Sofaer
by
7.6k points