Hi
I have to complete an assignment, for which I am trying to write a program. I have posted my code below and all the instruction are in the comments.
Code:
public class MathOperationsTester
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println( "TESTING sumOfIntegers" );
// STEP 3: The next two statements request the user to enter the value of n and then reads in their response as an int using the
// nextInt method of the Scanner class.
// The problem with this is that if the user enters something other than an int, we will have a runtime exception.
// After requesting the user enters n (first of the next two statements), write a while loop that repeats as long as the user
// enters something other than an int (recall that the hasNextInt method of the Scanner class will return true if the user
// enters an int and false otherwise. And recall that ! is Java's not operator. Inside the loop, you'll want to remove whatever they
// did enter with a call to the next method of the Scanner class. And you'll want to give them an error message indicating that they should try again.
// This loop should be immediately prior to the call to the nextInt method which has been done for you.
System.out.println( "Enter n:");
// Your loop from Step 3 will go here.
while( !hasNextInt())
System.out.println("Please enter a valid integer");
int n = in.nextInt();
int sum = MathOperations.sumOfIntegers(n);
System.out.println("Sum of first " + n + " integers is " + sum);
Bookmarks