A program that continually asks for integers until a non-integer is inputted. It prints the sum of all integers inputted and the number of attempts

Viewed 42

This is a problem from a coding challenge website I found. and this is my code:

What do I need to do or change to get the desired output I wanted.

import java.util.Scanner; 
   public class CopyOfInputLoop { 
        public static void main (String[] args)  { 
        Scanner scan = new Scanner(System.in); 
        System.out.println ("Enter an integer to continue or a non-integer value to finish. Then press return."); 
    
    //placeholder variables that change as user inputs values
    int attempts = 0;
    int values = 0;
    int total = 0;
    
    //adds the values input by the user and continues asking for an integer if another integer is input  
    while (scan.hasNextInt()) { 
        total += values;
        values = scan.nextInt(); 
        System.out.println("Enter an integer to continue or a non-integer value to finish. Then press return.");  
        attempts += 1;
    } 
    
    //ends the program when a non-integer is input and prints the number of attempts and the sum of all values
    String input = scan.next();      
    System.out.println ("You entered " + input + "!"); 
    System.out.println ("You had " + attempts + " attempts!"); 
    System.out.println("The sum of all your values is " + total);
} 

}

1 Answers

Try this.

import java.util.Scanner;

class Main {
  public static void main(String[] args) {

    Scanner scan = new Scanner(System.in); 
    System.out.println ("Enter an integer to continue or a non-integer value to finish. Then press return.");
    
    //placeholder variables that change as user inputs values
    int attempts = 0;
    String value;
    int total = 0;
    
    //adds the values input by the user and continues asking for an integer if another integer is input  
    for (;;) {

      value = scan.next();

      try {

        total += Integer.valueOf(value);
         attempts++;
        System.out.println ("Enter an integer to continue or a non-integer value to finish. Then press return."); 
            
      } 
        
      //ends the program when a non-integer is input and prints the number of attempts and the sum of all values
      catch (Exception e) {

        attempts++;
        System.out.println ("You entered " + value + "!"); 
        System.out.println ("You had " + attempts + " attempts!"); 
        System.out.println("The sum of all your values is " + total + "!");
        break;

      }
    }
    scan.close();
  }
}
Related