Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.Scanner;
- public class FindPair {
- int totalNum; //Total number
- Integer[] list; //The list of integers
- int size;
- //Test functions
- public static void main(String args[]){
- FindPair demo = new FindPair(4);
- demo.readUserInput();
- demo.displayResult();
- }
- //Constructor
- public FindPair(int listSize){
- totalNum = 0;
- size = listSize;
- list = new Integer[size];
- }
- /**
- * Validate the total number that entered by user
- * @param num the number that inputed by user
- * @return true for valid number, false for invalid number
- */
- private boolean NumVal(String num)
- {
- //Check whether the input is integer
- try {
- Integer.parseInt(num);
- }
- catch(NumberFormatException | NullPointerException e) {
- System.out.println("Please enter a valid integer");
- return false;
- }
- //Check whether the number is greater than 0
- if(Integer.parseInt(num) < 1) {
- System.out.println("Please enter a positive number: ");
- return false;
- }
- else
- return true;
- }
- /**
- * Read user input for the list and total number
- */
- public void readUserInput()
- {
- Scanner sc = new Scanner(System.in);
- //Catch the exception when user input the number
- System.out.println("Please enter the first numer as the sum: ");
- String num = sc.nextLine();
- //valid the number, if the result is false than let the user enter the number again
- while(!NumVal(num)) {
- num = sc.nextLine();
- }
- totalNum = Integer.parseInt(num);
- //Read user input for list
- for(int i = 0; i < size; i++)
- {
- System.out.println("Please enter the " + (i+1) + " number in the list: ");
- num = sc.nextLine();
- //Validation of number
- while(!NumVal(num)) {
- num = sc.nextLine();
- }
- list[i] = Integer.parseInt(num);
- }
- sc.close();
- }
- /**
- * Find pairs from the list
- * @return the array list of pairs
- */
- private ArrayList<Integer> findPair()
- {
- ArrayList<Integer> result = new ArrayList<Integer> ();
- //Find pairs by two loops
- for(int i = 0; i < size; i++)
- {
- for(int j = i + 1; j < size; j++)
- {
- if (list[i] + list[j] == totalNum && list[i] != list[j] && !result.contains(list[i]))
- {
- result.add(list[i]);
- result.add(list[j]);
- break;
- }
- }
- }
- return result;
- }
- /**
- * Display the pairs that have the sum of total number
- */
- public void displayResult()
- {
- //Invoke the method of findPair
- ArrayList<Integer> result = findPair();
- System.out.println("Result(s): ");
- for(int i = 0; i < result.size() - 1; i+=2)
- {
- System.out.print("[" + result.get(i) + ", " + result.get(i+1) + "] ");
- }
- }
- }
Add Comment
Please, Sign In to add comment