Advertisement
veronikaaa86

04. Sum of Two Numbers

Aug 6th, 2022 (edited)
737
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package nestedLoops;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class P04SumOfTwoNumbers {
  6.     public static void main(String[] args) {
  7.         Scanner scanner = new Scanner(System.in);
  8.  
  9.         int firstNum = Integer.parseInt(scanner.nextLine());
  10.         int secondNum = Integer.parseInt(scanner.nextLine());
  11.         int magicNum = Integer.parseInt(scanner.nextLine());
  12.  
  13.         int count = 0;
  14.         boolean isValid = false;
  15.         for (int i = firstNum; i <= secondNum; i++) {
  16.             for (int j = firstNum; j <= secondNum; j++) {
  17.                 count++;
  18.                 int sum = i + j;
  19.                 if (sum == magicNum) {
  20.                     isValid = true;
  21.                     System.out.printf("Combination N:%d ", count);
  22.                     System.out.printf("(%d + %d = %d)%n", i, j, sum);
  23.                     break;
  24.                 }
  25.             }
  26.             if (isValid) {
  27.                 break;
  28.             }
  29.         }
  30.         if (!isValid) {
  31.             System.out.printf("%d combinations - neither equals %d%n", count, magicNum);
  32.         }
  33.     }
  34. }
  35.  
Advertisement
RAW Paste Data Copied
Advertisement