Print String ArrayList in decimal and binary format - java

I have an ArrayList that I want to print in decimal and binary format.
Current output: decimal: S:2 S:3 S:3 S:3 S:1 S:2
Expected:
decimal: 2 3 3 3 1 2
binary : 10 11 11 11 1 10
Any help is appreciated on how I can accomplish this.
I get this error "Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method toBinaryString(int) in the type Integer is not applicable for the arguments (List)at generics.ExampleGenerics.main(ExampleGenerics.java:50)"
I am learning generics, do I need to cast an int to the string array to get this to work? or am I way off?
public class ExampleGenerics {
public static void main(String[] args) {
List < Square > squareList = new ArrayList < > (Arrays.asList(new Square(1),
new Square(2), new Square(2), new Square(3), new Square(3), new Square(3)));
System.out.println("original squareList: " + squareList);
Collections.rotate(squareList, -2);
System.out.println("rotated list: " + squareList);
System.out.println(Integer.toBinaryString(squareList)); //error
}
}
public class Square {
private int side;
public Square(int side) {
this.side = side;
}
public int getSide() {
return side;
}
public void setSide(int side) {
this.side = side;
}
#Override
public String toString() {
return "S:" + side;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + side;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Square))
return false;
Square other = (Square) obj;
if (side != other.side)
return false;
return true;
}
}

The issue is that you're attempting to pass your List to the method Integer.toBinaryString(). However, this method doesn't take Lists, it takes ints. This is stated in the exception: "The method toBinaryString(int) in the type Integer is not applicable for the arguments (List)".
Instead of passing in your List, you need to loop through it and pass in the int for each Square object. So instead of doing this:
System.out.println(Integer.toBinaryString(squareList));
Do this:
for(Square square:squareList){
System.out.println(Integer.toBinaryString(square.getSide()));
}

Related

OOP in Java: problem with constructor and methods

I am new to Java and I am trying to write a class with constructors and methods that adds and divides two numbers, and also compares if one object is larger or equal than the other. But I am getting an error: The method plus(int) in the type Compare is not applicable for the arguments (Compare). what's wrong?
Here's the code:
public class Compare {
// fields
private int number;
private int plus;
private double div;
// constructor
public Compare (int n) {
number = n;
}
public int plus (int x) {
return this.number + x;
}
public int div (int x) {
return this.number / x;
}
public boolean isLargerThan (int x) {
return this.number > x;
}
public boolean isEqualTo (int x) {
return this.number == x;
}
public static void main(String[] args) {
Compare n1 = new Compare(9);
Compare n2 = new Compare(4);
Compare sum = n1.plus(n2);
Compare div = n1.div(n2);
boolean check1 = sum.isLargerThan(n1);
boolean check2 = div.isLargerThan(n2);
boolean check3 = div.isEqualto(sum);
}
}
The requirement is to create sum and div objects using Compare constructor that will be equal to n1 plus n2, with plus method or division as applicable.
It may be that here you want a new Compare, containing the sum.
public Compare plus (int x) {
return new Compare(number + x);
}
public Compare plus (Compare x) {
return new Compare(number + x.number);
}
This also is implied by expecting a Compare object, not an int as shown.
With that Compare would become immutable, which is very good, as you then can share objects in different variables without problems (changing one variable's value changing other variables' values).
#Override
public String toString() {
return Integer.toString(number);
}
public int intValue() {
return number;
}
The issue here is for the "plus", "div", "isLargerThan" and "isEqualTo" methods in "Compare" class the argument/return type is of type "int". But in "main" function you are passing the object and expecting object of type "Compare".
To fix it either change the argument/return type to "Compare" for those methods in "Compare" class or pass the "int" value as parameter and get "int" value in "main" function.
The plus and div methods take an int and return an int and you are trying to receive their output in a Compare object. Also, isLargerThan takes an int and not a Compare.
Problem is here :
Compare sum = n1.plus(n2);
Compare div = n1.div(n2);
methods : plus and div return int value not an objet of Class Compare.
public int plus (int x) {
return this.number + x;
}
public int div (int x) {
return this.number / x;
}
Add getter method in Compare Class.
public int getNumber(){
return number;
}
Use below code and try to run:
public static void main(String[] args) {
Compare sum = new Compare(9);
Compare divObj = new Compare(4);
sum.plus(n2);
divObj.div(n2);
boolean check1 = sum.isLargerThan(sum.getNumber());
boolean check2 = divObj.isLargerThan(divObj.getNumber());
boolean check3 = divObj.isEqualto(sum.getNiumber());
}

How to check in jUnit the equality of objects with double fields

We all know how to correctly check for fractional numbers in tests (using TOLERANCE):
class OxygenTankTest {
static final double TOLERANCE = 0.001;
#Test
void testFilling() {
OxygenTank tank = OxygenTank.withCapacity(100);
tank.fill(5.8);
tank.fill(5.6);
Assertions.assertEquals(0.114, tank.getStatus(), TOLERANCE);
}
}
But my question is how to check if we need to check not the individual values - but whole objects.
For example:
Need to test Summer - which performs the summation of fields
public class Summer {
public void setSum(Item itemTo, Item itemFrom) {
itemTo.setDiameter(itemTo.getDiameter() + itemFrom.getDiameter());
itemTo.setLength(itemTo.getLength() + itemFrom.getLength());
}
}
public class Item {
private Double diameter;
private Double length;
public Item(Double diameter, Double length) {
this.diameter = diameter;
this.length = length;
}
public Double getDiameter() {
return diameter;
}
public void setDiameter(Double diameter) {
this.diameter = diameter;
}
public Double getLength() {
return length;
}
public void setLength(Double length) {
this.length = length;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Item item = (Item) o;
if (diameter != null ? !diameter.equals(item.diameter) : item.diameter != null) return false;
return length != null ? length.equals(item.length) : item.length == null;
}
#Override
public int hashCode() {
int result = diameter != null ? diameter.hashCode() : 0;
result = 31 * result + (length != null ? length.hashCode() : 0);
return result;
}
#Override
public String toString() {
final StringBuffer sb = new StringBuffer("Item{");
sb.append("diameter=").append(diameter);
sb.append(", length=").append(length);
sb.append('}');
return sb.toString();
}
}
How i try to write a test:
public class SummerTest {
#Test
public void setSum() {
Summer summer = new Summer();
Item itemFrom = new Item(2.321, 1.111);
Item itemTo = new Item(0.999, 0.999);
summer.setSum(itemFrom, itemTo);
// expected
Item expectedItem = new Item(3.32, 2.11);
assertThat(itemFrom, equalTo(expectedItem));
}
}
But it does not work!
java.lang.AssertionError:
Expected: <Item{diameter=3.32, length=2.11}>
but: was <Item{diameter=3.3200000000000003, length=2.11}>
Expected :<Item{diameter=3.32, length=2.11}>
Actual :<Item{diameter=3.3200000000000003, length=2.11}>
<Click to see difference>
How to properly check for compliance?
You overwrote the equals method that checks for exact equality. If you have objects that contain floating point values (float, double) that are considered in your equals implementation, you will want to not compare the object itself, but the values within the object:
assertEquals(expected.getDiameter(), itemFrom.getDiameter(), TOLERANCE);
assertEquals(expected.getLength(), itemFrom.getLength(), TOLERANCE);
Or if you want to get fancy you can create your own Matcher that goes into the assertThat.
Consider changing the set up of the test to allow for exact comparisons via Item::equals:
private static final double ITEM_FROM_DIAMETER = 2.321;
private static final double ITEM_FROM_LENGTH = 1.111;
private static final double ITEM_TO_DIAMETER = 0.999;
private static final double ITEM_TO_LENGTH = 0.999;
Item itemFrom = new Item(ITEM_FROM_DIAMETER, ITEM_FROM_LENGTH);
Item itemTo = new Item(ITEM_TO_DIAMETER, ITEM_TO_LENGTH);
Item expectedItem = new Item(ITEM_FROM_DIAMETER + ITEM_TO_DIAMETER, ITEM_FROM_LENGTH + ITEM_TO_LENGTH);
Also, since Item is mutable, it would be a good idea to assert itemFrom was not changed.

Java : Genrics - Two similar codes, one doesn't work

The below code doesn't work :
class Stats<T extends Number>
{
T[] nums;
Stats(T[] o)
{
nums = o;
}
double average()
{
double sum = 0.0;
for(int i=0; i < nums.length; i++)
sum += nums[i].doubleValue();
return sum / nums.length;
}
boolean sameAvg(Stats<T> ob)
{
if(average() == ob.average())
return true;
return false;
}
}
class BoundsDemo
{
public static void main(String args[])
{
Integer inums[] = { 1, 2, 3, 4, 5 };
Stats<Integer> iob = new Stats<Integer>(inums);
double v = iob.average();
System.out.println("iob average is " + v);
Double dnums[] = { 1.1, 2.2, 3.3, 4.4, 5.5 };
Stats<Double> dob = new Stats<Double>(dnums);
double w = dob.average();
System.out.println("dob average is " + w);
if(iob.sameAvg(dob))
System.out.println("Averages are the same.");
else
System.out.println("Averages differ.");
}
}
But, the following works:
class Gen04<T extends Number>
{
T num;
void set(T a)
{
num = a;
}
T get()
{
return num;
}
boolean equals(Gen04<T> ob)
{
if(num.doubleValue() == ob.get().doubleValue())
return true;
else
return false;
}
}
class GenericCompare
{
public static void main(String args[])
{
Gen04<Integer> obI1 = new Gen04<Integer>();
obI1.set(new Integer(5));
Gen04<Double> obI2 = new Gen04<Double>();
obI2.set(new Double(5.0));
System.out.println("obI1 and obI2 are equal = "+obI1.equals(obI2));
}
}
What is the difference ? In both the programs, I am trying to call a method with parameter type different from the parameter type of the invoking object
In the first snippet, in iob.sameAvg(dob) you attempt to pass a Stats<Double> instance to a method of Stats<Integer>, which expects a Stats<Integer> argument. Since Stats<Double> is not a sub-class of Stats<Integer>, the compiler doesn't accept it.
In the second snippet you call obI1.equals(obI2). equals is a method of Object class that accepts an Object argument, so you can pass any Object instance to it.
EDIT : I see were you got confused. Your second snippet has an equals(Gen04<T> ob) method that overloads Object's equals, but that method is not being called. Instead, the compiler chooses the equals(Object other) method of Object class. If you rename your equals method and call the renamed method from your main, the second snippet would produce the same error.

Comparable interface project [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm very stuck on a project, so far I have got:
public class MyInt implements Comparable<MyInt> {
private int value;
MyInt(int x) {
value = x;
}
public String toString() {
return ("" + value);
}
public int intValue() {
return value;
}
public int compareTo(MyInt rhs) {
MyInt myInt = (MyInt) rhs;
int myInteger = myInt.intValue();
int result = 0;
if (value < myInteger) {
result = -1;
} else if (value == myInteger) {
result = 0;
} else {
result = +1;
}
return result;
}
}
And this is the question:
Consider the following Java Library interface:
public interface Comparable<T> {
int compareTo(T rhs);
}
Complete the implementation of the class below that implements the above
interface (note this interface is automatically imported by java – do NOT
re-type it in your project). The compareTo method should return -1 if
value is less than rhs.value, 0 if both sides are equal and +1 if value is
greater than rhs.value.
public class MyInt implements Comparable<MyInt> {
private int value;
MyInt(int x) {...}
public String toString() {...}
public int intValue() {...}
public int compareTo(MyInt rhs){...}
}
Now I need to implement the comparable interface in another class which performs basic arithmetic with rational numbers, would it be best to use inheritance to achieve this?The class :
public class Rational {
private int num;
private int denom;
public Rational() {
this(0,1);
}
public Rational(int num, int denom) {
this.num = num;
this.denom = denom;
}
int getNum() {
return num;
}
int getDenom() {
return denom;
}
public Rational add(Rational rhs) {
return new Rational(num * rhs.denom + rhs.num * denom, denom * rhs.denom);
}
public Rational subtract(Rational rhs) {
return new Rational(num * rhs.denom - rhs.num * denom, denom * rhs.denom);
}
public Rational multiply(Rational rhs) {
return new Rational(num * rhs.num, denom * rhs.denom);
}
public Rational divide(Rational rhs) {
return new Rational(num * rhs.denom, denom * rhs.num);
}
public String toString() {
String result;
if (num == 0)
result = "0";
else if (denom == 1)
result = num + "";
else
result = num + "/" + denom;
return result;
}
public static void main(String[] args) {
Rational r1 = new Rational(1, 2); // 1/2
Rational r2 = new Rational(3, 4);// 3/4
Rational result = new Rational();
result = r1.add(r2);
System.out.println(result);
Rational result1 = new Rational();
result1 = r1.subtract(r2);
System.out.println(result1);
Rational result2 = new Rational();
result2 = r1.multiply(r2);
System.out.println(result2);
Rational result3 = new Rational();
result3 = r1.divide(r2);
System.out.println(result3);
}
}
You need to compare this.intValue() (the current instance) and rhs.intValue() (the "right hand side"). Comparing rhs to itself (by aliasing it to myInt) should always return 0. And storing the result as a temporary variable doesn't seem to server any purpose in your code. You could do something like
// MyInt myInt = (MyInt) rhs;
if (this.intValue() < rhs.intValue()) {
return -1;
} else if (this.intValue() == rhs.intValue()) {
return 0;
}
return 1;
No need to do explicit casting of your parameter (MyInt rhs), and since you are simply comparing two integers, use static compare method from Integer:
public int compareTo(MyInt rhs) {
return Integer.compare(this.value, rhs.intValue());
}
I would suggest to change your int field to Integer to avoid performance loss in autoboxing of primitives

compareTo() method java is acting weird

hi im having trouble getting this to work im getting an error here with my object comparison...how could I cast the inches to a string ( i never used compare to with anything other than strings) , or use comparison operators to compare the intigers,
Object comparison = this.inches.compareTo(obj.inches);
here is my code so far
import java.io.*;
import java.util.*;
import java.lang.Integer;
import java.lang.reflect.Array;
public class Distance implements Comparable<Distance> {
private static final String HashCodeUtil = null;
private int feet;
private int inches;
private final int DEFAULT_FT = 1;
private final int DEFAULT_IN = 1;
public Distance(){
feet = DEFAULT_FT;
inches = DEFAULT_IN;
}
public Distance(int ft, int in){
feet = ft;
inches = in;
}
public void setFeet(int ft){
try {
if(ft<0){
throw new CustomException("Distance is not negative");
}
}
catch(CustomException c){
System.err.println(c);
feet =ft;
}
}
public int getFeet(){
return feet;
}
public void setInches(int in){
try
{
if (in<0)
throw new CustomException("Distance is not negative");
//inches = in;
}
catch(CustomException c)
{
System.err.println(c);
inches = in;
}
}
public int getInches(){
return inches;
}
public String toString (){
return "<" + feet + ":" + inches + ">";
}
public Distance add(Distance m){
Distance n = new Distance();
n.inches = this.inches + m.inches;
n.feet = this.feet + m.feet;
while(n.inches>12){
n.inches = n.inches - 12;
n.feet++;
}
return n;
}
public Distance subtract(Distance f){
Distance m = new Distance();
m.inches = this.inches - f.inches;
m.feet = this.feet - f.feet;
while(m.inches<0){
m.inches = m.inches - 12;
feet--;
}
return m;
}
#Override
public int compareTo(Distance obj) {
// TODO Auto-generated method stub
final int BEFORE = -1;
final int EQUAL = 0;
final int AFTER = 1;
if (this == obj) return EQUAL;
if(this.DEFAULT_IN < obj.DEFAULT_FT) return BEFORE;
if(this.DEFAULT_IN > obj.DEFAULT_FT) return AFTER;
Object comparison = this.inches.compareTo(obj.inches);
if (this.inches == obj.inches) return compareTo(null);
assert this.equals(obj) : "compareTo inconsistent with equals";
return EQUAL;
}
#Override public boolean equals( Object obj){
if (obj != null) return false;
if (!(obj intanceof Distance)) return false;
Distance that = (Distance)obj;
( this.feet == that.feet &&
this.inches == that.inches);
return true;
else
return false;
}
#Override public int hashCode(int, int) {
int result = HashCodeUtil.inches;
result = HashCodeUtil.hash(result, inches );
result = HashCodeUtil.hash(result, feet);
ruturn result;
}
You're comparing object references. Try to compare object value; either override hashCode() or compare field values.
#Override
public int compareTo(Distance obj) {
....
if (this == obj) return EQUAL; <--- This
...
}
With this line:
Object comparison = this.inches.compareTo(obj.inches);
you are trying to dereference an int, a primitive type. The compiler should be giving you an error: you can only dereference Objects using the dot .
I'm not sure what you want this compareTo code to do, but it is at this point, to compare primitive types, that you should be using ==:
if (this.inches == obj.inches) return compareTo(null);
Be aware that in this line: if (this == obj) return EQUAL; you are comparing object references, which might or might not be what you want. Since your class doesn't override the equals method, this comparison is equivalent to this.equals(obj).

Categories