I wrote this code but I am still new in JUnit and have no idea of testing equal and equal2 method. Below is the code I wrote. My object in this code is to see if the fname is equal to lname using equal method and by using equal2 to check if fname is same as fname(it self) maybe my code have errors too.
public class EqualMethods {
/**
* #param args
*/
private String fname;
private String lname;
public EqualMethods(String fl)
{
fname = fl;
}
public EqualMethods(String f, String l)
{
fname = f;
lname = l;
}
public String getFname() {
return fname;
}
public String getLname()
{
return lname;
}
public void setLname(String lname)
{
this.lname = lname;
}
public void setFname(String fname) {
this.fname = fname;
}
public int equal(EqualMethods name)
{
if(fname == name.getFname() && lname == name.getLname())
{
return 1;
}
else
{
return 0;
}
}
public int equal2(Object o)
{
if(o.getClass() == EqualMethods.class )
{
EqualMethods e = (EqualMethods) o;
if(this.fname.equals(e.fname))
{
return 1;
}
return 0;
}
return 0;
}
public String toString()
{
return (" My first name is: "+fname + " Last name is: " + lname);
}
The objective is to create a Junit test case to equal and equal2 as the test case i created does not provide a proper output.Here is the JUnit test case I wrote but I cant make my method static though how to get around it?
public class EqualMethodsTest extends TestCase{
#Test
public void testEqual2() {
String name = "goma";
int ret = 1;
int ans ;
ans= EqualMethods.equal2(name);
assertEquals(ret,ans);
}
}
You need to create instances of EqualMethods to compare them. Like this:
public class EqualMethodsTest extends TestCase{
#Test
public void testEqual2() {
assertEquals(1, new EqualMethods("goma").equal(new EqualMethods("goma")));
}
}
Edit:
A few comments about the code:
If you work with an actual version of junit you don't need to extend TestCase and the name of the test method does not need to start with "test".
Naming a method "equal" or "equal2" might not be the best idea ... in Object, the root of all other objects, there is already a method with the name "equals" ... might be confusing.
Most probably fname == name.getFname() does not what you want to accomplish. This compares the references to two strings, not the content. Strings are objects and are to be compared like this string1.equals(string2).
This is probably a better way to do this:
private EqualsMethods a;
private EqualsMethods b;
#Before
public void before {
a = EqualsMethods("a);
b = EqualsMethods("b);
}
#Test
public void equalTest() {
assertTrue(a.equal(b));
}
#Test
public void equal2Test() {
assertTrue(a.equal2(b));
}
I still think what your doing is a bit odd though, you should probably have two classes with the same attributes and methods - each with an equals method. Then you should created tests for both those classes. Not sure what your trying to achieve here.
Related
Is there any simple way to reduce the lines of code to print the innermost not null object using Optional as alternative to the below code. I feels like we have to write more lines of code to avoid the null checks now.
Is there any easy way to make this code short and sweet in Java 8?
import java.util.Optional;
public class OptionalInnerStruct {
public static void main(String[] args) {
// creepy initialization step, dont worry
Employee employee = new Employee();
employee.setHuman(Optional.empty());
// with optional
Optional<Human> optionalHuman = employee.getHuman();
if (optionalHuman.isPresent()) {
Human human = optionalHuman.get();
Optional<Male> optionalMale = human.getMale();
if (optionalMale.isPresent()) {
Male male = optionalMale.get();
Optional<Integer> optionalAge = male.getAge();
if (optionalAge.isPresent()) {
System.out.println("I discovered the variable finally " + optionalAge.get());
}
}
}
// without optional in picture, it will be something like:
/*if(null! = employee.getHuman() && null!= employee.getHuman().getMale() && null! = employee.getHuman().getMale().getAge()) {
System.out.println("So easy to find variable " + employee.getHuman().getMale().getAge());
}*/
}
static class Employee {
Optional<Human> human;
public Optional<Human> getHuman() {
return human;
}
public void setHuman(Optional<Human> human) {
this.human = human;
}
}
class Human {
Optional<Male> male;
public Optional<Male> getMale() {
return male;
}
public void setMale(Optional<Male> male) {
this.male = male;
}
}
class Male {
Optional<Integer> age;
public Optional<Integer> getAge() {
return age;
}
public void setAge(Optional<Integer> age) {
this.age = age;
}
}
}
You can use Optional.flatMap here
employee.getHuman()
.flatMap(Human::getMale)
.flatMap(Male::getAge)
.ifPresent(age -> System.out.println("I discovered the variable finally " + age);
I've created this method and I'm unsure why it says there's a missing return statement. do I need to change the print to a return? (it's the method at the very bottom) I'm a bit of a Java beginner so any help will be appreciated!
public class Book {
private String title;
private String author;
private int copies;
private boolean borrowed;
public Book( String inAuthor, String inTitle, int inNumberOfCopies ) {
this.author = inAuthor;
this.title = inAuthor;
this.copies = inNumberOfCopies;
}
public void borrowed() {
borrowed = true;
}
public void rented() {
borrowed = true;
}
public void returned() {
borrowed = false;
}
public boolean isBorrowed() {
return borrowed;
}
public String getAuthor() {
return this.author;
}
public static String getTitle() {
return getTitle();
}
public int getTotalCopies() {
return this.copies;
}
public int getAvailableCopies() {
}
public void withdrawCopy() {
int found = 0;
for (Book b : Library.getListOfBooks()) {
if (b.getTitle().equals(title)) {
if (found == 0) {
found = 1;
}
if (!b.isBorrowed()) {
b.borrowed=true;
found = 2;
break;
}
if (found == 0) {
System.out.println("Sorry, this book is not in our catalog.");
} else if (found == 1) {
System.out.println("Sorry, this book is already borrowed.");
} else if (found == 2) {
System.out.println("You successfully borrowed " + title);
}
}
}
}
public String returnCopy() {
boolean found = false;
for (Book book : Library.getListOfBooks()) {
if (getTitle().equals(title) && book.isBorrowed()) {
book.returned();
found = true;
}
if (found) {
System.out.println("you successfully returned " + title);
}
}
}
}
public String returnCopy()
String after public means that this method will return a String.
Your public String returnCopy() is currently not returning anything.
If you don't want to return anything, you can use void like this:
public void returnCopy(){
// code
}
Same issue with public int getAvailableCopies(), this is supposed to return an int but you are not returning anything.
Be careful:
this method:
public static String getTitle() {
return getTitle();
}
is a recursive method without a base condition. This will cause an error and force your application to crash.
You've defined the method as returning a String but you don't return a value anywhere in the method body. Simplest fix is probably to change the return type to void...
public void returnCopy() {...
}
All the above answer are pointing to the same issue, you have defined methods that are breaking the contract about what they return..
In you code you have as well something like this:
public int getAvailableCopies() {
}
so you are telling the compiler, you have a method with the name getAvailableCopies, it takes no params and return an integer.
BUT if you don't return anything, then you are contradicting your own method, your own contract, this is an enough reason for a compiler to complain...
Conclusion:
keep in mind the information that defines the method.
I need to write a Java enumeration LetterGrade that represents letter grades A through F, including plus and minus grades.
Now this is my enumeration code:
public enum Grade {
A(true),
A_PLUS(true),
A_MINUS(true),
B(true),
B_PLUS(true),
B_MINUS(true),
C(true),
D(true),
E(true),
F(false);
final private boolean passed;
private Grade(boolean passed) {
this.passed = passed;
}
public boolean isPassing() {
return this.passed;
}
#Override
public String toString() {
final String name = name();
if (name.contains("PLUS")) {
return name.charAt(0) + "+";
}
else if (name.contains("MINUS")) {
return name.charAt(0) + "-";
}
else {
return name;
}
}
What I am confused about is writing the main program. I think it could be quite straightforward but I have no clue on how to start it.
I don't want the whole code. Just a few lines to give me a head start. The rest I will try to figure out on my own.
I imagine you have a Student class that looks like this:
class Student {
protected Grade grade = null;
public Student(Grade g) {
this.grade = g;
}
}
Then you simply add a method in this class calling the isPassing method from your enum:
public boolean isPassing() {
if (this.grade != null)
return this.grade.isPassing();
return false;
}
This is supposing the passed boolean in Grade are correctly set and are invariant.
I am using three classes in my program:
Term class with variables coefficient and exponent, toString() method etc.
Polynome class, using an ArrayList to store the different Term objects.
Main class that runs the program.
Can I use the toString method of ArrayList in my Polynome class? I'm trying to, but I can't.
I need my polynome to output like this: [3x^2, 3x^1, 1x^0]
I am really confused, I'm calling the toString method of Term, using a for-loop to access each term separately.
My code:
public class Term {
private int coëfficiënt;
private int exponent;
public Term(int coëfficiënt, int exponent) {
this.coëfficiënt = coëfficiënt;
this.exponent = exponent;
}
public int getCoef() {
return coëfficiënt;
}
public int getExp() {
return exponent;
}
public String toString() {
return coëfficiënt + "x^" + exponent;
}
}
Polynome class:
public class Polynoom {
private ArrayList<Term> polynoom;
public Polynoom() {
polynoom = new ArrayList<Term>();
}
public void add(Term term) {
polynoom.add(term);
}
public Term get(int i) {
return polynoom.get(i);
}
public int size() {
return polynoom.size();
}
public String toString() {
// what should I write here?
}
}
Main class:
public class opgave3 {
public static void main(String[] args) {
Polynoom polynoom1, polynoom2, sompolynoom;
polynoom1 = new Polynoom();
polynoom1.add(new Term(1, 2));
polynoom1.add(new Term(3, 1));
polynoom1.add(new Term(1, 0));
polynoom2 = new Polynoom();
polynoom2.add(new Term(-1, 3));
polynoom2.add(new Term(2, 2));
polynoom2.add(new Term(-5, 0));
System.out.println("Tests: ");
System.out.println(polynoom1.toString());
for (int i = 0; i < polynoom1.size(); i++) {
System.out.println(polynoom1.get(i).toString());
}
System.out.println(polynoom1.get(0).toString());
}
}
You just need to use your ArrayList's toString() method as the results of Polynome's toString() method.
public class Polynome {
public ArrayList<Term> terms;
#Override
public String toString() {
if (terms != null) {
return terms.toString();
} else {
return "";
}
}
}
EDIT: The quick answer, since you put your code up is to put
return polynoom.toString();
where you have indicated. Then in your Main class you can simply write
System.out.println(polynoom1);
to show the contents in the desired format.
As Tenner said, use the toString() method of your ArrayList to get the desired output. But also make sure your Term class has a useful toString method of its own:
public class Term {
private int co, ex;
public Term(int coeff, int exp) {
co = coeff;
ex = exp;
}
#Override
public String toString() {
return co + "x^" + ex;
}
}
Add #Override toString() to your Term & Polynome class. The Term class toString() should return a string in the format of coefficientx^exponent.
Then have the Polynome class toString() return yourArrayList.toString()
public static void main(String[] args) throws Exception {
Polynome polynome = new Polynome();
polynome.addTerm(3, 2);
polynome.addTerm(3, 1);
polynome.addTerm(1, 0);
System.out.println(polynome);
}
public static class Term {
private int coefficient;
private int exponent;
public Term(int c, int e) {
coefficient = c;
exponent = e;
}
#Override
public String toString() {
return coefficient + "x^" + exponent;
}
}
public static class Polynome {
private List<Term> terms = new ArrayList<>();
public void addTerm(int coefficient, int exponent) {
terms.add(new Term(coefficient, exponent));
}
#Override
public String toString() {
return terms.toString();
}
}
Results:
Long story short, you can ALWAYS use toString() on anything, even if it's a user defined class. When you call the method, it calls the closest parent class's toString() method, which is guaranteed to be there as Object has one. If you want to control the output of toString() called on your object, you must override it. As it is, if you have an object with a member of type ArrayList, calling your object's toString() will include a ton of extra information that you probably don't want. In order to get the output you want, you need to have the code given by #Tenner's answer, which is
public class Polynome {
public ArrayList<Term> terms;
#Override
public String toString() {
if (terms != null) {
return terms.toString();
} else {
return "";
}
}
}
But you also need to override toString() in the Term class, so that each term outputs in the form desired. The reason this is required is that when you call toString() on an ArrayList, or any other container for that matter, it iterates through the container, calling each object's toString() in turn, adding whatever formatting the container class defines. Ultimately, Term's toString() will be called, and you can control that output by overriding it in the Term class.
As for the last part of the question, you need not call Term's toString() directly, as calling the toString() method of the ArrayList will do this on its own.
I am trying to practice with Polymorphism and using classes. I wrote a superclass called Card. I then wrote 3 subclasses called: IDCard, CallingCard, and DriverLicense. I then wrote another class called Billfold which is supposed to contain slots for two of the cards.
I am supposed to write a BillfoldTester program which adds two objects of different subclasses to a Billfold object.
In BillfoldTester, a DriverLicense object and a CallingCard object are instantiated and added to a Billfold, which refers to these objects with Card references.
I don't really understand how to do this. I created two Card objects but I am trying to add it to my Billfold and it wont work. I tried Billfold a = new Card (x); but it's not right... Any help is much appreciated.
public class BillfoldTester
{
public static void main (String[]args)
{
Card x= new IDCard("Julie", 1995);
Card j= new DriverLicense("Jess", 1997);
//Having trouble trying to put the objects into my Billfold and print it.
}
}
public class Billfold extends Card
{
private String card1;
private String card2;
void addCard(String Card)//Not sure if this should be String
{
card1=Card;
}
}
public class Card
{
private String name;
public Card()
//This is my superclass
{
name = "";
}
public Card(String n)
{
name = n;
}
public String getName()
{
return name;
}
public boolean isExpired()
{
return false;
}
public String format()
{
return "Card holder: " + name;
}
}
public class IDCard extends Card
{
//This is one of my subclasses
private int IDNumber;
public IDCard (String n, int id)
{
super(n);
this.IDNumber=id;
}
public String format()
{
return super.format() + IDNumber;
}
}
The polymorphism example. Not sure if the functionally is exactly what you need, but you can see the whole idea (I hope). See the showAllFormat() method of Billfold class.
The whole point is inside different format() methods of the DriverLicense and IDCard. Depending on the 'real' (or initially assigned) object the different method will be called even if you just only refer to 'Card' class.
NOTE:
You didn't provide your DriverLicense implementation, and my is just from head. I have a bit different constructor to show this sub-classes may be totally different.
import java.util.ArrayList;
import java.util.List;
class Billfold {
List<Card> list = new ArrayList<Card>(10);
void addCard(Card card) // Q: Not sure if this should be String
// A: You would like to add a Card
{
list.add(card);
}
void showAllFormat() {
// go polymorphism !...
// when you call this general 'format()' you see the subclasses
// 'format()' is executed, not from 'Card' class
for(Card x: list) {
System.out.println(x.format());
}
}
}
class Card {
private String name; /* owner */
public Card() //This is my superclass
{
name = "";
}
public Card(String n) {
name = n;
}
public String getName() {
return name;
}
public boolean isExpired() {
return false;
}
public String format() {
return "Card holder: " + name;
}
}
class IDCard extends Card {
//This is one of my subclasses
private int IDNumber;
public IDCard(String n, int id) {
super(n);
this.IDNumber = id;
}
public String format() {
return "(ID)" + super.format() + " " + IDNumber;
}
}
class DriverLicense extends Card {
private String type;
public DriverLicense(String n, String type) {
super(n);
this.type = type;
}
public String format() {
return "(DL)" + super.format() + " TYPE: " + type;
}
}
public class BillfoldTester {
public static void main(String[] args) {
Card x = new IDCard("Julie", 1995);
Card j = new DriverLicense("Jess", "AB");
Billfold bf = new Billfold();
bf.addCard(x);
bf.addCard(j);
bf.showAllFormat();
}
}
This is wrong. A Billfold is not a Card; it HAS Cards.
public class Billfold
{
List<Card> cards = new ArrayList<Card>();
void addCard(Card card) {
if (card != null) {
this.cards.add(card);
}
}
}
Prefer composition over inheritance.
You should have Billfold class have two Card objects, not two Strings:
public class Billfold
{
Card card1;
Card card2;
void addCard(Card card) {
if (card != null) {
if (card1 != null) {
this.card1 = card;
} else {
this.card2 = card;
}
}
}
Ok, you're largely on the right track, just a couple of things:
void addCard(String Card)//Not sure if this should be String
{
card1=Card;
}
You're right, this should be:
void addCard(Card card)
{
card1=card;
}
then to add them:
public class BillfoldTester
{
public static void main (String[]args)
{
Card x= new IDCard("Julie", 1995);
Card j= new DriverLicense("Jess", 1997);
Billfold bf = new Billfold();
Billfold.addCard(x);
Billfold.addCard(j);
}
}
Then add a method to Billfold to print the cards in it.
Edit: Oh yeah, and duffymo is totally right, you don't need to extends Card on Billfold