In: Computer Science
TwoNumbersAddTo 1. write a class called TwoNumbersAddTo with a main method 2. the program asks for a number (lets call it "goal"). 3. then the program reads at most 20 integers (i.e. any number of integers from 0 to 20) 4. the program stops reading when user enters 0 or user has entered 20 numbers. 5. program prints all the pairs that add up to goal. 6. Notice that if goal is 5, for example, 1 + 4 and 4 + 1 are the same pair. Your program should report only one. 7. The pairs should be printed such that the first number is in the same order in which it was entered. For example: % java TwoNumbersAddTo enter goal: 5 enter at most 20 integers, end with 0: 1 2 3 4 5 0 1 + 4 = 5 2 + 3 = 5 % java TwoNumbersAddTo enter goal: 5 enter at most 20 integers, end with 0: 4 3 2 1 0 4 + 1 = 5 3 + 2 = 5
import java.util.Scanner;
public class TwoNumbersAddTo {
public static void main(String[] args) {
int arr[] = new int[20];
int goal;
int len = 0;
Scanner sc = new
Scanner(System.in);
//reading goal from user
System.out.println("Enter goal:
");
goal = sc.nextInt();
int n = 0;
//reading numbers from user
System.out.println("enter at most
20 integers, end with 0:");
for (int i = 0; i < 20; i++)
{
n =
sc.nextInt();
arr[len++] =
n;
if (n == 0)
{
break;
}
}
//finding some of the numbers
for (int i = 0; i < len; i++)
{
for (int j = i +
1; j < len; j++) {
//check if sum is =goal
if (arr[i] + arr[j] == goal) {
System.out.println(arr[i] + "
+ " + arr[j] + " = " + (arr[i] + arr[j]));
}
}
}
}
}
Note : Please comment below if you have concerns. I am here to help you
If you like my answer please rate and help me it is very Imp for me