2016-01-20 52 views
0

我需要创建一个方法来检查数组中的每个元素以查看它是真还是假,每个元素包含一个化合物的质量,公式,面积等几个值,以及总共有30个化合物(所以该阵列有30个元素)。我需要一个算法来询问是否质量和面积> 5 =真。检查我的数组元素是否符合要求

我的属性的类的样子:

public void addProperty (Properties pro) 
     { 
     if (listSize >=listlength) 
     { 
     listlength = 2 * listlength; 
     TheProperties [] newList = new TheProperties [listlength]; 
     System.arraycopy (proList, 0, newList, 0, proList.length); 
     proList = newList; 
     } 
     //add new property object in the next position 
     proList[listSize] = pro; 
     listSize++; 

     } 

     public int getSize() 
     { 
     return listSize; 
     } 
     //returns properties at a paticular position in list numbered from 0 
     public TheProperties getProperties (int pos) 
     { 
     return proList[pos]; 
     } 
     } 

,并使用我的getter/setter方法从TheProperties后,我把所有的信息在阵列中使用以下;

TheProperties tp = new properties(); 

string i = tp.getMass(); 
String y = tp.getArea(); 
//etc 
theList.addProperty(tp); 

然后我使用以下内容保存文件的输出;

StringBuilder builder = new StringBuilder(); 

    for (int i=0; i<theList.getSize(); i++) 
    { 
     if(theList.getProperties(i).getFormatted() != null) 
     { 
      builder.append(theList.getProperties(i).getFormatted()); 
      builder.append("\n"); 
     } 
    }   

    SaveFile sf = new SaveFile(this, builder.toString()); 

我只是不能工作,如何单独询问每种化合物对他们是否达到价值与否,阅读文件并具有然后把它保存了工作每一个的值,我可以写一个如果声明为检查要求,但如何实际检查每种化合物的元素是否符合要求?我想尽我所能说出最好的,我仍然在努力解决我相当差的Java技能。

+0

一件事我建议是定义为每个参数的阵列,例如一个阵列为质谱,一个阵列区域等,然后为每个阵列的第一个元素表示第一对象。你有更多的控制权。 如果您使用的是Java 8,我建议您检查并行数组:http://mathbits.com/MathBits/Java/arrays/ParallelArrays.htm – Arsaceus

回答

0

不完全确定你在做什么之后,我发现你的描述很难理解,但是如果你想看看质量是否小于50并且面积大于5,那么简单的if语句就像这样,会做。

if (tp.getMass() < 50 && tp.getArea() > 5) {} 

虽然,你将再次,必须实例TP,并确保已经通过某种构造赋予其属性。

0

很多方法可以做到这一点,这使得很难回答。

你可以在创建时检查,甚至不添加无效的列表。这意味着你只需要循环一次。

如果您只是想将输出保存到文件中,而不做其他任何事情,我建议您将读取和写入组合到一个函数中。

Open up the read and the write file 
    while(read from file){ 
     check value is ok 
     write to file 
    } 
    close both files 

做这种方式的优点是:

  1. 你只遍历一次,而不是三次,所以它更快
  2. 你从来没有存储在内存中的整个列表,所以你可以处理真正的大文件,数千个元素。
0

万一要求的变化,您可以编写一个使用Predicate<T>方法,这是一个FunctionalInterface专为这种情况下(functionalInterfaces用Java 8中引入):

// check each element of the list by custom condition (predicate) 
public static void checkProperties(TheList list, Predicate<TheProperties> criteria) { 
    for (int i=0; i < list.getSize(); i++) { 
     TheProperties tp = list.get(i); 
     if (!criteria.apply(tp)) { 
      throw new IllegalArgumentException(
        "TheProperty at index " + i + " does not meet the specified criteria"); 
     } 
    } 
} 

如果你想检查,如果质量< 50和面积> 5,可编写:

checkProperties(theList, new Predicate<TheProperties>() { 

    @Override 
    public boolean apply(TheProperties tp) { 
     return tp.getMass() < 50 && tp.getArea() > 5; 
    } 

} 

这可以通过使用lambda表达式被缩短:

checkProperties(theList, (TheProperties tp) -> { 
    return tp.getMass() < 50 && tp.getArea() > 5; 
}); 
+0

谢谢,这真的很有趣,我会研究一下。 – Gem

相关问题