gpt4 book ai didi

java - 两个数组中最大的元素

转载 作者:太空宇宙 更新时间:2023-11-04 12:00:21 25 4
gpt4 key购买 nike

我正在尝试编写一个程序来查找两个数组中最大的元素。如果数组包含相似的元素,它将返回相互元素中最高的。如果数组不包含相似元素,则返回 -1。我已经完成了 90% 的程序。我设法返回了最高的数字,我只是不知道如何返回 -1,因为我们只能执行一个 return 语句!有什么帮助吗?

    public class finalLargestInCommon
{
public static void main(String [] args)
{
//array declaration
int [] array1 = {3, 8, 5, 2, 7, 9};
int [] array2 = {5, 1, 22, 7, 2, 15, 3};
int [] array3 = {35, 12, 19, 35, 45};
int [] array4 = {55, 99, 12};
int [] array5 = {33, 11, 77, 44, 55};
int [] array6 = {99, 88, 222, 66, 1000};

System.out.println(LargestInCommon(array1, array2));
System.out.println(LargestInCommon(array3, array4));
System.out.println(LargestInCommon(array5, array6));



}

public static int LargestInCommon (int [] a, int [] b)
{
//variable declaration
int i = 0;
int k = 0;
int greatest = 0;
int notPresent = -1;

for(i = 0; i < a.length; i++)
{
for(k = 0; k < b.length; k++)
{
if(a[i] == b[k])
greatest = a[i];

}
}

return(greatest);


}


}

最佳答案

greatest 初始化为 -1 并返回 greatest ,就像您所做的那样。如果您的 if 条件未命中(这意味着不存在两个相似的数字)greatest 将返回值 -1。

public static int LargestInCommon (int [] a, int [] b)
{
//variable declaration
int i = 0;
int k = 0;
int greatest = -1;

for(i = 0; i < a.length; i++)
{
for(k = 0; k < b.length; k++)
{
if(a[i] == b[k])
greatest = a[i];

}
}

return greatest;


}

关于java - 两个数组中最大的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40966929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com