Quote (Hyperdimension @ Apr 9 2020 03:05am)
there are a lot of errors in your code.
first of all, you are not even calling your twoSum method and you are not doing anything with the returned result.
second mistake : you do i++ at the end of the for loop, but the for loop already does i++ so you're skipping an index every iteration
third mistake : to return an array of values, use return new int[] {1, i}
fourth mistake : your twosum function should be static
fifth mistake : if you had 6 in your numArray, it would return that index twice because you look for every result + itself
sixth mistake : I think compiler will not let you compile if you dont put a dummy return at the end of your function, but I don't have a java compiler so I can't test
Yeah thanks, it wasn't complete code yet, just had 1 specific question.... But i actually got some modified code before i read your answer......
Code
package com.company;
import java.util.Arrays;
import java.util.Scanner;
public class TwoNumbers {
public static void main(String[] args) {
int[] numArray = {4, 5, 7, 9, 3};
int target = 8;
int[] sumArray = twoSum(numArray, target);
System.out.println(Arrays.toString(sumArray));
}
public static int[] twoSum(int[] nums, int target) {
for(int i=0; i<nums.length; i++) {
if(nums[0] + nums[i] == target) {
return new int[] {0, i};
} else if(nums[1] + nums[i] == target) {
return new int[] {1, i};
} else if(nums[2] + nums[i] == target) {
return new int[] {2, i};
} else if(nums[3] + nums[i] == target) {
return new int[] {3, i};
} else if(nums[4] + nums[i] == target) {
return new int[] {4, i};
}
}
return new int[0];
}
}
Granted still has some issues but i'm not done yet either.... actually doing something new now....
Code
package com.company;
import java.util.Arrays;
public class AnyArrayIndexNumbers {
public static void main(String[] args) {
int[] numArray = {4, 5, 7, 9, 3};
int target = 12;
int[] sumArray = twoSum(numArray, target);
System.out.println(Arrays.toString(sumArray));
}
public static int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums.length; j++) {
if(nums[i] + nums[j] == target) {
return new int[] {i, j};
}
}
}
return new int[0];
}
}
Fixing a bug with this code atm