如何在Java数组中找到总和等于给定数字的所有元素对?
在Java数组中查找总和等于给定数的所有元素对-
将数组中的每个元素添加到所有其余元素(自身除外)。
验证总和是否等于所需数量。
如果为true,则打印其索引。
示例
import java.util.Arrays;
import java.util.Scanner;
public class sample {
public static void main(String args[]){
//从用户读取数组
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array that is to be created: ");
int size = sc.nextInt();
int[] myArray = new int[size];
System.out.println("Enter the elements of the array: ");
for(int i=0; i<size; i++){
myArray[i] = sc.nextInt();
}
//读号码
System.out.println("Enter the number: ");
int num = sc.nextInt();
System.out.println("The array created is: "+Arrays.toString(myArray));
System.out.println("indices of the elements whose sum is: "+num);
for(int i=0; i<myArray.length; i++){
for (int j=i; j<myArray.length; j++){
if((myArray[i]+myArray[j])== num && i!=j){
System.out.println(i+", "+j);
}
}
}
}
}输出结果
Enter the size of the array that is to be created: 8 Enter the elements of the array: 15 12 4 16 9 8 24 0 Enter the number: 24 The array created is: [15, 12, 4, 16, 9, 8, 24, 0] indices of the elements whose sum is: 24 0, 4 3, 5 6, 7
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短