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

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

Related

Getter and Setter methods

I'm doing a Java assignment in Greenfoot and I'm stuck on a question about getter and setter methods which I cannot find an answer to.
I'm asked to write a getter and setter method for three attributes (name, colour, age) and then use these methods to:
(a) ensure that age cannot be less than 0 and age cannot be greater than 100
(b) ensure the only valid colours are Black, White, Brown and Grey
Any ideas or suggestions to how I would solve this problem?
Thanks in advance
I hope that help you, that will give you at least a visibility and you can modify it as you want :
public class MyClass {
private String name;
private int age;
private String color;
private final List<String> colors = Arrays.asList("Black", "White", "Brown ", "Grey");
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
if (colors.contains(color)) {
this.color = color;
} else {
// if not valid do what you want
}
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age > 0 && age <= 100) {
this.age = age;
} else {
// if not valid do what you want
}
}
}
I see that there is already a very nice code answer to your question, so i will focus on explaning getter and setter methods:
getter methods are used to get an atribute (also known as a field.) An atribute is usualy found in the top a program, for instance: private int i; i is an atribute. atributes can be accesed by all methods in the same class. so when writing a getter method you simply have to write:
public returntype getSomeAtribute(){
return someAtribute;
}
setter methods are used to set the value of an atribute, different types of atributes can have different values, boolean has true or false, int has integers, String has text. to set the value of a you simply overwrite the current value by writing:
public void setSomeAtribute(){
someAtribute = something;
}

Object Orientation, Inheritance, Abstraction [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
class Student {
private String name;
private int age;
public static String city;
Student() {
}
Student(int a) {
age = a;
}
public void setName(String n) {
name = n;
}
public String getName() {
return name;
}
private int getAge() {
return age;
}
public void setCity(String c) {
city = c;
}
public String getCity() {
return city;
}
}
When considering the features of object orientation, which feature(s) is/are shown clearly in the program?
How can I know that above code is:
Abstraction
Encapsulation
Data hiding
Inheritance
Polymorphism
abstraction - No (you don't have any abstract members or classes in your code).
Encapsulation - yes ( Binding code and data together - the class itself) .
polymorphism - no ( no multiple functions with same names ) .
inheritance - no (There is no class that inherits this one and vice versa )

Java help:How do I fix this error?

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.

Bookstore software in java: basic classes- need help for APCS [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am having a problem with the program I am trying to make. When I implement an arraylist, it is giving me different errors. I am very confused right now on how to initialize my ArrayList of type book.
Here is the Book class:
public class Book {
private double myPrice;
private String myTitle;
private String bookAuthor;
private String isbn;
private int myCopies;
public Book(double price, int copies, String bookTitle, String Author, String isbnNumber) {
myPrice = price;
myCopies = copies;
myTitle = bookTitle;
bookAuthor = Author;
isbn = isbnNumber;
}
public double getPrice() {
return myPrice;
}
public String getIsbn() {
return isbn;
}
public String getTitle() {
return myTitle;
}
public String getAuthor() {
return bookAuthor;
}
public int copiesLeft(){
return myCopies;
}
public String toString() {
return "Title: " + getTitle() + "\nAuthor: " + getAuthor()
+ "\nNumber of Available Books: " + copiesLeft()
+ "\nPrice: $" + getPrice();
}
}
And here is the Inventory Class:
import java.util.ArrayList;
public class Inventory extends Book {
private ArrayList<Book> allBooks = new ArrayList<Book>;
private String customerName;
public Inventory() {
super();
}
//#param double price, int copies, String bookTitle, String Author, String isbnNumber
public void addBooks() {
allBooks.add(new Book(4.99, 6, "A Tale of Two Cities", "Charles Dickens", "9781783220731"));
}
public boolean isAvailable() {
for(Book myBook : allBooks) {
if(myBook.copiesLeft() == 0)
return false;
else
return true;
}
}
public Book getBookByTitle(String titleSearch) {
for (Book myBook : allBooks) {
if (titleSearch.equals(myBook.getTitle()));
return myBook;
}
}
}
I don't know which errors you got, and therefore it's a bit hard to help you. But here are some of the errors in your code. They're marked with //<----
import java.util.ArrayList;
public class Inventory extends Book {
private ArrayList<Book> allBooks = new ArrayList<Book>; //<---- Should be new ArrayList<Book>(); that is, with parentheses.
private String customerName;
public Inventory() {
super(); //<---- I'm rusty on inheritance, but this line** might fuck up some stuff
}
//#param double price, int copies, String bookTitle, String Author, String isbnNumber
public void addBooks() {
allBooks.add(new Book(4.99, 6, "A Tale of Two Cities", "Charles Dickens", "9781783220731"));
}
public boolean isAvailable() {
for(Book myBook : allBooks) {
if(myBook.copiesLeft() == 0)
return false;
else
return true;
}
//<---- You need a second return statement, in case the for-loop and if statement is never accessed. The method always needs to return something when you've told it to.
}
public Book getBookByTitle(String titleSearch) {
for (Book myBook : allBooks) {
if (titleSearch.equals(myBook.getTitle())); //<---- Semicolon
return myBook;
}
//<---- You need a second return statement, in case the for-loop and if statement is never accessed. The method always needs to return something when you've told it to.
}
}
It would be easier to help if you could post the main method and the specific errors you get.
Also, as pointed out by Elliott; I'm not sure why you've extended class Inventory with Book.
** I might be in the wrong here; When calling super(), which in this case is constructor in Books(?), there might spawn errors since you're lacking parameters. This method call should probably not be in this class, since Inventory probably shouldn't extend Book.

How to manipulate value from a return string in Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have a variable that contains a return value.
Value:
Team ID:
111111
Founded:
Feb 13, 2014 By USER
Dispute Percentage:" 0%
Reputation: -
What I am looking to keep is stickly (11111) and save it back to the value teamID. How can I manipulate the return string to only store that value and delete the rest.
If I understand what you want, you can do something like this
String value = "Team ID:\n" + "19288568\n"
+ "Founded:\n" + "Feb 13, 2014 By MLGQA\n"
+ "\n" + "Dispute Percentage: 0%\n"
+ "Reputation: -\n";
System.out.println(value.split("\n")[1]);
Outputs
19288568
Since your returned String seems somewhat complex to me, I would suggest returning a custom object (a bean) containing the information you want, each with its own field.
By doing that, you will have a quick access to any of the fields you want, by simply calling the appropriate getter method on the returned object.
For example:
public class MyContainer {
private int teamID;
private String foundationDate;
private String foundator;
private int disputePercentage;
private int reputation;
public MyContainer() {
// Constructor code.
}
public int getTeamID() {
return teamID;
}
public void setTeamID(int teamID) {
this.teamID = teamID;
}
public String getFoundationDate() {
return foundationDate;
}
public void setFoundationDate(String foundationDate) {
this.foundationDate = foundationDate;
}
public String getFoundator() {
return foundator;
}
public void setFoundator(String foundator) {
this.foundator = foundator;
}
public int getDisputePercentage() {
return disputePercentage;
}
public void setDisputePercentage(int disputePercentage) {
this.disputePercentage = disputePercentage;
}
public int getReputation() {
return reputation;
}
public void setReputation(int reputation) {
this.reputation = reputation;
}
}
And your original returning method would look to something like this:
public MyContainer returningMethod(Object args) {
// Your code.
MyContainer bean = new MyContainer();
// Fill the container.
return bean;
}
I do not know the exact types of data you use, so feel free to adjust this example for your needs!

Categories

Resources