我有一个包含数千个单行句子的ArrayList,我想搜索大约50个关键词。如果它包含这些关键字之一,我希望它将对应于该关键字的双精度数添加到数组中。一旦检查了所有数组的匹配,我想总结数组的总和。
目前我有类似的东西,除了arraylist和双变量列表要大得多:
import java.util.ArrayList;
public class searchArrayList {
public static void main(String[] args){
String subject2 = "The color of the ball is blue.";
String subject3 = "The building is white.";
String subject4 = "Red is my favorite color.";
String subject5 = "Black and blue are the team colors";
ArrayList<Double> arrlist = new ArrayList<Double>();
ArrayList<Double> difflist = new ArrayList<Double>();
double Black = 10.1;
double Blue = 1.6;
double Red = 11.4;
double White = 4.3;
String[] subjectArray = {subject2,subject3,subject4,subject5};
for (String subjects: subjectArray)
{
if (subjects.toUpperCase().contains("BLUE"));
System.out.println(Blue+ "Blue ");
arrlist.add(Blue);
if (subjects.toUpperCase().contains("BLACK"));
System.out.println(Black+" Black");
arrlist.add(Black);
if (subjects.toUpperCase().contains("WHITE"));
System.out.println(White+" White");
arrlist.add(White);
if (subjects.toUpperCase().contains("RED"));
System.out.println(Red+" Red");
arrlist.add(Red);
}
System.out.println(sum(arrlist));
}
public static double sum(ArrayList<Double>arrlist)
{
double result = 0;
for (double number:arrlist)
result += number;
return result;
}
}
这就是我需要它,但我想知道是否有更好或更直观的方法来做到这一点?我可以将if语句组合到单个对象/类中,然后调用该类来搜索数组吗?使用switch语句会更好吗?我尝试使用正则表达式来进行搜索,但是.contains似乎也能正常工作。
答案 0 :(得分:3)
只需使用包含关键字 - 双关联的数组(或集合),并遍历此数组:
public class Keyword {
private String value;
private double points;
...
}
private Keyword[] keywords = new Keyword[] {
new Keyword("BLUE", 1.6),
new Keyword("BLACK", 10.1),
...
}
for (String subject : subjectArray) {
for (Keyword keyword : keywords) {
if (subject.toUpperCase().contains(keyword.getValue())) {
System.out.println(keyword.getPoints() + " " + keyword.getValue());
arrlist.add(keyword.getPoints());
}
}
}
答案 1 :(得分:0)
我没有足够的声誉来发表评论,但这不会比将字符串转换为大写更有效吗?
org.apache.commons.lang3.StringUtils.containsIgnoreCase(String, String)
图书馆的文档:http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html