I have a boolean method as following below
public boolean validID(String personalNumber) { .... }
I wanna to print out a string "is valid" or "is not valid" dependent on if the boolean true or false.
the problem is how can I print out string in a boolean method. The code below return always false even if the if statment is true.
if (sum % 10 == 0) {
return Boolean.parseBoolean("is valid");
} else {
return false;
}
You have only two choices :
a boolean method :
public boolean validID(String personalNumber) {
// ... code to compute 'sum'
return sum % 10 == 0;
}
a String method :
public String validID(String personalNumber) {
// ... code to compute 'sum'
if (sum % 10 == 0) {
return personalNumber + " is valid";
} else {
return personalNumber + " is not valid";
}
}
Or a choice that combine both, the String one that calls the boolean one :
public boolean isValidId(String personalNumber) {
// ... code to compute 'sum'
return sum % 10 == 0;
}
public String validID(String personalNumber) {
if (isValidId(personalNumber)) {
return personalNumber + " is valid";
} else {
return personalNumber + " is not valid";
}
}
I'd suggest to take the boolean one, the better is to let the method find the validity of the personalNumber and let the code that calls it handle the result to print a message, because you may this method again and this time you'll need the boolean result to handle it differently
String id = "fs6d7f6sd";
if(this.validID(id))
System.out.println("ID is valid");
else
System.out.println("ID is not valid");
I recommend to use bean Result.
Check my code.
class Result {
private boolean value;
private String message;
public Result(boolean value, String message) {
this.value = value;
this.message = message;
}
// getter & setter
}
public Result validID(String number) {
// ... code to compute 'sum'
return sum % 10 == 0 ?
new Result(true, "valid") :
new Result(false, "invalid");
}
Related
Full Disclosure: This was an assignment, it has been marked already, but I want to understand why I'm getting this error.
I'm having some issues understanding why junit.framework.AssertionFailedError is being thrown. Normally when errors occur I could at least look at the stack trace and see what is happening. In this case, the output console shows this:
Testcase: testIsCorrectMCQ(mr_3.myTester): FAILED
null
junit.framework.AssertionFailedError
at mr_3.MyTester.testIsCorrectMCQ(Assign03Tester.java:207)
testIsCorrectMCQ(mr_3.MyTester): FAILED
In the test result tab in NetBeans, copying the stack trace gives me:
junit.framework.AssertionFailedError
at mr_3.myTester.testIsCorrectMCQ(myTester.java:207)
In the tester file, I have this:
#Test
public void testIsCorrectMCQ() {
System.out.println("isCorrect of MCQ");
MCQuestion instance = new MCQuestion(1,"Capital city of Canada is", 'A',
"Ottawa", "Vancouver", "New York", "Toronto");
assertFalse(instance.isCorrect("B"));
assertTrue(instance.isCorrect("A")); // line 207
}
My isCorrect method is this:
#Override
public boolean isCorrect(Object guess) {
if (guess == null)
return false;
if (guess instanceof String) {
String userGuess = (String)guess;
return (userGuess.charAt(0) == this.getAnswer());
}
if (guess instanceof Character) {
Character userGuess = (Character)guess;
return (userGuess == this.getAnswer());
}
else return false;
}
Any help in understanding what is happening is greatly appreciated.
Edit 1 : My MCQuestion source code
public class MCQuestion extends Question {
private char answer;
private String[] options;
public MCQuestion() {
super();
questionType = QuestionType.MULTIPLE_CHOICE;
}
public MCQuestion(int id, String text, char answer, String... options) {
super(id, text);
setOptions(options);
setAnswer(answer);
questionType = QuestionType.MULTIPLE_CHOICE;
}
public String[] getOptions() {
String[] getOptions = new String[this.options.length];
System.arraycopy(this.options, 0, getOptions, 0, this.options.length);
return getOptions;
}
public void setOptions(String... options) {
if (options.length > 0) {
this.options = new String[options.length];
for (int i = 0; i < options.length; i++) {
if (options[i].isEmpty())
throw new IllegalArgumentException("You have nothing in this option");
else
this.options[i] = options[i];
}
}
else throw new IllegalArgumentException("You have no options set");
}
public char getAnswer() {
return this.answer;
}
public void setAnswer(char ans) {
ans = Character.toLowerCase(ans);
int index = ans - 97;
if (Character.isLetter(ans) && index >= 0 && index < this.options.length)
this.answer = ans;
else throw new IllegalArgumentException(ans + " is not a valid answer option");
}
#Override
public boolean isCorrect(Object guess) {
if (guess == null)
return false;
if (guess instanceof String) {
String userGuess = (String)guess;
return (userGuess.charAt(0) == this.getAnswer());
}
if (guess instanceof Character) {
Character userGuess = (Character)guess;
return (userGuess == this.getAnswer());
}
else return false;
}
#Override
public String toString() {
String option = "";
if (this.options.length == 0)
option = "No options added, yet!";
else {
char index = 'a';
for (String e: options)
option += index + ") " + e + "\n";
}
return (super.toString() + "\n" + option);
}
}
You execute ans = Character.toLowerCase(ans); for whatever reason in your setAnswer() method before saving it in this.answer. This means that (userGuess.charAt(0) == this.getAnswer()) will return false when you provide the answer in upper case, but compare it with the stored lower case character.
Depending on if you want case insensitive answers or not, you should add or remove the Character.toLowerCase() call to your isCorrect() method as well.
package restaurantclient;
public class Restaurant extends Store {
//Instance Variables
private int peopleServed;
private double averagePrice;
//Constructor with 3 parameters
public Restaurant(String storename, int peopleServed, double averagePrice) {
super(storename);
setPeopleServed(peopleServed);
setAveragePrice(averagePrice);
}
//Getters (Accessors)
public int getPeopleServed() {
return peopleServed;
}
public double getAveragePrice() {
return averagePrice;
}
//Setters (Mutators)
public void setPeopleServed(int peopleServed) {
this.peopleServed = peopleServed;
}
public void setAveragePrice(double averagePrice) {
this.averagePrice = averagePrice;
}
//toString Method [Must Override]
#Override
public String toString() {
String information = "Store name: " + (super.getName());
information += "\n" + "The number of people served: " + peopleServed;
information += "\n" + "The average price per person: $" + averagePrice;
return information;
}
//Equals Method
#Override
public boolean equals (Object other) {
if (this == other)
return true;
if (other == null)
return false;
if (!(other instanceof Restaurant))
return false;
Restaurant otherRestaurant = (Restaurant) other;
if (this.getName() == null) {
if (otherRestaurant.getName() != null)
return false;
} else if (!(this.getName().equals(otherRestaurant.getName())))
return false;
if (peopleServed == -1) {
if (otherRestaurant.peopleServed != -1)
return false;
} else if (peopleServed != (otherRestaurant.peopleServed))
return false;
if (averagePrice == -1) {
if (otherRestaurant.averagePrice != -1)
return false;
}
else if (averagePrice != (otherRestaurant.averagePrice))
return false;
return true;
}
public double getAverageTaxes() {
double total;
total = this.getPeopleServed() * this.getAveragePrice()
* super.CA_TAX_RATE;
return total;
}
}
package restaurantclient;
public class Store {
//Instance Variables
protected final double CA_TAX_RATE = 0.0884;
private String storename;
//Constructor
public Store(String storename) {
setName(storename);
}
//Getters (Accessors)
public String getName() {
return storename;
}
//Setters (Mutators)
public void setName(String storename) {
this.storename = storename;
}
//toString Method [Must Override]
#Override
public String toString() {
String directory = "Name of store: " + storename;
return directory;
}
//Equals Method
public boolean equals (Store storename) {
if (this == storename)
return true;
if (storename == null)
return false;
if (!(storename instanceof Store))
return false;
return true;
}
}
Above are the equals methods I'm calling. They are displaying the wrong answers: it should be in the first instance, "They are not equal" and in the second instance after setting everything equal to each other, it should display, "They are equal". I have tried very hard on this problem and many things have not worked. There are no overt errors it runs fine, but I am doing something wrong and some precise guidance would be a lot of help. Much of the vague hints have got me nowhere. I need something concrete, if this makes to you. Thanks again for the help. The following is the Client class:
package restaurantclient;
public class RestaurantClient {
public static void main(String[] args) {
Restaurant r1 = new Restaurant("McDonald's", 1000000, 8.00);
Restaurant r2 = new Restaurant("KFC", 500000, 6.00);
System.out.println(r1.toString());
System.out.println(r2.toString());
System.out.println();
r2.setAveragePrice(r1.getAveragePrice());
r2.setPeopleServed(r1.getPeopleServed());
System.out.println(r1.toString());
System.out.println(r2.toString());
if (r1.equals(r2)) {
System.out.println("The objects are equal.");
}
else {
System.out.println("The objects are not equal."); //SHOULD say "not equal" here EVERY TIME the second instance (next comment down) says "Equal"...this should never change.
System.out.println();
}
System.out.println();
r2.setName(r1.getName());
System.out.println(r1.toString());
System.out.println(r2.toString());
if (r1.equals(r2)) {
System.out.println("The objects are equal."); //Now that everything is equal, it should print "The Objects are Equal" but it doesn't. It's in lock-step with the previous instance. Changing some things like return true to return false might make both these instances "Are equal" and some might change them to "Not Equal" but they are never the way I want them, which is when 2 changes are made, they are not equal (first case) and when the third and final change is made (like this case here on this line) it should say "the obj are equal" but it doesn't.
}
else {
System.out.println("The objects are not equal.");
System.out.println();
}
System.out.println();
System.out.print("The avg. annual taxes paid by the restaurant is: $");
System.out.println(r1.getAverageTaxes());
}
}
The reason that I see is simple, you are not getting the same name.
In equals, you are comparing super.getName() with otherRestaurant.getName()
If the superclass of Restaurant have a different format or return an other variable, since you compare it to Restaurant.getName(), this will compare different value. Using this.getName() to compare the same variable (or format of variable) is safer. Even if Restaurant.getName() is only returning the super.getName(), this would be safer if you changed the method of Restaurant (because you prefer it an other way).
Here is an example :
Restaurant:
public String getName(){
return "A restaurant " + name;
}
Super class :
public String getName(){
return name;
}
Will result into comparing "A restaurant : KFC" with "KFV".
Using the same getter assure you to return the same "format".
Aslo, your logic is wrong. You want to check if one of the value is different, if it is, return false. And if you reach the end of the method, meaning there where no difference leading to a return false, you return true.
if (this.getName() == null) {
if (otherRestaurant.getName() != null)
return false;
} else if (!super.getName().equals(otherRestaurant.getName())) // added ! here
return false;
if (peopleServed == -1) {
if (otherRestaurant.peopleServed != -1)
return false;
} else if (peopleServed != (otherRestaurant.peopleServed)) // change to != here
return false;
if (averagePrice == -1) {
if (otherRestaurant.averagePrice != -1)
return false;
}
else if (averagePrice != (otherRestaurant.averagePrice)) // change to != here
return false;
//No differences, then it is equals.
return true;
Note :
This condition could be shorten
if (averagePrice == -1) {
if (otherRestaurant.averagePrice != -1)
return false;
}
else if (averagePrice != (otherRestaurant.averagePrice)) // change to != here
return false;
Since it is doing the same thing (comparing the values) :
if (averagePrice != (otherRestaurant.averagePrice))
return false;
Edit :
You are having a problem of overriding.
In Store:
public boolean equals(Store s){}
And in Restaurant
public boolean equals(Object o){}
Since you are calling the method with a Restaurant (subclass of Store), the JVM will use the Store.equals method since it match the type, Restaurant.equals is not overriding it, it override the method in Object. Change to Store.equals(Object o) to correct this.
The method equals comes from Object so it should be always receiving an Object to prevent any problem like this one, if you specify the type in a method, it will not override correctly the method (depending on the type)
Seems you are checking for equality and then returning false, when you should check for not equality to return false.
else if (!super.getName().equals(otherRestaurant.getName()))
return false;
else if (peopleServed != (otherRestaurant.peopleServed))
return false;
else if (averagePrice != (otherRestaurant.averagePrice))
return false;
Also as asked, any reason to uses super.getName() ?
And since peopleServed & averagePrice cannot be null, the -1 check is not needed as the expected result we be the same as the equality check
And finally, I'm guessing the end return should be true, as it means it's different instance of an object, but they have all the same attributs.
Within your equals() method , If super.name() equals otherRestaurant.name() shouldn't you return true, here:
else if (super.getName().equals(otherRestaurant.getName())) return false;
Ok, that one will work in any cases:
#Override
public boolean equals (Object other) {
if (this == other)
return true;
if (other == null)
return false;
if (!(other instanceof Restaurant))
return false;
Restaurant otherRestaurant = (Restaurant) other;
if (name == null) {
if (otherRestaurant.getName() != null)
return false;
} else if (name!=otherRestaurant.getName())
return false;
if (peopleServed == -1) {
if (otherRestaurant.peopleServed != -1)
return false;
} else if (peopleServed != otherRestaurant.peopleServed)
return false;
if (averagePrice == -1) {
if (otherRestaurant.averagePrice != -1)
return false;
}
else if (averagePrice != otherRestaurant.averagePrice)
return false;
return true;
}
check it and reply if it is ok
This is a method from my code and it's throwing me an 'unreachable statement' error when I attempt to compile it.
public static boolean whoareyou(String player)
{
boolean playerwhat;
if (player.equalsIgnoreCase("Player 1"))
{
return true;
}
else
{
return false;
}
return playerwhat;
}
The exact error is:
java:82: error: unreachable statement
return playerwhat;
^
I then attempt to use this boolean I return in the following code:
public static int questions(int diceroll, int[] scorep1)
{
String wanttocont = " ";
boolean playerwhat;
for (int i = 0; i <= 6; i++)
{
while (!wanttocont.equalsIgnoreCase("No"))
{
wanttocont = input("Do you wish to continue?");
// boolean playerwhat; wasn't sure to declare here or outside loop
if (diceroll == 1)
{
String textinput = input("What's 9+10?");
int ans1 = Integer.parseInt(textinput);
output("That's certainly an interesting answer.");
if (ans1 == 19)
{
if (playerwhat = true)
{
output("Fantastic answer player 1, that's correct!");
diceroll = dicethrow(diceroll);
scorep1[0] = scorep1[0] + diceroll;
output("Move forward " + diceroll + " squares. You are on square " + scorep1[0]);
}
else if (playerwhat = false)
{
output("Fantastic answer player 2, that's correct!");
diceroll = dicethrow(diceroll);
scorep1[1] = scorep1[1] + diceroll;
output("Move forward " + diceroll + " squares. You are on square " + scorep1[1]);
}
} // END if diceroll is 1
} // END while wanttocont
} // END for loop
} // END questions
I'm not sure if the above code is relevant to the question but I just wanted to show what I'm attempting to do with the boolean that is throwing me the error. Thank you.
return playerwhat; can never be reached, since either the if or else clause will return true or false. Therefore you should remove this statement. The playerwhat variable is not required.
BTW, your method can be replaced with a one liner method :
public static boolean whoareyou(String player)
{
return player.equalsIgnoreCase("Player 1");
}
I would rename this method to something more descriptive, such as isFirstPlayer.
EDIT :
You never call whoareyou is your questions method. You should call it :
Replace
if (playerwhat = true) // this is assigning true to that variable, not comparing it to true
with
if (whoareyou(whateverStringContainsTheCurrentPlayer)) {
..
} else {
...
}
Just update your code this way
public static boolean whoareyou(String player)
{
boolean playerwhat;
if (player.equalsIgnoreCase("Player 1"))
{
playerwhat = true;
}
else
{
playerwhat = false;
}
return playerwhat;
}
Try this:
public static boolean whoareyou(String player)
{
return player.equalsIgnoreCase("Player 1");
}
You have the issue, because:
return player what;
is never reached. You exit the your function either through the "if"- or through the "else"-part.
I'm having a problem calling a method and then trapping its return.
I need it to update the result so the next time round the loop it will see it and return a different message.
public class Patient {
private char patientStatus;
public boolean admit() {
if (patientStatus != 'S')
return false;
else
patientStatus = 'A';
return true;
}
This section is in the main() method
do {
Patient temp = null;
System.out.print("Enter selection: ");
menuSelect = sc.nextLine();
// validation
if (menuSelect.length() != 1) {
System.out.println("You must enter a single character");
} else {
menuAnswer = menuSelect.charAt(0);
switch (menuAnswer) {
case 'A':
case 'a':
// patient number
System.out.print("Enter patient number: ");
patNumber = sc.nextLine();
// search for patient number
for (int i = 0; i < pat.length && temp == null; i++) {
if (pat[i].getPatientNo().equals(patNumber)) {
temp = pat[i];
}
}
if (temp == null) {
System.out.println("Patient not found");
} else {
System.out.println("Patient " + patNumber + " Found");
boolean patStatus = temp.admit();
if (patStatus == false) {
System.out.println("Admitted");
} else if (patStatus == true) {
System.out.println("Already admitted");
}
}
}
}
} while (menuAnswer != 'x' && menuAnswer != 'X');
System.out.println("Exiting menu");
I don't know how to update the patStatus so the next time in the menu if you select 'A' and the same patient number it returns "Already admitted".
Let me know if there's enough code to understand what's happening.
Your Patient has the atribute for patientStatus but its value is never saved. Your admit() method needs to set the value for it.
Currently, your code only returns the value but does not save it.
Try this:
public class Patient {
private char patientStatus;
/** "Getter" method for patientStatus
*/
public char getPatientStatus(){
return patientStatus;
}
/** "Admits" the new patient, changing its patientStatus
* #return "true" if patient is admitted; "false" if patient was already admitted.
*/
public boolean admit() {
if (patientStatus != 'A')
patientStatus = 'A'; //set the value to Admitted
return true;
else
return false;
}
}
Then, in your loop, test the value for the admit() call:
if (temp == null) {
System.out.println("Patient not found");
} else {
System.out.println("Patient " + patNumber + " Found");
boolean admitted = temp.admit(); // try to admit the patient
if (admitted) {
System.out.println("Admitted");
} else { //You don't need another if here
System.out.println("Already admitted");
}
}
Since admitted is of type boolean, you don't need to use the == operator, as the if statement uses a boolean value as argument.
You don't need a second if statement after the else either, since boolean can only have two values, if it is not true, then it can only be false
/* You have to re-factor the code on these lines.
Maintain Patients class which holds admitted patients.*/
public class Patients{
private ConcurrentHashMap<Integer, Patient> allPatients = new ConcurrentHashMap();
private HashSet<Integer) admittedPatients = new HashSet();
public Patients(){
}
public void add(Patient p){
allPatients.put(p.getPatientId(),p);
}
public Patient removePatient(int patientId){
dischargePatients.remove(patientId);
return allPatients.remove(patientId);
}
public Patient getPatient(int patientId){
return allPatients.get(patientId);
}
public void admitPatient(int patientId){
admittedPatients.add(patientId);
}
public boolean dischargePatient(int patientId){
return admittedPatients.remove(patientId);
}
public boolean isAdmittedPatient(int patientId){
return admittedPatients.contains(patentId);
}
}
From `Patient.java` class, you can admit & discharge patient.
If getPatient() is null implies patient is not present in list.
Once he is present, isAdmittedPatient returns whether
he is admitted or not.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm trying to create a method so I can set the "tuitionFees" and "scholarships" as a double for the profile of the user of the program. I'm unsure if I'm even setting this up right.
import java.util.Scanner;
/**
StudentInvoice.java
Defines StudentInvoice objects
#author: Evan Fravert
*/
public class StudentInvoice {
// declare instance variables here
// constructor
// methods
// toString method (for String output)
private String studentName;
private String studentNumber;
private double tuitionFees;
private double scholarships;
public String toString() {
String output = "Name: " + studentName + "\n";
output += "Student ID Number: " + studentNumber + "\n";
output += "Tuition & Fees: " + tuitionFees + "\n";
output += "Scholarship: " + scholarships + "\n";
return output;
}
public StudentInvoice(String name, String number, double fees, double scholarship){
studentName = name;
studentNumber = number;
tuitionFees = fees;
scholarships = scholarship;
}
public boolean setStudentName(String name){
if(name.length() == 0)
{
return false;
}
else
{
studentName = name;
return true;
}
}
public boolean setStudentNumber(String number){
if(number.length() == 0)
{
return false;
}
else
{
studentNumber = number;
return true;
}
public boolean setTuitionFees(double fees){
if(fees < 0.0) {
return false;
}
else {
tuitionFees = fees;
return true;
}
}
public boolean setScholarships (double scholarship){
if(scholarship < 0.0) {
return false;
}
else {
Scholarships = scholarship;
return true;
}
}
}
}
My class with the interactions:
public class StudentInvoiceApp {
public static void main (String[] args) {
StudentInvoice Evan = new StudentInvoice("Evan Fravert");
Evan.setName("Evan Fravert");
Evan.setNumber(01234);
Evan.setTuitionFees(0.00);
Evan.setScholarship(0.00);
System.out.print(Evan);
}
}
Upon trying to edit your post, I discovered you had a missing brace after setStudentNumber. The corrected code with proper formatting is below. In any programming language, formatting your code is important to understanding its meaning. People write entire books on how to format code, and for good reason. With good formatting, you likely would have noticed the missing brace.
Searching for "How to format Java code" yields several useful conventions, including documents from Oracle about how they format their Java code. When in doubt, most IDE's provide shortcuts to format code as well. In Eclipse, it's Ctrl+Shift+F, and in NetBeans, it's Alt+Shift+F.
import java.util.Scanner;
/**
* StudentInvoice.java Defines StudentInvoice objects
*
* #author: Evan Fravert
*/
public class StudentInvoice {
// declare instance variables here
// constructor
// methods
// toString method (for String output)
private String studentName;
private String studentNumber;
private double tuitionFees;
private double scholarships;
public String toString() {
String output = "Name: " + studentName + "\n";
output += "Student ID Number: " + studentNumber + "\n";
output += "Tuition & Fees: " + tuitionFees + "\n";
output += "Scholarship: " + scholarships + "\n";
return output;
}
public StudentInvoice(String name, String number, double fees,
double scholarship) {
studentName = name;
studentNumber = number;
tuitionFees = fees;
scholarships = scholarship;
}
public boolean setStudentName(String name) {
if (name.length() == 0) {
return false;
} else {
studentName = name;
return true;
}
}
public boolean setStudentNumber(String number) {
if (number.length() == 0) {
return false;
} else {
studentNumber = number;
return true;
}
}
public boolean setTuitionFees(double fees) {
if (fees < 0.0) {
return false;
} else {
tuitionFees = fees;
return true;
}
}
public boolean setScholarships(double scholarship) {
if (scholarship < 0.0) {
return false;
} else {
scholarships = scholarship;
return true;
}
}
}
change your setStudentNumber method to this
public boolean setStudentNumber(String number){
if(number.length() == 0)
{
return false;
}
else
{
studentNumber = number;
return true;
}
}
you were missing an closing brace for else