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();
}
}
}