-1

How can I write a test to print this result?

package leetcode_one_twenty;

import java.util.HashMap; // HashMap package

public class Two_Sum {

    public int[] twoSum(int[] numbers, int target) {
        HashMap<Integer, Integer> map = new HashMap<>();

        for (int i = 0; i < numbers.length; i++) {
            if (map.get(numbers[i]) != null) {
                int[] result = {map.get(numbers[i]) + 1, i + 1};
                return result;
            }
            map.put(target - numbers[i], i);
        }

        int[] result = {};
        return result;
    }

    public static void main(String[] args) {

        // How can I write a test to print this result? THX!
    }

}
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Mars_Tina
  • 33
  • 1
  • 10
  • 1
    Either you can use junit, or you can provide some test-data within your main(string...) method. Odd question. – vegaasen Nov 30 '17 at 08:21

2 Answers2

1

Make your twoSum method static, and call it with values from your main method:

int[] myArray = {1,2,3};
int target = 5;
System.out.println(Arrays.toString(twoSum(myArray, target)));
achAmháin
  • 4,176
  • 4
  • 17
  • 40
  • Thank you so much! – Mars_Tina Nov 30 '17 at 08:22
  • @user635967 no problem - obviously change the values around to whatever you need to suit your program. – achAmháin Nov 30 '17 at 08:24
  • Sorry, may I ask more question? Why should the twoSum method static? Thank you so much! – Mars_Tina Nov 30 '17 at 08:30
  • @Mars_Tina yep - if you don't make it static, your compiler will throw an error saying you can't reference a non-static method from a static context; read more here: https://stackoverflow.com/questions/290884/what-is-the-reason-behind-non-static-method-cannot-be-referenced-from-a-static – achAmháin Nov 30 '17 at 08:47
  • 1
    Got it ~ I try this several times and finally figure this out. Thank you so much! – Mars_Tina Nov 30 '17 at 08:51
0

I'm not really sure what are you exactly trying to do. Why not try System.out.println() and toString()?

jeevaa_v
  • 423
  • 5
  • 14