43 lines
1.4 KiB
Java

/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package lab11_calebfontenot;
import java.util.Scanner;
/**
*
* @author caleb
*/
public class DoWhileEvent3 {
public static void main(String[] args) {
// Define variables
int sum = 0, numInt = 0;
String num = "This can be literally anything, it just needs to be initialized";
// Create scanner
Scanner input = new Scanner(System.in);
do {
System.out.print("Enter an integer to add to the sum (type x to exit): ");
num = input.nextLine(); //Read input from console
try {
numInt = Integer.parseInt(num); // Parse input as integer
} catch (Exception NumberFormatException) { // Catch invalid inputs
if (num.toLowerCase().equals("x")) {
break;
} else;
System.out.println("Invalid input!");
}
sum += numInt; // add integer to the sum
System.out.println("Current sum: " + sum);
} while (!(num.toLowerCase().equals("x")));
System.out.println("Exited loop!");
System.out.println("Final sum: " + sum);
}
}