I have the methods, but need program code for Grade enum - java

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.

Related

New integer is equal to the difference of 2

I'm coding something for a theoretical airport case study and I need help with one bit. I've got 2 different integers with names: maxfuelCapacity and fuelCurrent, and I need something that says ' fuel needed to pump is '.....' being the difference between the maxfuelCapacity of the plane and the current amount. There are no real values so far. How do I go about doing that?
public static int maxfuelCapacity;
public int fuelCurrent;
public String name;
Boolean parked;
public String[] Plane = {
"BA103", "BA493", "BA209"
};
public void setName(String n) {
name = n;
}
public void setParked(Boolean o) {
parked = o;
}
public int getInt(String Maxfuelcapacity) {
return maxfuelCapacity;
}
public String getInt1 (String fuelCurrent) {
return fuelCurrent;
}
As has been mentioned in the comments, your method would look like:
public int fuelNeeded(int fuelCurrent, int maxfuelCapacity) {
if(fuelCurrent >= maxfuelCapacity) {
System.out.println("The tank already has enough");
return 0;
}
return maxfuelCapacity- fuelCurrent;
}
So you call this method in your main function that does the calculation.

multiple Constructors and if Statement

I want to, within my abstract class, define two constructors.
When create a new instance of the class, i want the toString to return something different depending on what was called:
The FireEngine Class
public class FireEngine extends EmergencyVehicle {
private String colour;
public FireEngine(String colour) {
super (colour);
}
public FireEngine() {
this("red");
}
public String toString () {
if (colour == "red") {
return "red";
} else
return "no";
}
}
The EmergencyVehicle class:
public abstract class EmergencyVehicle extends RoadVehicle {
public boolean codeBlue = false;
public EmergencyVehicle(String colour){
super(colour);
}
public boolean isEmergency () {
if (codeBlue == true) {
return true;
} else {
return false;
}
}
public void setEmergency(boolean newEmergency) {
codeBlue = newEmergency;
}
}
This is a homework exercise so I don't want the answer per se, but does the above code make sense?
For example, if I add a new EmergencyVehicle, I want an if statement depending on what colour the vehicle I add is.
1st Remark
Don't call
this("red");
in the default constructor, do
colour = "red";
unless the EmergencyVehicle(String colour) RoadVehicle(String colour) constructor is doing something else.
2nd Remark
Don't compare using
if (colour == "red")
use
if ("red".equals(colour))
3rd Remark
The method
public String toString()
is supposed to return a string representation of the instance. You implementation only returns red or no which is not very informative. Use something like
return("FireEngine(colour=" + colour + ")");

Error with method contains Vector java

I want to make a phone book.
Executing and putting two identical objects is not recognized in the "while" loop with the method "contains(OBJECT)==TRUE".
Where did my code go wrong? Appreciate any help thanks!
Main
public class MainRubrica {
public static void main(String[] args) {
Scanner keyb= new Scanner(System.in);
System.out.print("Inserire il numero di contatti da aggiungere: ");
int nM= keyb.nextInt();
Vector<Contatto> rubrica = new Vector<Contatto>(20, 5);
for(int i=0;i<nM;i++){
System.out.println("\nContatto n."+(i+1));
Contatto c =new Contatto();
c.inserimento();
while(rubrica.contains(c)==true) {
System.out.println("Il contatto è già presente");
c.inserimento();
}
rubrica.addElement(c);
}
for(int i=0;i<nM;i++){
System.out.println("\nContatto n."+(i+1));
System.out.println(rubrica.elementAt(i));
}
Class Contatto
public class Contatto {
//attributi
private String nome;
private String cognome;
private String numeroTel;
//costruttore di default
public Contatto(){
nome="";
cognome="";
numeroTel=""; }
//costruttore con parametri
public Contatto(String nome, String cognome, String numeroTel){
this.nome=nome;
this.cognome=cognome;
this.numeroTel=numeroTel; }
//metodo set
public void setNome(String nome){
this.nome=nome; }
public void setCognome(String congnome){
this.cognome=cognome; }
public void setNumeroTel(String numeroTel){
this.numeroTel=numeroTel; }
//metodo get
public String getNome(){
return nome; }
public String getCognome(){
return cognome; }
public String getNumeroTel(){
return numeroTel; }
//metodo inserimentoContatto
public void inserimento(){
Scanner keyb= new Scanner(System.in);
System.out.println("Nome: ");
nome=keyb.nextLine();
System.out.println("Cognome: ");
cognome=keyb.nextLine();
System.out.println("Numero di telefono: ");
numeroTel=keyb.nextLine();
}
public String toString(){
return "Nome: "+nome+"\nCognome: "+cognome+"\nNumero di Telefono: "+numeroTel;
}
}
I don't understand what you are trying to accomplish, but the reason you aren't ever getting into the while loop is that you haven't overridden the Object.equals method for your Contatto class. Here is the definition of Object.equals:
public boolean equals(Object obj) {
return (this == obj);
}
Using this definition of the "equals" method, it doesn't matter whether all the fields have equivalent values. The two objects are not equal unless they are the same object.
Overriding the equals method in your Contatto class will address this. When you do that, you also need to override the Object.hashCode method so as to maintain the contract for that method as well (equal objects must have equal hash codes). I like to use the Apache Commons Lang library for this. Using that library, you would add something like these methods to your Contatto class:
#Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
} else if (obj instanceof Contatto) {
final Contatto rhs = (Contatto) obj;
return new EqualsBuilder().append(getNome(), rhs.getNome())
.append(getCognome(), rhs.getCognome())
.append(getNumeroTel(), rhs.getNumeroTel())
.isEquals();
} else {
return false;
}
}
#Override
public int hashCode() {
return new HashCodeBuilder().append(getNome()).append(getCognome())
.append(getNumeroTel()).toHashCode();
}
Without the Apache Commons Lang library (should be equivalent to what the library is doing):
#Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
} else if (obj instanceof Contatto) {
final Contatto rhs = (Contatto) obj;
return Objects.equals(getNome(), rhs.getNome())
&& Objects.equals(getCognome(), rhs.getCognome())
&& Objects.equals(getNumeroTel(), rhs.getNumeroTel());
} else {
return false;
}
}
#Override
public int hashCode() {
int hash = 17 * 37 + getNome().hashCode();
hash = hash * 37 + getCognome().hashCode();
hash = hash * 37 + getNumeroTel().hashCode();
return hash;
}
After you add those methods, or implementations of them that match your definition of equality between two Contatto instances, then you should see your code entering that while loop if you input equivalent Contatto objects.

Missing return statement method ReturnCopy

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.

JUnit testing of java Equal method

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.

Categories