PrimeAgeChecker only returning false - java

My PrimeAgeChecker is returning false for every age even those that are prime and I can not seem to figure out why this is. I am new to programming and help would be appreciated. Could anyone point me in the right direction?
public class Employee {
// fields
String name;
int age;
Department department;
PrimeAgeChecker checks;
// constructors
public Employee(Department department, String name, int age) {
this.name = name;
this.age = age;
this.department = department;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public Department getDepartment() {
return department;
}
public boolean getChecker(){
return PrimeAgeChecker.isPrime;
}
public String toString(){
StringBuffer sb = new StringBuffer();
sb.append(getDepartment() + " ");
sb.append("\t");
sb.append(getName());
sb.append("\t");
sb.append(getAge());
sb.append("\t");
sb.append(getChecker());
return sb.toString();
}
}
public class PrimeAgeChecker {
static int ages;
public static boolean isPrime = false;
PrimeAgeChecker(Employee age) {
ages = age.getAge();
}
public boolean check() {
if ((ages % 2 == 0) || (ages == 2))
{
isPrime = true;
}
return isPrime;
}
}
Fixed Solution
public boolean getChecker(){
PrimeAgeChecker primeAgeChecker = new PrimeAgeChecker();
return primeAgeChecker.isPrime(getAge());
}
public class PrimeAgeChecker {
static int ages;
public boolean isPrime;
public static void getAge(Employee e){
ages = e.getAge();
}
boolean isPrime(int ages) {
if (ages%2==0) return false;
for(int i=3;i*i<=ages;i+=2) {
if(ages%i==0)
return isPrime = false;
}
return isPrime = true;
}
}

The problem is that when you call getChecker(), you are returning PrimeAgeChecker.isPrime which returns the value of the static variable isPrime. isPrime is declared to be false, which causes your PrimeAgeChecker to always return false.
What you need to do is create an instance of PrimeAgeChecker, passing in the age then call the check method of PrimeAgeChecker.
Your getChecker method could look something like this:
public boolean getChecker(int age){
PrimeAgeChecker primeAgeChecker = new PrimeAgeChecker(age);
return primeAgeChecker.check();
}
Keep in mind, as others have mentioned, your logic behind checking whether the age is prime is also flawed.

Related

Why does my boolean value remain as false despite meeting the if condition in my setter?

public class Main {
public static void main(String[] args) {
// test1 where all variables are valid
Main test1 = new Main("David", "male", 2);
System.out.println(test1);
}
private String name;
private String gender;
private int noOfEyes;
private boolean human;
public Main(){
setHuman(false);
}
public Main(String isName, String isGender, int isNoOfEyes){
setName(isName);
setGender(isGender);
setNoOfEyes(isNoOfEyes);
}
public String getName(){
return name;
}
public String getGender(){
return gender;
}
public int getNoOfEyes(){
return noOfEyes;
}
public boolean getHuman(){
return human;
}
public boolean setName(String newName){
boolean flag =false;
if(newName.length() > 1){
name = newName;
flag = true;
}
else{
flag = false;
}
return flag;
}
public boolean setGender(String newGender){
boolean flag =false;
if(newGender.length() > 1){
gender = newGender;
flag = true;
}
else{
flag = false;
}
return flag;
}
public boolean setNoOfEyes(int newNoOfEyes){
boolean flag =false;
if(newNoOfEyes == 2){
noOfEyes = newNoOfEyes;
flag = true;
}
else{
flag = false;
}
return flag;
}
public boolean setHuman(boolean newHuman) {
boolean flag = false;
if(name == null || gender == null || noOfEyes == 0) {
human = newHuman;
flag = true;
}
else {
flag = false;
}
return flag;
}
public String toString(){
String output = "";
output += "Name is: " + getName() + "\n";
output += "Gender is: " + getGender() + "\n";
output += "No of eyes is: " + getNoOfEyes() + "\n";
output += "Is Human?: " + getHuman() +"\n";
return output;
}
}
I am aware that boolean instance variable will auto instan. as false. But since the setHuman if condition is met, as the name is not null,gender is not null and noOfEyes is not 0,
should not the boolean human value change to true?
The boolean instance variable is not in the constructor as I am not allowed to do so
As you pointed out in your question, booleans default to false. That includes the boolean human which is not set in your three argument constructor so it uses the default value.
But why you are returning booleans from your setters anyway? Your class definition is not very conventional. Why not just do the following for your fields.
public void setGender(String gender) {
this.gender = gender;
}
public String getGender() {
return gender;
}
public void setHuman(boolean value) {
this.human = human;
}
public boolean isHuman() {
return human;
}
And as you may be new to Java, a better solution for gender would be to establish an enum of permitted genders. That would ensure that something like tree or table can't be passed (as it could if you used a String). Here is how it might work.
enum Gender {MALE, FEMALE, TRANS, NONBINARY} // etc.
private Gender gender; // class field
public void setGender(Gender gender) {
this.gender = gender;
}
public Gender getGender() {
return gender;
}
To set it to male for example, you would do.
setGender(Gender.MALE);

Taking user input for the objects

Question : Create a two objects of class Employee and check both are same or diffrent
Below code gives an error : Exception in thread "main" java.util.InputMismatchException
Only object e1 accepts values
class Employee {
String name;
int age;
char gender;
public Employee() {
super();
}
public Employee (String name, int age, char gender) {
this.gender = gender;
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
}
public class Source {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Employee e1 = new Employee();
//e1.name = sc.nextLine();
//e1.age = sc.nextInt();
//e1.gender = sc.next().charAt(0);
System.out.println(e1.name+" "+e1.age+" "+e1.gender);
Employee e2 = new Employee();
//e2.name = sc.nextLine();
//e2.age = sc.nextInt();
//e2.gender = sc.next().charAt(0);
System.out.println(e2.name+" "+e2.age+" "+e2.gender);
boolean isSame = e1.equals(e2);
if(e1.equals(e2)) {
System.out.println("Same");
}
else {
System.out.println("Different");
}
}
}
How to take user input or input from keyboard for objects e1 and e2?
I have made some changes to your Employee and Source classes, take a look.
public class Source {
Scanner sc = null;
public static void main(String[] args) {
Source source = new Source();
Employee e1 = source.getEmployee();
Employee e2 = source.getEmployee();
if(e1.equals(e2)) {
System.out.println("Same");
}
else {
System.out.println("Different");
}
source.closeScanner();
}
public Source() {
sc = new Scanner(System.in);
}
public void closeScanner() {
sc.close();
}
public Employee getEmployee() {
Employee e = new Employee();
System.out.print("Enter Name: ");
e.name = sc.next();
System.out.print("Enter Age: ");
e.age = sc.nextInt();
System.out.print("Enter Gender: ");
e.gender = sc.next().charAt(0);
System.out.println(e.getName() + " " + e.getAge() + " " + e.getGender());
return e;
}
}
public class Employee {
String name;
int age;
char gender;
public Employee() {
super();
int age = -1;
}
public Employee (String name, int age, char gender) {
this.gender = gender;
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + gender;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (age != other.age)
return false;
if (gender != other.gender)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
Please note that I've added the following two methods
public int hashCode()
and
public boolean equals(Object obj)
to make it possible to compare the two instances of the employee object

Efficient way to access/store data instead of having a huge constructor class

I'm currently in need of some guidance. Instead of making a huge constructor class with gets/sets. Is it possible to simplify this task?
Trying to avoid having a huge constructor with gets/sets. So I'm assuming what's a good way to avoid doing something like this. How can this sort of thing be simplified significantly?
public User(int id, String name, long skillPoints) {
this.id = id;
this.name = name;
this.skillPoints = skillPoints;
this.level = 0;
// So on so forth
}
Have you heard of Project Lombok?
By adding the annotation #Data you will get a shortcut for #ToString, #EqualsAndHashCode, #Getter on all fields, #Setter on all non-final fields, and #RequiredArgsConstructor. And there are plenty more annotations you can check out!
With Lombok
import lombok.AccessLevel;
import lombok.Setter;
import lombok.Data;
import lombok.ToString;
#Data public class DataExample {
private final String name;
#Setter(AccessLevel.PACKAGE) private int age;
private double score;
private String[] tags;
#ToString(includeFieldNames=true)
#Data(staticConstructor="of")
public static class Exercise<T> {
private final String name;
private final T value;
}
}
Vanilla Java
import java.util.Arrays;
public class DataExample {
private final String name;
private int age;
private double score;
private String[] tags;
public DataExample(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
void setAge(int age) {
this.age = age;
}
public int getAge() {
return this.age;
}
public void setScore(double score) {
this.score = score;
}
public double getScore() {
return this.score;
}
public String[] getTags() {
return this.tags;
}
public void setTags(String[] tags) {
this.tags = tags;
}
#Override public String toString() {
return "DataExample(" + this.getName() + ", " + this.getAge() + ", " + this.getScore() + ", " + Arrays.deepToString(this.getTags()) + ")";
}
protected boolean canEqual(Object other) {
return other instanceof DataExample;
}
#Override public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof DataExample)) return false;
DataExample other = (DataExample) o;
if (!other.canEqual((Object)this)) return false;
if (this.getName() == null ? other.getName() != null : !this.getName().equals(other.getName())) return false;
if (this.getAge() != other.getAge()) return false;
if (Double.compare(this.getScore(), other.getScore()) != 0) return false;
if (!Arrays.deepEquals(this.getTags(), other.getTags())) return false;
return true;
}
#Override public int hashCode() {
final int PRIME = 59;
int result = 1;
final long temp1 = Double.doubleToLongBits(this.getScore());
result = (result*PRIME) + (this.getName() == null ? 43 : this.getName().hashCode());
result = (result*PRIME) + this.getAge();
result = (result*PRIME) + (int)(temp1 ^ (temp1 >>> 32));
result = (result*PRIME) + Arrays.deepHashCode(this.getTags());
return result;
}
public static class Exercise<T> {
private final String name;
private final T value;
private Exercise(String name, T value) {
this.name = name;
this.value = value;
}
public static <T> Exercise<T> of(String name, T value) {
return new Exercise<T>(name, value);
}
public String getName() {
return this.name;
}
public T getValue() {
return this.value;
}
#Override public String toString() {
return "Exercise(name=" + this.getName() + ", value=" + this.getValue() + ")";
}
protected boolean canEqual(Object other) {
return other instanceof Exercise;
}
#Override public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof Exercise)) return false;
Exercise<?> other = (Exercise<?>) o;
if (!other.canEqual((Object)this)) return false;
if (this.getName() == null ? other.getValue() != null : !this.getName().equals(other.getName())) return false;
if (this.getValue() == null ? other.getValue() != null : !this.getValue().equals(other.getValue())) return false;
return true;
}
#Override public int hashCode() {
final int PRIME = 59;
int result = 1;
result = (result*PRIME) + (this.getName() == null ? 43 : this.getName().hashCode());
result = (result*PRIME) + (this.getValue() == null ? 43 : this.getValue().hashCode());
return result;
}
}
}
Add Kotlin to your project, is becoming the standard, solves your problem as a charm, and as is officially supported by Google, you do not have any problem if you go in production, instead to use other libraries( that could have bugs).
Do not think that you cannot manage to transform all the project from Java to Kotlin, because Kotlin is 100 per cent compatible. One of the K features of Kotlin is just to solve your problem: avoiding to have constructor linked to instance variables and getter and setter, is a lot of boiler plate code.
you just add Kotlin to your project, will take less than 3 minutes, then you can change only the POJO classes, this is the name/acronym of the plain classes you are referring with constructors, getter and setters.
After you installed Kotlin, use Data Classes
in this way a class with 86 lines like the following will become one line. Is worthy to do it, even if you are not going to implement Kotlin to the rest of your project
public class Movie {
private String name;
private String studio;
private float rating;
public Movie(String name, String studio, float rating) {
this.name = name;
this.studio = studio;
this.rating = rating;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStudio() {
return studio;
}
public void setStudio(String studio) {
this.studio = studio;
}
public float getRating() {
return rating;
}
public void setRating(float rating) {
this.rating = rating;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + Float.floatToIntBits(rating);
result = prime * result + ((studio == null) ? 0 : studio.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Movie other = (Movie) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (Float.floatToIntBits(rating) != Float.floatToIntBits(other.rating))
return false;
if (studio == null) {
if (other.studio != null)
return false;
} else if (!studio.equals(other.studio))
return false;
return true;
}
#Override
public String toString() {
return "Movie [name=" + name + ", studio=" + studio + ", rating=" + rating + "]";
}
}
will become just
this and will get for free also toHash and toString:
data class Movie(var name: String, var studio: String, var rating: Float)

Cannot find symbol with mutators and accessors

I'm pretty knew to Java so I don't quite understand what I'm looking for when I'm trying to find errors in my program. I'm trying to create a player class for a game and I'm getting the "cannot find symbol" error. I did some research prior to asking this question but I don't understand the responses.
I get errors such as:
PlayerClass.java:51: cannot find symbol
symbol : variable getLevel
location: class PlayerClass
PlayerClass.setLevel(PlayerClass.getLevel + 1);
^
PlayerClass.java:51: setLevel(int) in PlayerClass cannot be applied to (<nulltype>)
PlayerClass.setLevel(PlayerClass.getLevel + 1);
^
PlayerClass.java:93: cannot find symbol
symbol : variable getName
location: class PlayerClass
if (name.equals(PlayerClass.getName))
^
3 errors
But here's the class:
import io.*;
//CLASS: Player
public class PlayerClass
{
//CLASS FIELDS: name, level, damage, health, kills
//CONSTRUCTORS:
private static int level, health, kills, damage;
private static String name;
//Default Constructor: IMPORT: None
public PlayerClass()
{
name = "Jeremy";
level = 1;
health = 100;
kills = 0;
}
//Alternate Constructor: IMPORT: inName
public PlayerClass(String inName)
{
name = inName;
level = 1;
health = 100;
kills = 0;
}
//Copy Constructor: IMPORT: inPlayer
public PlayerClass(PlayerClass inPlayer)
{
name = inPlayer.getName();
}
//MUTATORS:
//setName IMPORT: inName
public void setName(PlayerClass inPlayer)
{
name = inPlayer.getName();
}
//setLevel IMPORT: inLevel
public int setLevel(int inLevel)
{
PlayerClass.level = inLevel;
}
//levelUp IMPORT:inPlayer
public int levelUP(PlayerClass inPlayer)
{
PlayerClass.setLevel(PlayerClass.getLevel + 1);
}
//ACCESSORS:
//getName IMPORT: None EXPORT: name
public String getName()
{
return name;
}
//getLevel IMPORT: None EXPORT: level
public int getLevel()
{
return level;
}
//getHealth IMPORT: None EXPORT: health
public int getHealth()
{
return health;
}
//getKills IMPORT: None EXPORT: kills
public int getKills()
{
return kills;
}
//toString IMPORT: None EXPORT: playerStr
public String toString()
{
String playerStr;
playerStr = "Name: " + name + "Level: " + level + "Kills: " + kills;
return playerStr;
}
//equals IMPORT: inPlayer EXPORT: same
public boolean equals()
{
boolean same;
same = false;
if (name.equals(PlayerClass.getName))
{
same = true;
}
return same;
}
}
U have missed a parenthesis on getLevel() and getName() and have in mind that you have static fields. Also, you have put
//setLevel IMPORT: inLevel
public int setLevel(int inLevel)
{
PlayerClass.level = inLevel;
}
Where it should be void instead of an int if you want a setter, as well as levelUp() method.
to call a method getName on object player you would do player.getName(). You are missing parenthesis.
Semantically there are bunch of issues in your program.
Why are your fields static? They seem like instance variables. (Read the difference between static fields and instance fields)
Its not java convention to suffix class name with Class. In your case class name would simply be Person instead of PersonClass.
Your equals method is prone to throw NullpointerException
Two of your constructors have same code except for one statement. You should be able to factor out those using constructor chaining. (Read up about it)
I would write your code (using eclipse) as the following:
public class Player {
private int level, health, kills, damage;
private String name;
// Alternate Constructor: IMPORT: inName
public Player(String name, int level, int health, int kills) {
this.name = name;
this.level = level;
this.health = health;
this.kills = kills;
}
public Player() {
this("Jeremy", 1, 100, 0);
}
public Player(Player player) {
this.name = player.getName();
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public int levelUP() {
this.setLevel(this.getLevel() + 1);
return this.level;
}
public int getHealth() {
return health;
}
public void setHealth(int health) {
this.health = health;
}
public int getKills() {
return kills;
}
public void setKills(int kills) {
this.kills = kills;
}
public int getDamage() {
return damage;
}
public void setDamage(int damage) {
this.damage = damage;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// toString IMPORT: None EXPORT: playerStr
public String toString() {
String playerStr;
playerStr = "Name: " + this.name + "Level: " + this.level + "Kills: "
+ this.kills;
return playerStr;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Player other = (Player) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}

JAVA How to compare integer using compareTo in this exercise

I'm trying to do this exercise: i have a student that has a name,surname and a number, i want to order the students by number..if i want to order by name or surname it seems easy but with number i don't know how to do..
this is my code:
public class Student implements Comparable<Student> {
private String name;
private String surname;
private int number;
public Student(String n, String s, int m) {
name = n;
surname = s;
number = m;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public int getmatricola() {
return number;
}
//CompareTo Name
public int compareTo(Student otherObject) {
return name.compareTo(otherObject.getName());
}
}
//TESTER
ArrayList<Student> list = new ArrayList<Student>();
System.out.print("\n ORDER BY NUMBER \n");
Collections.sort(list);
for (int i = 0; i < list.size(); i++) {
Student s = list.get(i);
String std = s.getAll();
System.out.println(std);
}
You can implement something like:
public int compareTo(Student otherObject) {
return Integer.compare(this.number, otherObject.getNumber());
}
So why you number is an int you can substract the number and return the difference:
public class Student implements Comparable<Student> {
private String name;
private String surname;
private int number;
public Student(String n, String s, int m) {
name = n;
surname = s;
number = m;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public int getmatricola() {
return number;
}
//CompareTo number
public int compareTo(Student otherObject) {
return number - otherObject.getmatricola();
}
}
Try doing this...should work
//CompareTo Name
public int compareTo(Student otherObject) {
if( this.getmatricola() > otherObject.getmatricola())
return 1;
else
return -1;
}

Categories