how can I improve my code for this task - java

I am newbie to object orientated programming and trying to construct something which resembles a basic vote counter which should take an int parameter that represents a choice of two candidates and print the election results to the terminal window. albeit (the votes attributable to each candidate and the total votes cast)
The method I am looking for should also return a string that gives information on the success or failure of casting the vote.”your vote has been cast” “invalid choice, no vote cast"
I have created a class and the constructors and also implemented some basic get methods.
I am wondering how I should go about achieving this objective albeit through a conditional statement or using some sort of advanced method.
any help in terms of the syntax or wider approach would be appreciated.
public class VoteCounter {
private String candidate1;
private String candidate2;
private int candidate1Votes;
private int candidate2Votes;
private boolean completed;
public VoteCounter(String candidate1, String candidate2) {
this.candidate1 = candidate1;
this.candidate2 = candidate2;
this.candidate1Votes = 0;
this.candidate2Votes = 0;
this.completed = false;
}
public VoteCounter() {
this("CANDIDATE 1", "CANDIDATE 2");
}
public String getCandidate1 () {
return this.candidate1;
}
public String getCandidate2 () {
return this.candidate2;
}
public Boolean getCompleted () {
return this.completed;
}
public void setCompleted (boolean completed) {
this.completed = completed;
}
}

Something like this?
private String vote(int choice)
{
if(choice == 1)
{
candidate1Votes++;
}
else if(choice == 2)
{
candidate2Votes++;
}
else
{
return "invalid choice, no vote cast";
}
return "your vote has been cast";
}

I would do that in more general manner, avoiding code duplication and allowing to change number of candidates easily.
So let's make a class Vote similar to your VoteCounter but only for one candidate, with following fields:
private String candidate; // init this in constructor
private int candidateVotes; // initially 0, so no need to init
and with vote() method like in other answer but also without a candiadate, so:
public void vote() {
candidateVotes++;
}
Then you can make class VoteCounter which will take any number of candidates and will keep them in Array or Map.
Map<Integer, Vote> votes = new HashMap<>();
then you're creating vote method with choice:
public void vote(int choice) {
votes.get(choice).vote();
}
Then all is left is to iterate through your votes map and find the one with biggest number of votes.

Related

Getting a parameter's value change to persist after function ending in Java [duplicate]

This question already has answers here:
Java : Best way to pass int by reference
(7 answers)
Closed 5 years ago.
I have a program which is meant to be a client/server game question game. I've made it as far as accounting various cases of the client/server sending a termination command for the end of the game.
Now, my issue is that I have a set of primitive int points, attempts, correct which are read by the client from the server in a String as below:
N.B. I do know that Java functions pass parameters by value, not reference, and that assigning the value inside of the function will not change the value of the original.
int points = accepted = correct = 0;
String inbound = check (inbound, points, accepted, correct);
System.out.println(points); // Displays value of 0, when expecting > 0
private static String check (String str, int points, int attempts, int correct) {
// Expect Q QuestionString
if (str.substring(0,1).equals("Q")) {
//System.out.println("This is the question.");
return str.substring(2, str.length());
}
String[] input = str.split(" ");
// Expect EX # # #
if (input[0].contains("EX")) {
points = Integer.parseInt(input[1]);
attempts = Integer.parseInt(input[2]);
correct = Integer.parseInt(input[3]);
return "EX";
}
// Expected strings: Correct..., Incorrect.
return str;
}
I am unsure how to workaround this issue without jeopardizing encapsulation or hindering other concepts.
Create a wrapper class to contain those three integer parameters then simply pass an instance of that wrapper to the check method and then modify its contents within the method.
example:
public class Wrapper
{
private int points;
private int attempts;
private int correct;
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
public int getAttempts() {
return attempts;
}
public void setAttempts(int attempts) {
this.attempts = attempts;
}
public int getCorrect() {
return correct;
}
public void setCorrect(int correct) {
this.correct = correct;
}
}
thus the first part of your code will become:
Wrapper wrapper = new Wrapper();
String inbound = check (inbound, wrapper);
System.out.println(wrapper.getPoints());
and your check method becomes:
private static String check (String str, Wrapper wrapper) {
...
...
if (input[0].contains("EX")) {
wrapper.setPoints(Integer.parseInt(input[1]));
wrapper.setAttempts(Integer.parseInt(input[2]));
wrapper.setCorrect(Integer.parseInt(input[3]));
return "EX";
}
...
...
}

text adventure/interactive fiction in java

I decided to create an account in order to ask a question I cant seem to figure out myself, or by some googling, hopefully I didn't just overlook it.
Essentially I am trying to make a text adventure game in Java, and am having a little trouble seeing how I should relate everything in the idea of objects. I have been successful in using XML stax and sending a file to the program, and using attributes and what not, to make it where the user can enter an integer associated with an option, and see if option requires an "item" or gives them an Item. I however did not take an OOP to this.
I want my new program to people able to take a string of user input in, instead of only an integer, and checking it against an array list if it exists. This is closer to the classic MUDs most may be familiar with.
I want to design it in a modular way, so I can slowly add on ideas, and more complexity to go along, so I don't want a "well it works so lets leave it alone" approach either.
Currently I simply want something close to this:
A Room object, which would have: an ID, Description, and interact-able
a Choice object (this one im not sure on) I thought about making an object to hold each rooms possible choices, both for exit, and for interact-ables
if so, the room object may need a Choice Object.
I've thought it over, tried some code, thought it over again, and every time, I keep ending up hard coding more than I feel I should, and making tons more variables than I feel are necessary, which makes me feel like i'm missing something crucial in my thinking.
I also want these rooms to be created through an inputted file, not generated in the code (so essentially the code is a story reader/crafter for any type, not one)
I have also been attempting this too long, and my solutions are becoming worse, but below was my most recent attempt at a rough Idea:
a GameManager class that takes the userInput and checks it some, before passing it along. I havent passed any data because im not sure of the approach. also im not used to regex, so some of that may also be wrong, if it is, maybe point it out, but that is not my focus
import java.util.Scanner;
public class GameManager {
private static final String EXIT_PHRASE = "exit";
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
String userStringVal = "";
while(!userStringVal.equals(EXIT_PHRASE)){
userStringVal= userInput.nextLine();
if(checkKeywords(userStringVal)){
System.out.println("matches keyword");
}
else System.out.println("didnt match a keyword");
}
userInput.close();
}
public static boolean checkKeywords(String string){
boolean isKeyword = false;
string.toLowerCase();
if(string.matches("travel.*") || string.matches("search.*")){
System.out.println("passed first check");
String substring = string.substring(6);
if(matchDirection(substring)){
isKeyword = true;
}
}
return isKeyword;
}
public static boolean matchDirection(String string){
boolean hasDirection = false;
if(string.matches(".*\\bnorth|south|east|west|northeast|northwest|southeast| southwest|up|down")){
hasDirection = true;
}
return hasDirection;
}
}
The Room object I thought about as such:
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
public class Room {
private String roomDescription = "";
private int roomID=0;
private int northExit=0;
private int southExit=0;
private int eastExit=0;
private int westExit=0;
private int northeastExit=0;
private int northwestExit=0;
private int southeastExit=0;
private int southwestExit=0;
private int upExit=0;
private int downExit=0;
private String[] interactables = new String[10];
private Options options = new Options();
public Room(XMLStreamReader reader) throws XMLStreamException{
setAttValues(reader);
setRoomDescription(reader);
setUpOptions();
}
public void setinteractables(XMLStreamReader reader){
int count = reader.getAttributeCount();
for(int i = 0; i < count; i++){
interactables[i] = reader.getAttributeValue(i);
}
}
public void setAttValues(XMLStreamReader reader){
int count = reader.getAttributeCount();
for(int i = 0; i < count; i++){
String att = reader.getAttributeLocalName(i);
if(att !=""){
switch(att){
case "North": northExit=Integer.parseInt(att);
case "South": southExit=Integer.parseInt(att);
case "East": eastExit=Integer.parseInt(att);
case "West": westExit=Integer.parseInt(att);
case "NorthEast": northeastExit=Integer.parseInt(att);
case "NorthWest": northwestExit=Integer.parseInt(att);
case "SouthEast": southeastExit=Integer.parseInt(att);
case "SouthWest": southwestExit=Integer.parseInt(att);
case "Up": upExit=Integer.parseInt(att);
case "Down": downExit=Integer.parseInt(att);
case "ID": roomID=Integer.parseInt(att);
}
}
}
}
public void setRoomDescription(XMLStreamReader reader) throws XMLStreamException{
roomDescription = reader.getElementText();
}
public void setUpOptions(){
options.setCardinalPointers(northExit, southExit, eastExit, westExit);
options.setIntercardinalPointers(northeastExit, northwestExit, southeastExit, southwestExit);
options.setElevationPointers(upExit, downExit);
}
}
what can I do to make sure I dont have to state so many directions with so many variables?
here is a quick and rough idea of an Option class that I thought about, but i didn't finish deciding I am already too far in the wrong direction
public class Options {
private int northPointer = 0;
private int southPointer= 0;
private int eastPointer = 0;
private int westPointer = 0;
private int northeastPointer= 0;
private int northwestPointer = 0;
private int southeastPointer = 0;
private int southwestPointer = 0;
private int upPointer = 0;
private int downPointer = 0;
private String northInteractable = "";
private String southInteractable = "";
private String eastInteractable = "";
private String westInteractable = "";
private String northeastInteractable ="";
private String northwestInteractable = "";
private String southeastInteractable = "";
private String southwestInteractable = "";
private String upInteractable = "";
private String downInteractable = "";
public Options(){
}
public void setCardinalPointers(int north, int south, int east, int west){
northPointer = north;
southPointer = south;
eastPointer = east;
westPointer = west;
}
public void setIntercardinalPointers(int northeast, int northwest, int southeast, int southwest){
northeastPointer = northeast;
northwestPointer=northwest;
southeastPointer=southeast;
southwestPointer=southwest;
}
public void setElevationPointers(int up, int down){
upPointer = up;
downPointer = down;
}
public String whatToReturn(String string){
String importantPart = "";
if(string.matches("travel.*")){
String substring = string.substring(6);
}
else {
importantPart = "Interactable";
String substring = string.substring(6);
if (substring.matches("\\bnorth\\b")) {
if(northInteractable!=0){
}
}
else if (substring.matches("\\bsouth\\b"))
else if (substring.matches("\\beast\\b"))
else if (substring.matches("\\bwest\\b"))
else if (substring.contains("northeast"))
else if (substring.contains("northwest"))
else if (substring.contains("southeast"))
else if (substring.contains("southwest"))
else if (substring.contains("up"))
else if (substring.contains("down"))
}
return importantPart;
}
}
I did not see the adventure tag until after I typed this, so I will start perusing through there, but will still post this, so my apologies if there is a good answer to this and I have yet to find it.
as a recap: what would be a good way to relate a few objects to create a room object (that gets its information from a file (XML being what im used to)) having exits, descriptions, and interactions. and the user interacting with these based off keywords that can be inputted freely, and not restricted to say, index values of array's holding keywords.
Im thinking when the user types something like "travel north" to first check if they typed a keyword, in this case being travel, then a direction. Then somewhree else checking if it states travel, check north with a possible northExit a room may or may not have. Then if its another keyword, say like check, to make it easy also have the exact same directions, but check for a different string.
Then if room "northExit" exists, get an option somehow, with a pointer to another roomID. though This thought process causes me issues when thinking about future possibility of requiring items for getting to the next room. Also where to store/acquire these options is causing some difficulties.
There are two things I would like to introduce to you. The first, in the enum. You can think of this as a special kind of class where all the possible options are enumerated in the class definition. This is perfect for things like, in your case, directions. Enums can be simple, where you just list all of the possible options for use in other classes:
public enum Direction {
NORTH, NORTH_EAST, EAST, SOUTH_EAST, SOUTH, SOUTH_WEST, WEST, NOTH_WEST;
}
They can be a bit more complex, if you want them to have methods and attributes of their own:
public enum Direction {
NORTH(true), NORTH_EAST(false), EAST(true), SOUTH_EAST(false), SOUTH(true), SOUTH_WEST(false), WEST(true), NOTH_WEST(false);
private final boolean isCardinal;
private Direction(boolean isCardinal){
this.isCardinal = isCardinal;
}
public boolean isCardinal(){
return isCardinal;
}
public static Collection<Direction> getCardinalDirections(){
return Arrays.asList(Direction.values()).stream().filter(Direction::isCardinal).collect(Collectors.toList());
}
public static Collection<Direction> getIncardinalDirections(){
return Arrays.asList(Direction.values()).stream().filter(x -> !x.isCardinal()).collect(Collectors.toList());
}
}
Please read more about Java enum types here.
The second thing I would like to introduce to you is the data structure known as the Map. Maps are also known as Dictionaries, and that can often help understanding how they work. A Map will take one object and map it to another object, like how a Dictionary maps a word to its definition, or a phonebook maps a person's name to their phone number. We can simplify your Room class a ton by using a Map. I am not going to reproduce all of your code, since I'm focusing on your Room exists right now:
public class Room {
private Map<Direction, Room> exits;
public Room(){
this.exits = new HashMap<>();
}
public void setExit(Direction direction, Room room){
this.exits.put(direction, room);
}
public Room getExit(Direction direction){
return this.exits.get(direction);
}
}
Please read more about the Java Map interface here.
You will, of course, need to adapt your methods which are reading from XML, etc. But, now, your Room class should be greatly simplified.
I hope this points you in a helpful direction.

How to access values stored in ArrayList in Java?

I'm a total newbie to Java, and until now all I've done was draw some shapes and flags. I'm struggling to understand the code I've been given. I need to access values stored in an ArrayList within another class. I'm not sure I'm making any sense, so here are the two classes Seat and Mandate:
package wtf2;
import java.util.*;
public class Seat {
public int index;
public String place;
public int electorate;
public String mp;
public String party;
public String prev;
public ArrayList<Mandate> results;
public Seat(int index, String place) {
this.place = place.trim();
this.index = index;
this.results = new ArrayList<Mandate>();
}
public void addMandate(Mandate m) {
//First candidate is always the MP
if (mp == null) {
mp = m.candidate;
party = m.party;
}
results.add(m);
}
public String toString() {
return "[" + this.index + "," + this.place + "]";
}
}
class Mandate {
public String candidate;
public String party;
public int vote;
public Mandate(String candidate, String party, int vote) {
this.candidate = candidate;
this.party = party;
this.vote = vote;
}
}
The main class contains code that feeds data from 2 text files into Seat and Mandate. From there I managed to access the date in Seat. Like here:
//Who is the MP for "Edinburgh South"
public static String qA(List<Seat> uk) {
for (Seat s : uk)
if (s.place.startsWith("Edinburgh South"))
return (s.mp);
return "Not found";
}
Now,instead of getting just the mp for Edinburgh South I need to get the vote values, compare them to each other, take the second biggest and display the associate party value.
Would appreciate any help, like how to access data from that Array would help me get started at least.
An element in an ArrayList is accesses by its index.
Seems you can just sort your ArrayList based on the vote values of the objects which are in the list.
For this you may want to look here: Sort ArrayList of custom Objects by property
Of course sorting is maybe too much for your given problem. Alternatively,
you may just iterate through the list and pick the two objects with the highest
votes values as you go.

Java - Better idiom for my control flow

I'd like to call a method that either returns false, or an integer. At the moment my code is:
int winningID = -1;
if((ID = isThereAWinner()) != -1) {
// use the winner's ID
} else {
// there's no winner, do something else
}
private int isThereAWinner() {
// if a winner is found
return winnersID;
// else
return -1;
}
I don't like the if((ID = isThereAWinner()) != -1) bit as it doesn't read very well, but unlike C you can't represent booleans as integers in Java. Is there a better way to do this?
I would use something similar to Mat's answer:
class Result {
public static Result withWinner(int winner) {
return new Result(winner);
}
public static Result withoutWinner() {
return new Result(NO_WINNER);
}
private static final int NO_WINNER = -1;
private int winnerId;
private Result(int id) {
winnerId = id;
}
private int getWinnerId() {
return winnerId;
}
private boolean hasWinner() {
return winnerId != NO_WINNER;
}
}
This class hides the implementation details of how you actually represent if there were no winner at all.
Then in your winner finding method:
private Result isThereAWinner() {
// if a winner is found
return Result.withWinner(winnersID);
// else
return Result.withoutWinner();
}
And in your calling method:
Result result = isThereAWinner();
if(result.hasWinner()) {
int id = result.getWinnerId();
} else {
// do something else
}
It may seem a little bit too complex, but this approach is more flexible if there would be other result options in the future.
What about something like:
private int getWinnerId() {
// return winner id or -1
}
private boolean isValidId(int id) {
return id != -1; // or whatever
}
int winnerId = getWinnerId();
if (isValidId(winnerId)) {
...
} else {
...
}
This is all quite subjective of course, but you usually expect an isFoo method to provide only a yes/no "answer".
The problem is you are trying to return two values at once. The approach you have taken is the simplest for this. If you want a more OO or design pattern approach I would use a listener pattern.
interface WinnerListener {
void onWinner(Int winnerId);
void noWinner();
}
checkWinner(new WinnerListener() {
// handle either action
});
private void checkWinner(WinnerListener wl) {
// if a winner is found
wl.onWinner(winnersID);
// else
wl.noWinner();
}
This approach works well with complex events like multiple arguments and multiple varied events. e.g. You could have multiple winners, or other types of events.
I'm afraid not. To avoid errors caused by mistaking if(a == b) for if(a = b), Java removes the conversion between boolean type and number types. Maybe you can try exceptions instead, but I think exception is somewhat more troublesome. (My English is not quite good. I wonder if I've made it clear...)
Perhaps you may wish to consider exceptions to help you with your understanding of asthetics of coding.
Use Integer instead of int and return null instead of -1. Look from this point: "I am returning not integer, but some object that represents winner identity. No winner - no instance"
Joe another suggestion, this is constructed based on #Mat and #buc mentioned little while ago, again this is all subjective of course I'm not sure what the rest of your class/logic is. You could introduce an enum with different ResultStatuses if it makes sense within the context of your code/exmaple.
As Matt mentioned you would expect isValid method to return a boolean yes/no (some may also complain of readability)
public enum ResultStatus {
WINNER, OTHER, UNLUCKY
}
This could be an overkill as well and depends on the rest of your logic (and if logic is expanding) but I thought I'll suggest nonetheless my two cents! So therefore in your public class (similar to #bloc suggested) you could have a method such as below that will return the status of the result checked.
public ResultStatus getResultStatus() {
if (isWinner()) {
return ResultStatus.WINNER;
} else {
return isOtherCheck() ? ResultStatus.OTHER : ResultStatus.UNLUCKY;
}
}

Need help extrapolating Java code

If anyone familiar with Rebecca Wirfs-Brock, she has a piece of Java code found in her book titled, Object Design: Roles, Responsibilities, and Collaborations.
Here is the quote >Applying Double Dispatch to a Specific Problem
To implement the game Rock, Paper, Scissors we need to write code that determines whether
one object “beats” another. The game has nine possible outcomes based on the three kinds of
objects. The number of interactions is the cross product of the kinds of objects. Case or switch statements are often governed by the type of data that is being operated on. The
object-oriented language equivalent is to base its actions on the class of some other object. In Java,
it looks like this
Here is the piece of Java code on page 16 '
import java.util.*;
import java.lang.*;
public class Rock
{
public static void main(String args[])
{
}
public static boolean beats(GameObject object)
{
if (object.getClass.getName().equals("Rock"))
{
result = false;
}
else if (object.getClass.getName().equals("Paper"))
{
result = false;
}
else if(object.getClass.getName().equals("Scissors"))
{
result = true;
}
return result;
}
}'
===>This is not a very good solution. First, the receiver needs to know too much about the argument.
Second, there is one of these nested conditional statements in each of the three classes. If new
kinds of objects could be added to the game, each of the three classes would have to be modified.
Can anyone share with me how to get this "less than optimal" piece of code to work in order to see it 'working'. She proceeds to demonstrate a better way, but I will spare you.
Thanks
I would start by defining classes RPSSystem and RPSObject. The code to construct the classic RPS-game would look like this:
RPSObject rock = new RPSObject("Rock");
RPSObject paper = new RPSObject("Paper");
RPSObject scissors = new RPSObject("Scissors");
RPSSystem classicRPS = new RPSSystem(rock, paper, scissors);
// new RPSSystem(Collection<RPSObject> objects) possible too
classicRPS.defineBeatsRule(rock, scissors);
classicRPS.defineBeatsRule(paper, rock);
classicRPS.defineBeatsRule(scissors, paper);
RPSSystem would have a method
int fight(RPSObject a, RPSObject b)
which would return -1 when a wins, 1 when b wins and 0 when the result is not defined. Internally RPSObjects could be stored in a list and beating rules could be stored in a matrix (columns and rows would match the indices of the objects in the list). If multiple instances of similar RPSObject should be allowed, the equals-method of RPSObject should be written accordingly.
Having a separate class for each object in the system seems a bit too complicated.
EDIT:
Complete classes:
package rpsgame;
public final class RPSObject {
private final String name;
public RPSObject(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String toString() {
return getName();
}
}
package rpsgame;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public final class RPSSystem {
private final List<RPSObject> objects;
private final int[][] beatsRules;
public static final int WINS = 1;
public static final int TIE = 0;
public static final int LOSES = -1;
public RPSSystem(RPSObject... objects) {
this.objects = Arrays.asList(objects.clone());
this.beatsRules = new int[objects.length][objects.length];
}
void defineBeatsRule(RPSObject winner, RPSObject loser) {
if (winner.equals(loser)) throw new IllegalArgumentException();
int winnerIndex = getObjectIndex(winner);
int loserIndex = getObjectIndex(loser);
beatsRules[winnerIndex][loserIndex] = WINS;
beatsRules[loserIndex][winnerIndex] = LOSES;
}
public int fight(RPSObject a, RPSObject b) {
int aIndex = getObjectIndex(a);
int bIndex = getObjectIndex(b);
return beatsRules[aIndex][bIndex];
}
public List<RPSObject> getObjects() {
return Collections.unmodifiableList(objects);
}
private int getObjectIndex(RPSObject o) {
int index = objects.indexOf(o);
if (index < 0) throw new IllegalArgumentException();
return index;
}
// test
public static void main(String[] args) {
RPSSystem classicRPS = buildClassicRPS();
List<RPSObject> objects = classicRPS.getObjects();
for (RPSObject a: objects) {
for (RPSObject b: objects) {
int result = classicRPS.fight(a, b);
switch (result) {
case RPSSystem.WINS:
System.out.println(a + " beats " + b);
break;
case RPSSystem.TIE:
System.out.println(a + " vs " + b + " is tied");
break;
case RPSSystem.LOSES:
System.out.println(a + " loses against " + b);
break;
}
}
}
}
private static RPSSystem buildClassicRPS() {
RPSObject rock = new RPSObject("Rock");
RPSObject paper = new RPSObject("Paper");
RPSObject scissors = new RPSObject("Scissors");
RPSSystem classicRPS = new RPSSystem(rock, paper, scissors);
classicRPS.defineBeatsRule(rock, scissors);
classicRPS.defineBeatsRule(paper, rock);
classicRPS.defineBeatsRule(scissors, paper);
return classicRPS;
}
}
Just add RPSSystem.EVERYONE_DIES and defineEveryoneDiesRule(...) and you're ready for
rps.add(atombomb);
rps.defineBeatsRule(atombomb, scissors);
rps.defineBeatsRule(atombomb, rock);
rps.defineBeatsRule(atombomb, paper);
rps.defineEveryoneDiesRule(atombomb, atombomb);
Use an enum for dealing with it (RPSObj) that has a beats(RPSObj o) method, with each enum element having a Set passed in, stored as beatset. Then, the beats(RPSObj o) method can do return beatset.contains(o);. Simples :)
Edit: You can actually use an EnumSet as the Set implementation, which should be even more efficient than other set implementations :)
You might want to take a look at this thread:
Using inheritance and polymorphism to solve a common game problem
It seems to be around the same subject.
I think personally I would simply have a utility-like class that would contain the 'beats' method. The 'beats' method would take two GameObject objects as parameters.
That way I could just pass in the two objects (rock, paper or scissors) and perform the necessary logic. Now if you add a new object, you don't change anything other than the 'beats' method within the utility class keeping things encapsulated from your main.
ryan's link is nice, it contains several other ideas for handling this situation as well.
So here's how I fixed it. I first made a new interface called GameObject since they refer to it!
public interface GameObject
{
public boolean beats(GameObject g);
}
The type didn't exist so referring to it wasn't going to work so great.
Here's my new code for Rock with comments on changes:
import java.util.*;
import java.lang.*;
public class Rock implements GameObject //Need to be an instance of GameObject somehow!
{
public static void main(String args[])
{
}
public boolean beats(GameObject object) //This isn't static anymore
{
boolean result = false; //Need to declare and initialize result
if (((Object)object).getClass().getName().equals("Rock")) //getClass should have ()
{
result = false;
}
else if (object.getClass().getName().equals("Paper")) //getClass should have ()
{
result = false;
}
else if(object.getClass().getName().equals("Scissors")) //getClass should have ()
{
result = true;
}
return result;
}
}
EDIT: You seemed to be asking for how to fix the code and not the better way to do it. I believe this should be good to go for you now.

Categories

Resources