简体   繁体   中英

How to compare the values of objects of a class

I have made an inner class- in and its constructor. In a function func() I am passing values of battery and time to the constructor as entered by the user using a Scanner, and this function is called multiple times.I want to compare the different values of battery as input by user using the class objects and then print them. lets say func is called 4 times and i pass different battery values each time. I want to check whether difference between them is greater then 1.. IF yes then print that battery value. Eg: 1st call- (98,2) 2nd call-(97,4) 3rd call(95,9) 4th call(94,11). Here difference between 2nd and 3rd call's battery level is greater than 1, so i'll have to print the initial one ie 2nd call battery level and its corresponding time.How can I code that?

public class Out {

Scanner sc = new Scanner(System.in)

class in {
    int x, int y;

    in(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

in obj = new in(0, 0); //call this obj inside func

public void func() {
    int battery = sc.nextInt();
    int time = sc.nextInt();
    in inner = new in(battery, time);


}

I cannot use an arraylist as func() will be called more than a thousand times so to avoid memory wastage. I have made an object obj with values 0,0. I will compare obj's battery value to in's battery value(compare whether the difference in battery value is more than 1 or not if yes then print the previous battery value) and after that update the obj's battery value to the current value of battery(passed by user)..

Create a function to compare two objects based on what you want to measure.

public boolean InEqual(in obj1, in obj2)
{
    if(obj1.x - obj2.x > 1)
      return true;
    else
      return false;
}

or you can return the difference between the values

public int Difference(in obj1, in obj2)
{
    if(obj1 != null && obj2 != null)
      return obj1.x - obvj2.x;
    else
      return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM