0

I am creating a program where the user is prompted to enter a positive integer. The program accepts integers until -1 is entered. After the user entered -1, the integers entered and the sum of the integers are displayed. If the user tries to enter a negative number, the program tells the user that it is an invalid input and to enter a positive integer. The problem that I am having is at the very end of the program. It doesn't let me input y(yes) or (no) even though it should let me, since I specifically added another = input.nextLine();. It just completes the program. How do I have it so it will read the user input of y(yes) or n(no) and let the user enter another set of integers?

import java.util.Scanner;

 public class InputSum
 {
    public static void main (String[] args)
     {
  int integer = 0;
  int sum = 0;
  int count = 0;
  String string = " ";
  String another = "y";

  Scanner input = new Scanner(System.in); // scanner object

  while (another.equalsIgnoreCase("y")) {
     while (integer != -1){
        count = count + 1;

        System.out.print ("Enter a positive integer (-1 to exit): ");
        integer = input.nextInt();

        while (integer < -1){
           System.out.print ("Invalid input was entered. Enter a positive integer (-1 to exit) : ");
           integer = input.nextInt();
        } 

        if (integer == -1)
           continue;
        sum = sum + integer;
        string = string + integer + ", ";

     }


     if (count == 1){
        System.out.println ("\n" + "No values were entered");
        System.out.println ("The Sum: " + sum);
     }
     else
        System.out.println ("\n" + "Entered value: " + string.substring(0, string.length()-2) + "\n" + "The Sum: " + "\t" + sum);


     System.out.print ("Run the program again (y/n)?: ");
     another = input.nextLine();

     }
   }
 }
Iamat8
  • 3,646
  • 8
  • 22
  • 29
j2k1218
  • 13
  • 4
  • That's the problem. It doesn't let me enter anything. It asks the user if they want to run the program again and it ends the program, without letting the user enter anything. – j2k1218 Oct 05 '15 at 06:04
  • this is because you have a new-line in the buffer from after entering the integer. – aioobe Oct 05 '15 at 06:09
  • 1
    go throught this http://stackoverflow.com/questions/13102045/skipping-nextline-after-using-next-nextint-or-other-nextfoo-methods leave a comment after going through if still confusing then i will post the changes for your code – Shadow Droid Oct 05 '15 at 06:11
  • Okay so i tried to fix my code, but no luck. Im still kind of confused – j2k1218 Oct 05 '15 at 06:21
  • Nevermind, I understood it and I fixed my code. Now, instead of the program letting the user enter a new set of numbers, it displays the same output overtime I enter "y". – j2k1218 Oct 05 '15 at 06:43

0 Answers0