JAVA代码抽出通用的公共方法该怎么写,别的类调用
int[] arr = {2, 3, 4};
int a1, b2, c3;
Random random = new Random();
// 随机生成三个不重复的索引
int index1 = random.nextInt(arr.length);
int index2;
do {
index2 = random.nextInt(arr.length);
} while (index2 == index1);
int index3;
do {
index3 = random.nextInt(arr.length);
} while (index3 == index1 || index3 == index2);
// 将对应索引的值赋给变量
a1 = arr[index1];
b2 = arr[index2];
c3 = arr[index3];
int[] getrandomarr(int[] arr)
{
int a1, b2, c3;
Random random = new Random();
// 随机生成三个不重复的索引
int index1 = random.nextInt(arr.length);
int index2;
do {
index2 = random.nextInt(arr.length);
} while (index2 == index1);
int index3;
do {
index3 = random.nextInt(arr.length);
} while (index3 == index1 || index3 == index2);
int[] result = new int[3];
result[0] = arr[index1];
result[1] = arr[index2];
result[2] = arr[index3];
return result;
}
就把 公用的部分提炼出来 把需要的参数 提出来 调用的时候传进去就行了
具体实现(Java):
import java.util.ArrayList;
public class SimilarityUtil {
public static double similarity(ArrayList va, ArrayList vb) {
if (va.size() > vb.size()) {
int temp = va.size() - vb.size();
for (int i = 0; i < temp; i++) {
vb.add(0);
}
} else if (va.size() < vb.size()) {
int temp = vb.size() - va.size();
for (int i = 0; i < temp; i++) {
va.add(0);
}
}
int size = va.size();
double simVal = 0;
double num = 0;
double den = 1;
double powa_sum = 0;
double powb_sum = 0;
for (int i = 0; i < size; i++) {
double a = Double.parseDouble(va.get(i).toString());
double b = Double.parseDouble(vb.get(i).toString());
num = num + a * b;
powa_sum = powa_sum + (double) Math.pow(a, 2);
powb_sum = powb_sum + (double) Math.pow(b, 2);
}
double sqrta = (double) Math.sqrt(powa_sum);
double sqrtb = (double) Math.sqrt(powb_sum);
den = sqrta * sqrtb;
simVal = num / den;
return simVal;
}
}
要抽取一个通用的公共方法,可以按照以下步骤进行:
public class CommonUtils {
public static String removeVowels(String str) {
// 实现功能的代码
String vowels = "aeiou";
StringBuilder result = new StringBuilder();
for (char c : str.toCharArray()) {
if (vowels.indexOf(c) == -1) {
result.append(c);
}
}
return result.toString();
}
}
public class OtherClass {
public static void main(String[] args) {
String str = "They are students.";
String result = CommonUtils.removeVowels(str);
System.out.println(result);
}
}
输出结果为:Thy r stdnts.
通过以上步骤,我们创建了一个通用的公共方法removeVowels,用于移除字符串中的元音字母。然后在其他类中调用该方法进行实际的操作。可以根据实际需求,在公共方法中添加参数和返回值来实现不同的功能。
注意:在创建通用公共方法时,需要考虑方法的输入参数和返回值类型。根据实际需求进行定义和实现。以上例子仅供参考。