Java help:How do I fix this error? - java

In my class we are working on a java program that creates 'cards' with a face value and suit. It uses two files, one being a runner and one being the class.However I have been stumped by a series of errors in my code that I can't figure out how to get rid of.
This is my code for the card class:
public class Card
{
public static final String FACES[] = {"ZERO","ACE","TWO","THREE","FOUR",
"FIVE","SIX","SEVEN","EIGHT","NINE","TEN","JACK","QUEEN","KING"};
private String suit;
private int face;
public Card()
{
face = 0;
suit = "CLUBS";
}
//set methods
public Card(String str1, int int1)
{
face = int1;
suit = str1;
}
public int getFace()
{
return face;
}
public String getSuit()
{
return suit;
}
public Void setFace(int face)
{
face = face;
return face;
}
public Void setSuit(String suit)
{
suit = suit;
return suit;
}
public String toString()
{
return FACES[face] + " of " + suit;
}
}
The part That is giving me issues is setSuit() and setFace().
before this I tries This.suit or This.face and that gave me a return error asking me to return (which of course didn't work)
this current setup gives me an error saying that it cannot convert to void.
I feel like this is so simple, yet I'm a novice and just started trying java about three weeks ago, so can someone help me out here? I don't just want an answer, I want to understand why this isn't working.

Ok there are two issues here :
1- First issue isn't necessarily a wrong thing but it isn't really needed here. You made your method return Void which would be needed in class that only allows methods that return Objects only or any other similar scenario. While here a void would really suffice.
2- void means nothing . So if your return type is void you shouldn't return anything , infact it wouldn't make sense to call a method setSuit and then ask it to return a value it is like telling your friend to put the food in the fridge and wait for him to give you the food.Now if you used the "Void" which I advised against you would have to return null since Void is an Object so it's something to be returned . Since Void also means nothing it wouldn't make sense for it to be instantialbe (i.e: You cant' make this:
Void nothing=new Void();
Thus in this case you will have to return null(which means nothing). Now if the last part didn't make sense it's alright just put void as a return type and you wouldn't have to return anything.
Lastly you have to put this that you said you put since the "this" will make java realize which face/suit you are referring to , thus assigning the setFace/SetSuits's method face parameter to the object's face parameter (this).
Here is a modified version of your methods:
public void setFace(int face){
this.face = face;
}
public void setSuit(String suit){
this.suit = suit;
}

Because the method is void and you are returning values, if it's void you shouldn't return value to those two methods, or edit them to their return types
Simply try deleting the return statements setters actually don't return they just set that's unnecessary since you have getter

As said by user6798995 the issue is below code
public Void setFace(int face)
{
face = face;
return face;
}
public Void setSuit(String suit)
{
suit = suit;
return suit;
}
you cannot return something if the return type is void
So these should be
public void setFace(int face)
{
face = face;
}
public void setSuit(String suit)
{
this.suit = suit;
}
For main method you can do
Card c=new Card();
c.setFace(7);
c.setSuit("Clubs");
System.out.prinln("Face is"+c.getFace +" Suit is"+ c.getSuit());

well, if anyone comes across this, I learned the hard way, but void needs to be used. "Void" is an object, which is what was giving me problems.

Related

Most idiomatic way of making a data structure on Java [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I'm making a Card class on Java, and I want it to be as idiomatic as possible. Should I encapsulate all the fields making them private and providing getters as following:
public class Card implements Comparable<Card> {
private char suit;
private String name;
private int value;
public Card(char suit, String name, int value) {
this.suit = suit;
this.name = name;
this.value = value;
}
public char getSuit() {
return suit;
}
public String getName() {
return name;
}
public int getValue() {
return value;
}
public String toString() {
return name + " of " + suit;
}
#Override
public int compareTo(Card card) {
return Integer.compare(value, card.value);
}
}
Or since any of the fields are not going to be modified, should make public and final all the fields:
public class Card implements Comparable<Card> {
public final char suit;
public final String name;
public final int value;
public Card(char suit, String name, int value) {
this.suit = suit;
this.name = name;
this.value = value;
}
public String toString() {
return name + " of " + suit;
}
#Override
public int compareTo(Card card) {
return Integer.compare(value, card.value);
}
}
I'm reading Clean Code on the chapter of Data Structures vs OO classes, and I do not know what approach should I take in this case. Thanks in advance!
EDIT:
This class is part of a BlackJack I'm developing, and I need to access the fields from another classes.
EDIT:
This question has been put on hold, but, where does this question should be posted then? Should I move it to Code Review? I'm truly interested in knowing the opinions of more experienced programmers on this subject, but I want to post it on the right site
In theory, when you design OOP solutions, you must provide least priviledge wherever possible. Therefore, your first approach is way to go. But, I would rather implement the hashCode() to make it more clear about the uniqueness of a Card.
What you are trying to implement is called as immutable objects

Using internal method call in constructor? (Basic)

Here is the exact instruction on what my professor has asked me to do:
Write a constructor with two parameters for int year and String player.
Use internal method call to setDetails to initialize the fields.
I have the class so far like this:
public class Card
{
private int year;
private String player;
public Card(String player, int year)
{
}
}
Not sure what the internal method call is, I have looked on the internet and StackOverflow and have not found anything that has benefited me. Any help is appreciated.
Thank you,
A first year programming student.
You need a method to set the details of the card, like this:
private final void setDetails(int year, String player) {
this.year = year;
this.player = player;
}
And then in the constructor, you can call setDetails(year, player).
Based on your statement here is the code that you 're asking for:
public class Card {
private int year;
private String player;
public Card(String player, int year) {
setDetails(player,year);
}
/*i'm making it public in case you want to call the setter directly
somewhere and final since i call an overridable method in the constructor*/
public final void setDetails(String player,int year) {
this.player=player;
this.year=year;
}
}

Java Optional<T> questions, am I doing this right?

I've had a "Bad habit" of tossing null into places, such as enumerators when something doesn't exist.
Example:
private enum Foo {
NULL(1, null, 2),
NOT_NULL(3, new Bar(), 4);
private int a, c;
private Bar b;
Foo(int a, Bar b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
}
So now I'm trying to convert my code to use Optional<T> Like everyone is suggesting, but I'm not sure if I'm doing it correctly.
Here's my code (Trimmed enum):
public static enum Difficulty {
EASY, MEDIUM, HARD
}
public static enum SlayerTasks {
NONE(0, Optional.empty(), Optional.empty(), Optional.empty()),
NPC(1, Optional.of(Difficulty.EASY), Optional.of("That one place."), Optional.of(1));
private int taskId;
private Optional<Difficulty> difficulty;
private Optional<String> location;
private Optional<Integer> npcId;
SlayerTasks(int taskId, Optional<Difficulty> difficulty, Optional<String> location, Optional<Integer> npcId) {
this.taskId = taskId;
this.difficulty = difficulty;
this.location = location;
this.npcId = npcId;
}
public int getTaskId() {
return taskId;
}
public Difficulty getDifficulty() {
return difficulty.get();
}
public String getLocation() {
return location.get();
}
public int getNpcId() {
return npcId.get();
}
}
What's bothering me is the documentation referring to #get() found here where it states:
If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException.
So, I figured that in order to prevent this I would wrap the getter in #isPresent(), but then I couldn't figure out how to return empty.
Is this the correct way to do things, or am I missing something? I'm not looking for a "Fix", I'm looking for information on efficiency and proper practices.
You need to ask yourself what you want your getter to do if there's nothing to return.
There are only really four options:
Return a null (but then you're back to what you were trying to avoid);
Have your getter return an Optional<T> instead of a T;
Return a default value if there's nothing set;
Throw an exception.
I'd go with 2 unless there's a very clearly right answer for what the default should be. 4 is appropriate only if the client code should always know whether there's something there and only ask for it if there is (which would be unusual, though not impossible).
You can replace location.get() with location.orElse("SomeDefaultValue") if you wish to avoid the exception. This allows you to return a default value when the Optional is empty.
IMO, if you're implementing your logic using 'maybe' monad (Optional values) you should stick to Optional object and toss it around, extracting the wrapped value only if its required.
To modify undelying value you can use Optional.ifPresent(), Optional.map() or Optional.flatMap() methods, e.g.
Optional<Difficulty> difficulty = NPC.getDifficulty();
difficulty.ifPresent(diff -> { /* do comething here ... */ });

what's wrong with my class definition?

Why won't this class compile?
class Exam {
private int score;
// constructor initializes score to 99
public void Exam() {
score = 99;
}
// returns the current value of score
private int getScore() {
return score;
}
// returns the String representation of the Object
public String toString() {
return "The score is " + getScore();
}
}
Your constructor shouldn't have a return type. Not even void.
public Exam() {
score = 99;
}
A construct should not contain the void keyword:
public Exam() {
score = 99;
}
A constructor returns a reference the the newly created object. But you don't have to write it. So thinking it is void is wrong as well.
Constructors don't need return types. Remove void and you should be set.
In a constructor you don't use void.
Write the constructor as:
public Exam() {
score = 99;
}
The main problem is the missing package declaration.
package yourpkg;
class Exam {
Additionally, the return type on the for Exam() makes it a function instead of a constructor and will result in a warning.
Just a suggestion not related to the concrete problem:
private int score;
// returns the current value of score
private int getScore() {
return score;
}
There is no point in having that getScore() if your going to keep it private. Make it public.
Also, always use the #Override annotation whenever your intention is to override some method. Compiler will let you known in case you are failing to do so. That means bug prevention.
e.g.
// returns the String representation of the Object
#Override
public String toString() {
return "The score is " + getScore();
}

Return enum value without calling get function

Is it possible in Java to return the enum value without having to call a function to return the value, such as getFlag() in my example? If so, how?
public enum MessageFlags {
BIT0((short)1),
BIT1((short)2),
BIT2((short)4),
BIT3((short)8),
BIT4((short)16),
BIT5((short)32),
BIT6((short)64),
BIT7((short)128),
BIT8((short)256),
BIT9((short)512),
BIT10((short)1024),
set_freq(BIT0),
get_freq(BIT1);
short bitFlag = 0;
MessageFlags flag;
MessageFlags(short flag) {
this.bitFlag = flag;
}
MessageFlags(MessageFlags flag) {
this.flag = flag;
}
public short getFlag() {
return this.flag.bitFlag;
}
public short getValue() {
return this.bitFlag;
}
}
Just say MessageFlags.BITX and that will return the same value as getFlag()
You can import static MessageFlags.*; and say BITX.getFlag().
Here is a complete example:
A.java
package foo;
import static foo.B.*;
public class A{
public B value = BAR;
}
B.java
package foo;
public enum B{
BAR, BAZ, BOO
}
I followed #Jeremy's advice of this:
package foo;
import static foo.B.*;
and then I created a method called set_freq in my MessageFlags enum. I made this function static and had it return short. For example,
public static short set_freqflag() {
return BIT0.getFlag();
}
The semantics of set_freqflag are a little weird because you are not setting anything but I do not have a better name at the moment. This allows me to just state set_freqflag() rather than the longer way I was doing before.
I might be really late, but I'm writing to anyone who visits this topic for help.
If you have an enum, and you'd like to return a specific parameter of its values by default without calling a get function, you need to insert an #Override above your selected function, like:
public class Plants {
public enum Fruits {
APPLE ("sweet"),
GRAPEFRUIT ("sour");
private String taste;
Fruits (String taste) {
this.taste = taste;
}
#Override
public String getTaste() {
return this.taste;
}
}
}
And now you can call whichever enum value you'd like, without a get function:
Plants.Fruits.APPLE
And it'll return "sweet"
P.S. I'm not a professional programmer, please correct me if I've written something anti-conventional by accident.

Categories

Resources