I need to modify DataSet to accept Comparable Objects. The tester will not compile and I do not know how to print out the compareTo method. Should I be using an ArrayList for the tester? Thanks ahead of time!
public interface Comparable
{
/**
Compares this object with another.
#param other the object to be compared
#return a negative integer, zero, or a positive integer if this object
is less than, equal to, or greater than, other
*/
int compareTo(Object other);
}
public class DataSetComparable
{
private double sum;
private Object maximum;
private Object minimum;
private int count;
private Comparable comparer;
/**
Constructs an empty data set with a given measurer.
#param aMeasurer the measurer that is used to measure data values
*/
public DataSetComparable(Comparable acomparer)
{
sum = 0;
count = 0;
maximum = null;
minimum = null;
comparer= acomparer;
}
/**
Adds a data value to the data set.
#param x a data value
*/
public void add(Object x)
{
sum = sum + comparer.compareTo(x);
if (count == 0 || comparer.compareTo(maximum) < comparer.compareTo(x))
maximum = x;
if (count == 0 || comparer.compareTo(minimum) > comparer.compareTo(x))
minimum=x;
count++;
}
/**
Gets the largest of the added data.
#return the maximum or 0 if no data has been added
*/
public Object getMaximum()
{
return maximum;
}
/**Gets the smallest of the added data.
*#return the minimum or 0 if no data has been added
**/
public Object getMinimum()
{
return minimum;
}
}
public class String implements Comparable {
private String input;
private int holder;
public String(String aninput){
input= aninput;
holder=0;
}
public String getComparer(){
return input;
}
public String getString(){
return input;
}
public int compareTo(Object other){
String temp= (String) other;
if(input.compareTo(temp)<0){
holder=-1;
}
else if (input.compareTo(temp)== 0) {
holder= 0;
}
else{
holder= 1;
}
return holder;
}
}
public class StringTester{
public static void main (String [] args){
Comparable c = new String();
DataSetComparable data = new DataSetComparable(c);
data.add(new String("Jimmy"));
data.add(new String("Amy"));
data.add(new String("Melissa"));
data.add(new String("Melissa"));
String max = (String) data.getMaximum();
String min = (String) data.getMinimum();
System.out.println("Maximum String = " + max);
System.out.println("Minimum String = " + min);
}
}
More specifically, the error says:
constructor String in class String cannot be applied to given types.
Your code includes this:
public class String implements Comparable {
...
}
Do you realize that there is a standard Java library class called String that gets imported by default into every class? If implement your own class called String you are going to get some very confusing compilation error messages.
I strongly recommend that you change the name of your class to something else; e.g. StringHolder.
Note, technically you could define a class called String. However the rules that Java uses to disambiguate the names of classes are not designed for this use-case ... and you will end up having to refer to java.lang.String by its fully qualified name wherever you use it. And other people reading / modifying your code would find that really awkward / annoying.
It is best to treat the names of classes in the java.lang package as "reserved", and don't define classes with the same (unqualified) name.
Related
I am trying to pass two variables along to a method and have the method give me back two independent results.
int numX = 5;
int numY = 3;
System.out.println(displayTwiceTheNumber(numX, numY));
}
public static int displayTwiceTheNumber(int numX, int numY) {
int numW, numZ;
numW, numZ = 2 * (numX, numY);
return numW numZ;
}
Java takes it that at numW, numZ = 2 * (numX, numY); that I am trying to redefine numX and numY. How do I phrase the last block to take two variables and give two results?
A single int function can only return 1 int at a time.
If you want to return 2 values, consider calling the function twice or creating a custom object to be used.
You need to change the return type of the function. Currently, the return type is int, so you have to return one integer.
To return two integer, you should consider returning an array or a list or something similar.
public static int[] displayTwiceTheNumber(int numX, int numY){
//your code that do something
int[] ret = {numW, numZ};
return ret;
}
Or knowing that this function would change the value of numW and numZ, you could declare those as global variable. Now, when you call this function, those variable will be changed. Then, you can use numW and numZ subsequently.
public int numW;
public int numZ;
public static void displayTwiceTheNumber(int numX, int numY){
//your code that do something and modifies numW and numZ
}
public static void anotherfunction(){
//after calling displayTwiceTheNumber, numW and numZ would have the appropriate value
//you can now just use numW and numZ directly
}
Overview: Use a tuple. In this example I use an tuple to return more than one result. Tuple means to return more than one result type. In this example I return a tuple of two integer types. My class TupleCustom contains one method function1 which receives two parameters of type integer: x and y. I create a tuple of type integer and return the tuple as a variable. Internally, the precomiler converts the tuple json than back to a tuple with variable Item1, Item2...ItemN in the unit test method.
public class TupleCustom
{
public async Task<Tuple<int, int>> Function1(int x, int y)
{
Tuple<int, int> retTuple = new Tuple<int, int>(x, y);
await Task.Yield();
return retTuple;
}
}
public class TestSuite
{
private readonly ITestOutputHelper output;
public TestSuite(ITestOutputHelper output)
{
this.output = output;
}
[Fact]
public async Task TestTuple()
{
TupleCustom custom = new TupleCustom();
Tuple<int, int> mytuple = await custom.Function1(1,2);
output.WriteLine($" Item1={mytuple.Item1} Item2={mytuple.Item2} ");
}
When I have this problem I create a private utility class for handling the return values. By doing it this way, you can pass various types in the argument list. Aspects of the class can be tailored to your requirements.
public static void main(String [] args) {
int numX = 5;
double numY = 3.0;
Nums n = displayTwiceTheNumber(numX, numY);
System.out.println(n.numX);
System.out.println(n.numY);
}
public static Nums displayTwiceTheNumber(int numX, double numY) {
int numW;
double numZ;
// do something with arguments.
// in this case just double them and return.
return new Nums(2*numX, 2*numY);
}
private static class Nums {
int numX;
double numY;
public Nums(int nx, double ny) {
this.numX = nx;
this.numY = ny;
}
public String toString() {
return "(" + numX + ", " + numY +")";
}
}
Prints
10
6.0
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());
}
For an assignment we are suppose to modify a custom BitString class. There are over 10 functions we need to actually write the code for and I am stuck on the very first one. This is the beginning parts to the class along with some of the methods contained that I am trying to use:
public class BitString implements Cloneable {
// An array to hold the bits that make up the bit string.
private boolean bits[];
/**
* A constant that defines the size of the default bit string.
*/
public static final int DEFAULT_SIZE = 8;
/**
* Creates a new, all false, bit string of the given size.
*/
public BitString(int size) {
if (size < 1) throw new IllegalArgumentException("Size must be positive");
bits = new boolean[size];
}
/**
* Creates a new all false bit string of size DEFAULT_SIZE.
*/
public BitString() {
this(DEFAULT_SIZE);
}
/**
* Set the value of a bit string at the given index to true.
*/
public void set(int index) {
bits[index] = true;
}
/**
* Set the value of a bit string at the given index to false.
*/
public void clear(int index) {
bits[index] = false;
}
Below is the method I am working on (The only part that was given is the method and the input types) I can not call bits.set() or bits.clear() or the same operations that they are doing. When compiling I get
Error: Cannot make a static reference to the non-static field bits
on both method calls.
public static BitString decimalToUnsigned(int n, int size) {
//throw new UnsupportedOperationException("This function needs to be completed!");
int result = 0;
int multiplier = 1;
int base = 2;
while(n > 0) {
int remainder = n % base;
n = n / base;
if (remainder == 0) {
//value = false;
try {
//bits.clear(size);
bits[size] = false;
} catch (InsufficientNumberOfBitsException ie) {}
} else {
//value = true;
try {
//bits.set(size);
bits[size] = true;
} catch (InsufficientNumberOfBitsException ie) {}
}
result = result + remainder * multiplier;
multiplier = multiplier * 10;
size--;
}
System.out.println("Result..." + result);
return(bits);
}
Thanks for any help.
We're having to make some assumptions here: the static method is a method on BitString, for instance.
Given that, the method is evidently supposed to create a BitString object, since it returns one. So it should create one of the size you need for the parameters you are dealing with. Since you have the (arbitrary, somewhat silly) restriction of not being allowed to call the set and clear methods, you will need to access the bits variable from within the BitString that you create directly; since the static method is on the BitString class, you can do this:
public static BitString decimalToUnsigned(int n, int size)
{
// ...
BitString bitString = new BitString(size);
// ... loops, logic, etc. all to be put in here; when you're ready to
// access the bits array, use:
bitString.bits[index] = false;
// ...
// then when you're ready to return your BitString object, just:
return bitString;
}
Yes, bits is declared private, but that just means it cannot be accessed from outside the class. The static method is within the class, though it cannot use the member variables since the static method does not operate on an instance (other than one it creates).
See if that can get you through the compilation error and on to your logic.
p.s. I don't think this is a very good assignment; it will get your head around static vs. non-static methods, but I think there are better ways to do that. And saying that you have to use and return a class but you cannot call its methods is hardly a real-world scenario.
In your static method you need an instance of a BitString to put your vales in. This is how I would do it:
public class BitString implements Cloneable {
/** A constant that defines the size of the default bit string. */
public static final int DEFAULT_SIZE = 8;
// an array to hold the bits that make up the bit string
private boolean bits[];
/** Creates a new, all false, bit string of the given size. */
public BitString(int size) {
if (size < 1) {
throw new IllegalArgumentException("size must be positive");
}
bits = new boolean[size];
}
/** Creates a new all false bit string of size DEFAULT_SIZE. */
public BitString() {
this(DEFAULT_SIZE);
}
/** Set the value of a bit string at the given index to true. */
public void set(int index) { // might want to check index bounds
bits[index] = true;
}
/** Set the value of a bit string at the given index to false. */
public void clear(int index) { // might want to check index bounds
bits[index] = false;
}
public String toString() { // one possible implementation, might not want to add leading 0's
StringBuilder buf = new StringBuilder(bits.length);
for (Boolean bit : bits) {
buf.append(bit ? '1' : '0');
}
return buf.toString();
}
public static BitString decimalToUnsigned(int n, int size) {
// throw new UnsupportedOperationException("this function needs to be completed");
// might want to check that size is big enough
// this is the key here: you need an instance of the object that has the bits array inside it
BitString result = new BitString(size);
while (n != 0 && size > 0) {
size--; // use size to index into the BitString
if ((n & 1) == 1) { // % 2 doesn't work well with negative numbers, you have to worry about +-1 then
result.set(size); // set bit if needed
}
n = n >>> 1; // unsigned shift to the next bit
}
return result;
}
public static void main(String[] args) {
// can be invoked with just decimalToUnsigned(42, 10) but I want to make it more clear
BitString example1 = BitString.decimalToUnsigned(42, 10);
System.out.println(example1);
BitString example2 = BitString.decimalToUnsigned(-42, 10); // will treat -42 as unsigned
System.out.println(example2);
BitString example3 = BitString.decimalToUnsigned(-1, 33); // will treat -1 as unsigned giving 32 1's
System.out.println(example3);
}
}
It prints:
0000101010 1111010110 011111111111111111111111111111111
I am working on a program that will take a list of temperatures(double) and days(string) and implement the list using an array of objects. Then I need to sort the objects using an insertion sort algorithm. The output of the program should be the original order and the sorter output. However I am a little confused on how I can go about sorting the temperatures. I implemented the Comparable interface and wrote the insertion sort. I just have to have the original arraylist to print out and the sorted arraylist to print out. I wrote a toString method to print out the original and it compiles but does not print. here is my code:
import java.io.*;
import java.util.Scanner;
import java.util.Arrays;
import java.util.ArrayList;
public class DailyTemperature implements Comparable<DailyTemperature>
{
//variables
private Double temperature;
private String day;
//getTemp & setTemp methods
public double getTemp()
{
return temperature;
}
public void setTemp(double newTemp)
{
temperature = newTemp;
}
//getDay & setTEmp methods
public String getDay()
{
return day;
}
public void setDay(String newDay)
{
day = newDay;
}
public DailyTemperature(String day, double temperature)
{
this.day = day;
this.temperature = temperature;
}
public int compareTo(DailyTemperature other)
{
if (temperature < other.temperature) return -1;
if (temperature == other.temperature) return 0;
return 1;
}
public String toString()
{
return("Day of Week" + this.getDay() +
"Temperature" + this.getTemp());
}
}
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
public class DailyTemperatureList
{
public static void main (String [] args)
{
ArrayList<DailyTemperature> dailytemps = new ArrayList<DailyTemperature>();
dailytemps.add(new DailyTemperature("Mon", 87.1));
dailytemps.add(new DailyTemperature("Tue", 88.3));
dailytemps.add(new DailyTemperature("Wed", 81.2));
dailytemps.add(new DailyTemperature("Thu", 84.0));
dailytemps.add(new DailyTemperature("Fri", 76.3));
}
public static <T extends Comparable<? super T>>
void insertionSort(ArrayList<DailyTemperature> dailytemps)
{
DailyTemperature temp = null;
int position = 0;
//loop from 2nd element on
for (int i = 1; i < dailytemps.size(); i++)
{
temp = dailytemps.get(i);
position = i;
while ( 0 < position && temp.compareTo(dailytemps.get(position - 1 )) < 0)
{
dailytemps.set(position, dailytemps.get(position - 1));
position--;
}
dailytemps.set(position,temp);
}
System.out.println( dailytemps.toString() );
}
}
You need to add the method public int compareTo(DailyTemperature) that is required for the Comparable interface
public class DailyTemperature implements Comparable<DailyTemperature>{
//...
public int compareTo(DailyTemperature other){
//your code goes here if "this"< than other, return a negative int
//if this > other return positive int
//if they are equal in the eyes of sort, then return 0
}
}
EDIT: your sort would use the comparables like this
DailyTemperature a = ...
DailyTemperature b = ...
if(a.compareTo(b) < 0){
// a < b
}else{
// a >=b
}
#dkatzel is spot on. I would only add that you can take some more advantage of the facilities provided by Java out of the box by making your compareTo implementation tighter:
Here is the same class edited for brevity:
public class DailyTemperature implements Comparable<DailyTemperature>
{
//variables
private Double temperature;
public int compareTo(DailyTemperature other) {
return temperature.compareTo(other.temperature);
}
}
If you store temperature internally as a Double and take advantage of autoboxing (which lets you go from double <-> Double seamlessly...ish), you can then take advantage of the fact Double implements Comparable and delegate the compareTo implementation in your custom class to Double's.
Then you do your insertion sort exactly as #dkatzel said, with the temperature.compareTo calls replacing the usual primitive comparisons.
Coincidentally, we just finished a tutorial on comparisons in Java. Have a look if you want some more explanation on how they work.
Hope that helps.
I'm working through an exercise sheet regarding interfaces, generics and abstract classes in Java. No matter what way I seem to code it, the class Exercise1 won't work. The question asked are commented in the code. Any help would be appreciated, I'm not sure if the error is in the Exercise one code or the implementation of the interface in the classes Time and Point.
/*Exercise 2
(a) Write an interface Printable which has a single method put whose intention is to display a string representation of any object whose class implements Printable. Check it by compiling it. */
interface Printable {
public void put(Object o);
}
/*(b) Enhance classes Point and Time from Chapter 2 of the notes to implement Printable. Check them by compiling them. */
class Point implements Printable {
static Scanner sc = new Scanner(System.in);
private double x, y; // coordinates
Point(double x, double y){ // all-args constructor
this.x = x; this.y = y;
}
Point(){}; // no-args constructor (defaults apply)
void get() {
x = sc.nextDouble();
y = sc.nextDouble();
}
public String toString() {
return "(" + x + "," + y + ")";
}
double distance(Point r) { // distance from r
double xdist = x-r.x; double ydist = y-r.y;
return(Math.sqrt(xdist*xdist+ydist*ydist));
}
public void put(Object o) {
if(o==null) return;
Point p = (Point)o;
System.out.println(x + ":" + y);
}
}
class Time implements Order, Printable {
private int hours; // 0..23
private int mins; // 0..59
Time() { }
Time (int hours, int mins) {
this.hours = hours;
this.mins = mins;
}
public boolean lte(Object other) { // Note public
if (other==null) return false;
Time t = (Time) other;
return hours*60+mins<=t.hours*60+t.mins;
}
public void put(Object o) {
if(o==null) return;
Time t = (Time)o;
System.out.printf("%02d:%02d\n", t.hours, t.mins);
}
}
/*(c) Write a static method print which takes an array of objects whose class implements Printable, and prints each element in the array, one element per line. Check it by placing it in an otherwise empty class and compiling it. */
//this is the bit that is giving me grief, I've tried :
public class Exercise1 {
static void print(Printable[] a) {
for(int i = 0; i < a.length ; i++) {
a[i].put(); // put(java.lang.Object) in Printable cannot be applied to () //a[i].put();
}
}
public static void main(String[] args) {
Time[] t = new Time[10];
for(int i = 0; i < t.length; i++) {
t[i] = new Time();
}
print(t);
}
}
public interface Order {
boolean lte (Object obj); // Object for max generality
// is this object less than or equal to obj?
}
You want to print this, not some arbitrary object o.
I think the problem is the interface Printable. It doesn't match the question correctly.
to display a string representation of any object whose class implements Printable
This doesn't mean, that the put() method should have a parameter of type Object.
The object here refers to this, the object which class implements Printable. And the method put() should print out a string representation of this. So in the simplest case you can implement it with the help of toString().
interface Printable {
/**
* Display a string representation of this
*/
void put();
}
class Point implements Printable {
// ...
/**
* returns a string representation of this
*/
public String toString() {
return "(" + x + "," + y + ")";
}
public void put() {
// this is the same as System.out.println(this.toString());
System.out.println(this);
}
}
Then you can call put() for every Printable in your array.
What you want to do is make the interface Printable look something like this:
interface Printable {
public void print(); //The name of the method should be similar to the name of the interface
}
Then your classes will work like this:
public class Time implements Printable {
private int hours, minutes;
public void print() {
System.out.println( hours + ":" + minutes );
}
}
For Exercise 1, you would then call print() for each element of the array.
By the way: There's already an interface similar to Order. It's called Comparable, and it looks like this:
public interface Comparable<T> {
public void compareTo(T other); //Returns -1 if less than, 0 if equal, and 1 if greater than other object.
}
If no parameter T is given, it becomes Object.
you might want your Printable method to be print(Object object), not put.