I am trying to write an if-else statement in Java with 7 different variables, initialized and declared as integers. I want to write an if-else statement that says "You win!" if their sum equals 21, but says "Sum does not equal 21, exiting program." otherwise. If the sum does not equal 21, then I would need to close the keyboard as well.
Below is your code:
import java.util.Scanner;
public class SumOfNumbers {
public static void main(String[] args) {
// initializing keyboard
Scanner keyboard = new Scanner(System.in);
// declaring 7 different variables
int var1, var2, var3, var4, var5, var6, var7;
// getting input from user for 7 variables
System.out.print("Enter number #1: ");
var1 = keyboard.nextInt();
System.out.print("Enter number #2: ");
var2 = keyboard.nextInt();
System.out.print("Enter number #3: ");
var3 = keyboard.nextInt();
System.out.print("Enter number #4: ");
var4 = keyboard.nextInt();
System.out.print("Enter number #5: ");
var5 = keyboard.nextInt();
System.out.print("Enter number #6: ");
var6 = keyboard.nextInt();
System.out.print("Enter number #7: ");
var7 = keyboard.nextInt();
// calculating sum
int sum = var1 + var2 + var3 + var4 + var5 + var6 + var7;
// printing result
if (sum == 21) {
System.out.println("You win!");
} else {
System.out.println("Sum does not equal 21, exiting program.");
}
// closing keyboard
keyboard.close();
}
}
Output
Enter number #1: 21
Enter number #2: 45
Enter number #3: 1
Enter number #4: 6
Enter number #5: 8
Enter number #6: 14
Enter number #7: 54
Sum does not equal 21, exiting program.
Get Answers For Free
Most questions answered within 1 hours.