I have a method called countDirectSimilarity, in this method I want to call another method, but I find it difficult to call it, can you help me?
here the source code, i will call method name countAggrIntStrength
private double countDirectSimilarity(double[][] matrixEgoNetwork, int index) {
double sim=0;
for (int i = 0; i < matrixEgoNetwork.length; i++) {
//here the trouble
if (matrixEgoNetwork[i][0]==this.countAggrIntStrength(*here the error*) && matrixEgoNetwork[i][index]!=0) {
sim++;
}
}
return sim;
}
this is method that I want to call
public double countAggrIntStrength(Map<DTNHost, ArrayList<Double>> neighborsHist) {
double AggrIntStrength = 0;
double lambda = 0, sigma = 0;
for (Map.Entry<DTNHost, ArrayList<Double>> data : neighborsHist.entrySet()) {
lambda = data.getValue().get(0);
sigma = data.getValue().get(1);
AggrIntStrength = this.countAgrIntStrength(lambda, sigma);
}
return AggrIntStrength;
}
another problem is that the data structure that I want to enter into
this.countAggrIntStrength()
is in another class, can you help me?
Use static
public static double countAggrIntStrength...
And in your method do not need this.countDirectSimilarity, you can just directly call countDirectSimilarity method.
Get the data structure from the other class using a getter:
otherClassName.getMap()
Then pass it to your method within the first class, either within the method call:
countAggrIntStrength(otherClassName.getMap());
Or by saving it first:
Map<DTNHost, ArrayList<Double>> mapToPass = otherClassName.getMap();
countAggrIntStrength(mapToPass)
You'll need a getter in the other class:
public Map getMap(){
return variableThatStoresTheMap;
}
if you don't already have one.
Some data Structure class which holds neighborsHist map.
public class DataStructure {
Map<DTNHost, ArrayList<Double>> neighborsHist;
public Map<DTNHost, ArrayList<Double>> getNeighborsHist() {
return neighborsHist;
}
public void setNeighborsHist(Map<DTNHost, ArrayList<Double>> neighborsHist) {
this.neighborsHist = neighborsHist;
}
public void businessLogicFunc() {
//business logic function.
...
}
}
Inside your countDirectSimilarity function call get method.
public DataStructure dataStructure;
private double countDirectSimilarity(double[][] matrixEgoNetwork, int index) {
double sim=0;
for (int i = 0; i < matrixEgoNetwork.length; i++) {
if (matrixEgoNetwork[i][0]==this.countAggrIntStrength(dataStructure.getNeighborsHist()) &&
matrixEgoNetwork[i][index]!=0) {
sim++;
}
}
return sim;
}
Related
I want to make a simple program to compare how long time takes rewrite and print out collection of Strings by `for loop`, `foreach` or `stream`. String is sentence where it replaces "i" by "y". In my case I made `count()` where I set to count `stream()` method but I want to make universal measuring method. But i dont know how to do it... It should works like: in Main class is `counter(forLoop);` It should call `forLoop();` from Method class `counter(forEach);` It should call `forEach();` from Metrod class`counter(stream);` It should call ` stream();` From Method class IDont know how to pass method as a parameter
I have class where are those metods:
import java.util.*;
import java.util.stream.*;
public class Methods {
private List<String> sentence = new ArrayList<>();
private String oldLetter = "i";
private String newLetter = "y";
private String methodType;
public String getMethodType() {
return methodType;
}
//making a collection with String
public void setSizeOfCollection(int size){
for (int i = 0; i < size; i++) {
sentence.add("Siti Zbinek plitce zvikal sirovi pelinek.");
}
}
public void forLoop(){
methodType = "For loop";
for (int i = 0; i < sentence.size(); i++) {
for (int j = 0; j < sentence.size(); j++) {
String replaceLetters = sentence.get(j);
replaceLetters = replaceLetters.replaceAll(oldLetter, newLetter);
sentence.set(j, replaceLetters);
}
System.out.println(sentence.get(i));
}
}
public void forEach(){
methodType = "For each";
String replacedLetters = "";
for(String oneLine: sentence){
for(String originalLetters: sentence){
replacedLetters = originalLetters.replaceAll(oldLetter,newLetter);
}
System.out.println(replacedLetters);
}
}
public void stream(){
methodType= "Stream";
sentence.stream()
.map(e->e.replaceAll(oldLetter,newLetter))
.collect(Collectors.toList())
.forEach(System.out::println);
}
}
This is count() that works fine, but only for method stream(). In comment is my imagine how it should be. But I dont know how it do by Java :(
import org.apache.commons.lang.time.*;
public class Counter {
private Methods methods;
private String methodType;
private StopWatch stopWatch = new StopWatch();
long timeTaken = 0;
//here should be something like any method as a parameter XXX xxx
// public void count(Methods methods XXX xxx)
public void count(Methods methods){
stopWatch.start();
// here sould be something what call any function by your choice, not only stream()
// methods.xxx;
methods.stream();
stopWatch.stop();
timeTaken= stopWatch.getTime();
System.out.println(methods.getMethodType()+" takes "+ timeTaken + " ms." );
}
}
And finally Main class
public class Main {
public static void main(String[] args) {
Methods methods = new Methods();
Counter counter = new Counter();
methods.setSizeOfCollection(10000);
counter.count(methods);
//here should be finally three times method, with different parameters:
// counter.count(methods, forEach);
// counter.count(methods, forLoop);
// counter.count(methods, stream);
}
}
Any advice please?
All your methods have the signature void(). Consequently, a reference to each method can be stored in a Runnable instance.
public void count(final Runnable method) {
stopWatch.start();
method.run();
stopWatch.stop();
timeTaken= stopWatch.getTime();
System.out.println(methods.getMethodType()+" takes "+ timeTaken + " ms.");
}
And then call as:
final Methods methods = new Methods();
final Counter counter = new Counter();
methods.setSizeOfCollection(10000);
counter.count(methods::stream); // or count(() -> methods.stream());
counter.count(methods::forEach); // count(() -> methods.forEach());
counter.count(methods::loop); // count(() -> methods.loop());
To be able to use method refs or lambdas, you need to have at least Java 8. For earlier Java versions, you would need to implement Runnable with an anonymous class, e.g.
counter.count(new Runnable() {
#Override public void run() { methods.stream(); }
});
or look up the methods by name via Reflection, but Reflection is usually the slowest option.
PS. Note however that your way of measuring method execution times is flawed; see How do I write a correct micro-benchmark in Java? for directions. This answer only explains the part of passing "methods" to another method.
you could pass the method name as a string and look for it with reflexion.
I'm a beginner in Java and I struggle a bit. I have 3 classes and I want the ArrayList from one class to access a method from another class. How can I do that?
Here is the method I want to retrieve the method from:
private void markAsUpdated()
{
this.needsUpdate = true;
}
Here is the arrayList:
public int getNumberOfUpdatedSites()
{
for (int i = 0; i < webSite.size(); i++)
{
if (webSite.get(i))
{
}
}
Both code belong to two different classes.
I'm stuck at the iteration part.
Basically it needs to return all the sites that are already updated. I have a UML diagram if needed I can provide it. Thanks in advance.
Assuming that Website class is as follows:
public class Website {
private boolean needsUpdate;
public boolean isNeedsUpdate() {
return needsUpdate;
}
public void markAsUpdated() {
this.needsUpdate = false;
}
}
Then in your other class, you just need to call the public isNeedsUpdate method to check if it needs to be updated or not. This means that in your other class you can do as follows:
public int getNumberOfUpdatedSites() {
int updatedWebsitesCount = 0;
for (int i = 0; i < webSite.size(); i++) {
if (!webSite.get(i).isNeedsUpdate()){
updatedWebsitesCount++;
}
}
return updatedWebsitesCount;
}
Just trying to run through some code for an assignment I'm doing. It is probably simple but for the life of me I can't figure out why I get the above error at the first line
(public WaterLog.......).
Later I want to pass it this line:
[ log = new WaterLog(8, damCapacity); ]
Any help would be appreciated, I am new to this sorry.
public class WaterLog(Integer windowSize, Integer maxEntry) {
private Integer size = windowSize;
private Integer max = maxEntry;
private ArrayList theLog(int windowSize);
private int counter = 0;
public void addEntry(Integer newEntry) throws SimulationException {
theLog.add(0, newEntry);
counter++;
}
public Integer getEntry(Integer index) throws SimulationException {
If (thelog.isEmpty() || thelog.size() < index) {
return null;
}
return thelog.get(index);
}
public Integer variation() throws SimulationException {
int old, recent = 0;
recent = thelog.get(0);
old = thelog.get(thelog.size-1);
return recent-old;
}
public Integer numEntries() {
return counter;
}
}
Assuming SimulationException is defined correctly:
class WaterLog{
private Integer size;
private Integer max ;
private ArrayList<Integer> theLog; //parameterize your lists
private int counter = 0;
public WaterLog(Integer windowSize, Integer maxEntry) //this is the behavior you were looking for
{
this.size = windowSize;
this.max = maxEntry;
theLog = new ArrayList<Integer>(windowSize);
}
public void addEntry(Integer newEntry) throws SimulationException {
theLog.add(0, newEntry);
counter++;
}
public Integer getEntry(Integer index) throws SimulationException {
if (theLog.isEmpty() || theLog.size() < index) { //Java is case sensitive
return null;
}
return theLog.get(index);
}
public Integer variation() throws SimulationException {
int old, recent = 0;
recent = theLog.get(0);
old = theLog.get(theLog.size()-1); //again, watch case, also size is a method
return recent-old;
}
public Integer numEntries() {
return counter;
}
}
See the comments I added.
EDIT: To explain a bit further what was going on, let's take a look at what you were doing.
public class WaterLog(Integer windowSize, Integer maxEntry) {
private Integer size = windowSize;
private Integer max = maxEntry;
private ArrayList theLog(int windowSize);
private int counter = 0;
You seem to have confused a class with a constructor. The variables you defined were attributes, which was correct. You needed to use the syntax I showed in my answer to create a constructor. For that same reason, you don't have access to variables like windowSize. To remedy this, we allow them to still be defined outside the constructor, but assigned values inside it, where we have access to windowSize and maxEntry.
If you want to pass some parameters to this class you need a constructor. By default Each and EVERY class comes with a default constructor - which is there, you just don't see it ( but can declare it). What you can then do is make an overloaded construcotr ( which takes some arguments ) and this is what you want so..
if you have a class
class WaterLog {
// no constructor
}
the above is really a
class WaterLog {
public WaterLog() {
// this is the constructor - if you do not declare it its still here, you just dont see it. Ofcourse you have option to declare it.
}
}
The overloaded constructor is something like this
class WaterLog {
public WaterLog() {
//default constructor
}
public WaterLog(Integer int, String string, etc...) {
//overloaded constructor
}
}
and the above is what you need in order to pass arguments to this class constructor. I am not briliant at explaining things but if you need more clarification just let me know :)
I have some code here that calculates the maxValue of an array:
public static int getMaxValue(int[] marks){
int maxValue = marks[0];
for(int i=1;i < marks.length;i++){
if(marks[i] > maxValue){
maxValue = marks[i];
}
}
return maxValue;
}
I want to display the maxvalue when a button is pressed by the user. This is what I have so far but it does not work:
private void analyzeButtonActionPerformed(java.awt.event.ActionEvent evt) {
maxValue mv = new maxValue ();
analyzeTextArea.setText("Maximum:" + maxValue.toString());
}
Thanks for any help!
Since your method is static, you can simply use the name of the class that contains it to call it.
analyzeTextArea.setText("Maximum:" + YourClassNameHere.getMaxValue());
You can't instantiate a method.
I think you're looking for something like this...
private void analyzeButtonActionPerformed(java.awt.event.ActionEvent evt) {
analyzeTextArea.setText("Maximum:" + getMaxValue(arrayOfValues));
}
To call a method, you don't need to do anything other than call methodName(inputValues) - you can't create an instance of the method by doing new methodName()
If the method is in a different class, and it is a static method like your case, you can do this...
private void analyzeButtonActionPerformed(java.awt.event.ActionEvent evt) {
analyzeTextArea.setText("Maximum:" + MyClass.getMaxValue(arrayOfValues));
}
Otherwise if the method is in a different class and it isn't static, then you create an instance of the class first, then call the method...
private void analyzeButtonActionPerformed(java.awt.event.ActionEvent evt) {
MyClass example = new MyClass();
analyzeTextArea.setText("Maximum:" + example.getMaxValue(arrayOfValues));
}
I have the following method that I would like to test, it simply increments an int if a Boolean condition is true:
public void incrementIfConditionMet(Boolean personCheckedIn) {
int peopleInHotel=0;
if (personCheckedIn==true){
peopleInHotel++
}
}
I am very new to unit testing in Java. How can I unit test this to check if the int has been incremented or not?
Currently your value of peopleInHotel cannot be accessed outside the method, as it was created internally. If you want to access it, you should do the following:
private int peopleInHotel=0;
public int getPeopleInHotel() {
return peopleInHotel;
}
public void incrementIfConditionMet(Boolean personCheckedIn) {
if (personCheckedIn){
peopleInHotel++
}
}
Now in your test class, you can check by calling getPeopleInHotel();
So the test case would be:
int initalValue = classInstance.getPeopleInHotel();
classInstance.incrementIfConditionMet(true);
assertEquals(classInstance.getPeopleInHotel(), initalValue +1);
This would also fix your issue where you don't keep the value once the method has been ran. At the moment, in your current code setup, your variable of peopleInHotel is discarded after you've finished with the method.
int peopleInHotel=0;
public void incrementIfConditionMet(Boolean personCheckedIn) {
if (personCheckedIn==true){
peopleInHotel++
}
}
public int getPeopleInHotel() { //test the returned value after you've incremented
return peopleInHotel;
}
Try like this:
public class Hotel {
private int peopleInHotel = 0;
//a constructor...
public int getPeopleInHotel() {
return this.peopleInHotel;
}
public void incrementIfConditionMet(Boolean personCheckedIn) {
if (personCheckedIn==true){
peopleInHotel++
}
}
}
In your Unit-Test, you now can do something like that:
//defining your TestCase
Hotel hotel = new Hotel();
int initValue = hotel.getPepleInHotel();
hotel.incrementIfconditionmet(true);
assertEquals(hotel.getPeopleInHotel(),initValue+1);