1 package test_2_7; 2 3 import java.util.Scanner; 4 5 public class FindTarget { 6 7 public static int[] numArray = { 1, 2, 3, 4, 5, 6 }; 8 9 public static void main(String[] args) { 10 11 /** 12 * 给定一个整数数组和一个目标值 请你在该数组中找出和为目标值的两个整数,并返回他们的数组下标 13 */ 14 15 System.out.println("请输入要找寻的数字:"); 16 Scanner sc = new Scanner(System.in); 17 int num = sc.nextInt(); 18 19 findTarget(num); 20 21 } 22 23 private static void findTarget(int num) { 24 25 for (int i = 0; i < numArray.length; i++) { 26 for (int j = i + 1; j < numArray.length; j++) { 27 if (numArray[i] + numArray[j] == num) { 28 System.out.println("下标分别为" + i + "," + j); 29 } 30 } 31 } 32 33 } 34 35 }
结果如下:
请输入要找寻的数字:
5
下标分别为0,3
下标分别为1,2
[20-04-27][Self-test 16]Java FindTarget
原文:https://www.cnblogs.com/mirai3usi9/p/12790639.html