I'm having a fairly odd problem with Netbeans.
I'm trying to calculate the sum of an ArrayList, but I am not able to call the method public int sumOfHand() onto my this.hands variable.
I've restarted Netbeans numerous times, created new classes and tried to calculate the sum using the .reduce() method using streams, but none of it helped.
Thanks for any suggestion!
import java.util.List;
import java.util.stream.Stream;
import java.util.ArrayList;
import java.util.Collections;
public class Hand implements Comparable<Hand>{
public ArrayList<Card> hands;
public Hand() {
this.hands = new ArrayList<>();
}
public void add(Card card) {
this.hands.add(card);
}
public void print() {
this.hands.forEach(crd -> {System.out.println(crd);});
}
public void sort() {
Collections.sort(this.hands, (crd1, crd2) -> crd1.compareTo(crd2));
}
#Override
public int compareTo(Hand otherHand) {
// sumOfHand() not recognized here, 'Cannot find symbol'
return this.hands.sumOfHand() - otherHand.sumOfHand();
}
public int sumOfHand() {
int sum = 0;
for (Card tc : this.hands) {
sum += tc.getValue();
}
return sum;
}
}
You can't call a int sumOfHand() of this.hands as hands is an ArrayList.class and int sumOfHand() is a method of Hand.class. To call this method you need to use this.sumOfHands() inside your Hand.class.
Related
i am trying to sort a TreeSet of objects ("Etudiant") using Comparator interface . This the Comparator implementation:
import java.util.Comparator;
public class TriParNom implements Comparator<Etudiant>{
public int compare(Etudiant o1, Etudiant o2) {
return o1.getNom().compareTo(o2.getNom());
}
}
here is the the TreeSet declaration and the call of the comparator in the main :
TreeSet<Etudiant> University= new TreeSet<Etudiant>(new TriParNom());
the error i get in the main class when i declare the TreeSet and call the comparator ,is : no suitable constructor found for TreeSet(TriParNom) .
Any solutions please ? thanks in advance .
I tried a very simple implementation based on the information you provided, and I give you my results:
The Etudiant class is a very simple pojo
public class Etudiant {
private String nom;
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
} }
The TriParNom class is the plain Comparator you described:
import java.util.Comparator;
public class TriParNom implements Comparator<Etudiant> {
#Override
public int compare(Etudiant o1, Etudiant o2) {
return o1.getNom().compareTo(o2.getNom());
}
}
And here is a simple class with an entry point and a sample method to exercise the newly created treeset
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
TreeSet<Etudiant> u = new TreeSet<>(new TriParNom());
System.out.printf("size? %d%n", u.size());
}
}
Execution results follow:
Apparently, there are no compilation errors either.
If your code matches to the snippet given below, then it should run fine without problems. The moment you remove the part implements Comparator<Etudiant> from class TriParNom, you will get the error indicating suitable constructor not found. Now, one another silly way it could happen if you haven't recompiled your classes after you implemented the comparator to your TriParNom - but that's too obvious. Have your class that contins main method(that declares Treeset) imported java.util.TreeSet ?
import java.util.Comparator;
import java.util.TreeSet;
public class TreesetCheck {
public static void main(String[] args) {
TreeSet<Etudiant> University= new TreeSet<Etudiant>(new TriParNom());
}
}
class TriParNom implements Comparator<Etudiant>{
public int compare(Etudiant o1, Etudiant o2) {
return o1.getNom().compareTo(o2.getNom());
}
}
class Etudiant {
public String getNom() {
// TODO Auto-generated method stub
return "some";
}
}
I need to write the method which let to store always last 10 (the newset) elements and only 10.I have tried to use CircularFifoBuffer.It works perfectly usee like this:
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import org.apache.commons.collections4.queue.CircularFifoQueue;
public class Main {
public static void main(String[] args) {
Queue<Integer> fifo = new CircularFifoQueue<Integer>(3);
fifo.add(11);
fifo.add(22);
fifo.add(33);
fifo.add(44);
fifo.add(55);
System.out.println(fifo); // [33, 44, 55]
But it doesn;t work when used inside the method:
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import org.apache.commons.collections4.queue.CircularFifoQueue;
public class TV {
public int channelNumber = 11;
public int getChannelNumber() {
return channelNumber;
}
public void addToChannelsHistory(int channnelNumber) {
Queue<Integer> fifo = new CircularFifoQueue<Integer>(3);
fifo.add(channnelNumber);
System.out.print(fifo);
}
}
Could you help what to use instead?
You have to use the notion of attribute, a member of your class which is a data, not a method:
public class TV {
private final Queue<Integer> fifo = new CircularFifoQueue<Integer>(3);
public Queue<Integer> getChannelNumbers() {
return fifo;
}
public Integer getChannelNumber() {
return fifo.isEmpty() ? null : fifo.peek();
}
public void addToChannelsHistory(int channnelNumber) {
fifo.add(channnelNumber);
}
public String toString() {
return fifo.toString();
}
public static void main( String[] args ) {
TV tv = new TV();
tv.addToChannelsHistory(11);
tv.addToChannelsHistory(22);
tv.addToChannelsHistory(33);
tv.addToChannelsHistory(44);
tv.addToChannelsHistory(55);
System.out.print( tv );
}
}
Forgive me if I've misunderstood, but as far as I can tell by copying this locally, this works. However, in a Java program, the main method is the entry point into the program. If you aren't instantiating your TV class in the main method, the addToChannelHistory method will never get run. For instance, this works for me:
public class TV {
public int channelNumber = 11;
public int getChannelNumber() {
return channelNumber;
}
public void addToChannelsHistory(int channnelNumber) {
Queue<Integer> fifo = new CircularFifoQueue<Integer>(3);
fifo.add(channnelNumber);
System.out.print(fifo);
}
public static void main(String[] args) {
TV tv = new TV();
tv.addToChannelsHistory(11);
tv.addToChannelsHistory(22);
tv.addToChannelsHistory(33);
tv.addToChannelsHistory(44);
tv.addToChannelsHistory(55);
}
}
Running that program should print out 33 to the console.
I'm trying to construct a subclass and I get error that the constructor is undefined?!?!
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
public class LinearAlgebra
{
public class Matrix
{
public int m;
public int n;
public float Matrix[][];
void Matrix(int tempm, int tempn)
{
m = tempm;
n = tempn;
Matrix = new float[m-1][n-1];
}
}
public static void main(String[] args)
{
LinearAlgebra Geometry = new LinearAlgebra();
LinearAlgebra.Matrix Rotation = Geometry.new Matrix(3,3);
System.out.println("hello");
}
}
Sorry have been out of java for a while. I looked at some java tutorials and think I'm doing the same but it is not working
https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
void Matrix(int tempm, int tempn)
This is a method not a constructor. You must remove the return type void:
Matrix(int tempm, int tempn)
You should also name your local variables to start with a lowercase, geometry instead of Geometry. Using an uppercase confuses the reader because it makes it seem as if the nested class Matrix is a static class, not an inner class. Same for the Rotation variable.
I have an ArrayClass and mergeSortArray extends it. And mergeSortArray contains a mergeSort() method. However, since I used super to call a constructor from the superclass, I do not know how to refer to the mergeSortArray (the subclass object / array) and pass it as a parameter in the mergeSort method. In fact, is this even feasible ? I know I can do this in a NON- OOP way. However, I am keen to know how to do this in an OOP way.
Please correct me if I have said incorrect, as I am new to Java and I want to learn more about it.
// ArrayClass Object
import java.util.*;
import java.io.*;
import java.math.*;
public class ArrayClass{
public int[] input_array;
public int nElems;
public ArrayClass(int max){
input_array = new int [max];
nElems = 0;
}
public void insert(int value){
input_array[nElems++] = value;
}
public void display(){
for(int j = 0; j < nElems; j++){
System.out.print(input_array[j] + " ");
}
System.out.println("");
}
}
import java.io.*;
import java.util.*;
import java.math.*;
class mergeSortArray extends ArrayClass{
public mergeSortArray(int max){
super(max);
}
public void methodOne(){
int[] output_array = new int[super.nElems];
mergeSort( // ************* // ,output_array,0, super.nElems -1);
}
................
}
I am not sure what I should put to replace ****** such that I can pass mergeSortArray as a parameter into the mergeSort method.
There isn't a mergeSortArray. You inherit input_array like (and no need for super.nElems you inherit that too),
mergeSort( input_array, output_array, 0, nElems - 1);
Your sub-class will inherit everything that is protected or greater visibility (not private), however your ArrayClass gives you both public fields
public int[] input_array;
public int nElems;
They should probably be protected and have accessor methods (getters).
protected int[] input_array;
protected int nElems;
public int size() {
return nElems;
}
public int[] getInputArray() {
return input_array;
}
First of all, I suggest you not to have public fields on OO code. You got two public fields (input_array and nElems), you should change them to private and create acessors if you need.
Then, to refer to those fields on the subclass, you can either use a protected acessor if you wish to hide the acessor from the rest of the API or a public one, if it's part of your public API. That way, on your ArrayClass:
public class ArrayClass {
private int[] input_array;
private int nElems;
//this may be public
protected int[] getInputArray() {
return input_array;
}
and when you get to call your mergeSort method, you can use getInputArray()
I have problem writing a testcase to this method below: EvenNum(double)
public class OddEven {
/**
* #param args
*/
public boolean evenNum(double num)
{
if(num%2 == 0)
{
System.out.print(true);
return true;
}
else
{
System.out.print(false);
return false;
}
}
This is the testcase I wrote but I think I have an inheritance problem or a logical problem in this test case. Should be a very simple one but can't figure out. Here is the code I wrote:
import static org.junit.Assert.*;
import org.junit.Test;
public class OddEvenTest {
#Test
public void testEvenNum() {
boolean ans = true;
boolean val;
double num= 6;
val = OddEven.EvenNum(num) // cant inherit the method dont know why???
assertEquals(ans,val);
}
}
You have a number of issues:
you are attempting to call a non-static method statically
method names in java are case sensitive and you've mixed up the case.
I corrected some things for you and just verified the code below:
OddEven.java:
public class OddEven {
public boolean evenNum(double num)
{
if(num%2 == 0)
{
System.out.print(true);
return true;
}
else
{
System.out.print(false);
return false;
}
}
}
OddEvenTest.java
import static org.junit.Assert.*;
import org.junit.Test;
public class OddEvenTest {
#Test
public void testEvenNum() {
boolean ans = true;
boolean val;
double num = 6;
OddEven oddEven = new OddEven();
val = oddEven.evenNum(num);
assertEquals(ans,val);
}
}
Assuming the calls to System.out.println() in OddEven are strictly for debugging, the whole thing could be collapsed down to:
OddEven.java
public class OddEven {
public boolean evenNum(double num) {
return num%2 == 0;
}
}
OddEvenTest.java
import static org.junit.Assert.*;
import org.junit.Test;
public class OddEvenTest {
#Test
public void testEvenNum() {
OddEven oddEven = new OddEven();
assertTrue(oddEven.evenNum(6));
assertFalse(oddEven.evenNum(5));
}
}
The code is now shorter and the unit test even covers an odd case for good measure.
Two things :
You are invoking a non-static method statically. The method should be declared static:
public static boolean evenNum(double num) {
}
You didn't type the name of the method correctly. Look closely. Also consider renaming it something more readable like, isEven(...)
This seems like testing gone mad to me, and programming gone mad too. All the method does is evaluate num % 2 == 0. You may as well just code that everywhere required and throw away both the method and its tests. If you must keep the method, it relies on a mathematical identity, you don't need to test those. You may as well test 1+1==2.