Can i know how to serialize and deserialize this program , im not able to figure it out , should i use arrays to store the content that is being printed out..?
It has two classes in two seperate calss files.
one is player and the other is SnakeAndladder1
Player class
------------
package coll.org;
public class Player {
private String name;
private int score;
Player(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
SnakeAndladder1 class
---------------------
package coll.org;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Map;
import java.util.Scanner;
public class SnakeAndladder1 {
ArrayList<String> name1=new ArrayList<String>(); //an array to store players names
public int throwdice() //to calculate the dice value
{
return (int)(Math.random()*6)+1;
}
public int ladder(int curscore)
{
Hashtable<Integer,Integer> ld = new Hashtable<Integer,Integer>();
//Map<Integer,Integer> ldmap = new Map<Integer,Integer>();
ld.put(15,30);
ld.put(45,71);
ld.put(25,62);
ld.put(81,91);
ld.put(9,39);
while(curscore!=15 || curscore!=45 || curscore!=25 || curscore!=81 || curscore!=9)
{ return curscore;}
int v=ld.get(15);
return v;
}
public int snake(int curscore)
{
Hashtable<Integer,Integer> ld = new Hashtable<Integer,Integer>();
ld.put(29,11);
ld.put(81,48);
ld.put(30,6);
ld.put(92,71);
ld.put(58,19);
while(curscore!=29 || curscore!=81 || curscore!=30 || curscore!=92 || curscore!=58 )
{return curscore;}
int v=ld.get(curscore);
return v;
}
public boolean Game (Player p){
//int score=0;
//String name;
int v=0;
//name=name1.toString();
System.out.println("Click y to roll dice");
Scanner in2=new Scanner(System.in);
String yes=in2.nextLine();
if(yes.equalsIgnoreCase("y"))
{
v=throwdice();
System.out.println("dice value:"+v);
}
p.setScore(p.getScore()+v);
if(p.getScore()==100)
{
System.out.println("User:"+p.getName()+"got"+v+".Winner!!!");
return false;
}
if (p.getScore()>100)
{
p.setScore(p.getScore()-v);
System.out.println("Current score of"+p.getName()+"is"+p.getScore());
return true;
}
int s1=ladder(p.getScore());
if(s1==p.getScore())
{
p.setScore(snake(p.getScore()));
System.out.println("Current score of"+p.getName()+"is"+p.getScore());
return true;
}
else
{
p.setScore(s1);
System.out.println("Current score of"+p.getName()+"is"+p.getScore());
return true;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int l=0;
//boolean flag=true;
System.out.println("Enter the number of players:");
Scanner in=new Scanner(System.in);
int n=in.nextInt();
System.out.println("Enter Players names in order:");
ArrayList<Player> p1=new ArrayList<Player>(); //an array to store players names
for (int i=0;i<n;i++)
{
Scanner in1=new Scanner(System.in);
String name2=in1.nextLine();
Player p = new Player(name2);
p1.add(p);
//name1.add(name2);
}
//Snakeandladder1[] players = new Snakeandladder1[n];
//ArrayList<Snakeandladder1> player=new ArrayList<Snakeandladder1>();
//for(int i=0;i<n;i++)
//player.add(new Snakeandladder1());
// SnakeAndladder1 players[];
// players = new SnakeAndladder1[n];
SnakeAndladder1 sk = new SnakeAndladder1();
while(true)
{
for (int i=0;i<n;i++)
{
Player p3=p1.get(i);
boolean flag = sk.Game(p3);
if (flag == false)
{System.exit(0);}
}
}
}
}
This program is allows any number of players and ask for the user to enter y to roll dice, i have got the output but i am not able to serialize it. Is there a way to take the output after the execution of the program is complete and serialize it ??
A neat library exists to serialize objects into XML files (and of course deserialize them after). It's extremely simple to use and very effective.
http://x-stream.github.io/tutorial.html
Related
I'm creating an object of type Lightmode, which is a class.
There's also a Smartlamp class which is having a variable of custom data of type Lighmodes and I want to show my defined data type value over there.
I'm trying to create an object and then insert a string against my Lightmode data type which is showing error. I want to print like this:
Name: lamp1
Location: 3.1
Switched On: false
Mode: STANDARD
Here mode is lightmode datatype and I'm getting a problem over it.
...
public class LightModes
{
String NIGHT_MODE;
String SOFT_MODE;
String STANDARD_MODE;
public String getNIGHT_MODE() {
return NIGHT_MODE;
}
public void setNIGHT_MODE(String NIGHT_MODE) {
this.NIGHT_MODE = NIGHT_MODE;
}
public String getSOFT_MODE() {
return SOFT_MODE;
}
public void setSOFT_MODE(String SOFT_MODE) {
this.SOFT_MODE = SOFT_MODE;
}
public String getSTANDARD_MODE() {
return STANDARD_MODE;
}
public void setSTANDARD_MODE(String STANDARD_MODE) {
this.STANDARD_MODE = STANDARD_MODE;
}
public LightModes() {
this.NIGHT_MODE = "NIGHT";
this.STANDARD_MODE = "STANDARD";
this.SOFT_MODE = "SOFT";
}
}...
...package smart.home.app;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Step5 {
public static void main(String[] args) throws IOException {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
int size,mode;
int displayindex=1;
String name;
double location,temperature;
boolean status=false;
System.out.println("Enter number of size of Fridge you want to add.");
Scanner in = new Scanner(System.in);
size=in.nextInt();
// TODO code application logic here
SmartLamp[] smartLamp=new SmartLamp[size];// creating an array object of smartdevice class
//
for(int j=0;j<size;j++)
{
System.out.println("Enter Lamp name.");
name=input.readLine();
System.out.println("Enter Lamp Location.\\hint(1.1)");
Scanner devicelocation=new Scanner(System.in);
location=devicelocation.nextDouble();
System.out.println("Enter Lamp Mode.(1 for Night 2 for Soft 3 for Standard)");
Scanner lampmode=new Scanner(System.in);
mode=lampmode.nextInt();
System.out.println("Enter Lamp status.1 for ON, 0 for OFF.");
Scanner devicestatus=new Scanner(System.in);
int currentstatus=devicestatus.nextInt();
if(currentstatus==1)
{
status=true;
}
else if(currentstatus==0)
{
status=false;
}
LightModes light = null;
smartLamp[j]=new SmartLamp(light.NIGHT_MODE, name, location, status);
}
//////////////Display Data////////////////////////////
for(int i=0;i<size;i++)
{
System.out.println("-Smart lamp "+displayindex+" -");
System.out.println(smartLamp[i].toString());
System.out.println("---------------------------------------------");
displayindex++;
}
}
}...
...public class SmartLamp extends SmartDevice{
private LightModes lightModes;
public LightModes getLightModes() {
return lightModes;
}
public void setLightModes(LightModes lightModes) {
this.lightModes = lightModes;
}
public SmartLamp(String name, double location, boolean switchedOn) {
super(name, location, switchedOn);
}
public SmartLamp(LightModes lightModes, String name, double location, boolean switchedOn) {
super(name, location, switchedOn);
this.lightModes = lightModes;
}
#Override
public String toString() {
return "SmartLamp{"+"\nName."+getName()+"\nLocation."
+getLocation() + "\nSwitchedOn."+isSwitchedOn()+
"\nMode=" + getLightModes() + '}';
}
}...
I downloaded your code and added the missing class SmartDevice. Your code contains two compiler errors.
name = input.readLine();
This line throws java.io.IOException which is an unchecked exception and hence must be handled by your code. There are several ways to do this, one of which is to add throws IOException to method main() in class Step5.
smartLamp[j]=new SmartLamp(light.NIGHT_MODE, name, location, status);
The first argument to SmartLamp constructor is an instance of class LightModes but you are passing a String. You need to create an instance of LightModes.
Here is your code with my modifications that get rid of the two compiler errors.
(Note: The below code includes my guessed implementation of class SmartDevice.)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Step5 {
public static void main(String[] args) throws IOException { // Change here.
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
int size, mode;
int displayindex = 1;
String name;
double location, temperature;
boolean status = false;
System.out.println("Enter number of size of Fridge you want to add.");
Scanner in = new Scanner(System.in);
size = in.nextInt();
SmartLamp[] smartLamp = new SmartLamp[size];// creating an array object of smartdevice class
for (int j = 0; j < size; j++) {
System.out.println("Enter Lamp name.");
name = input.readLine(); // throws java.io.IOException
System.out.println("Enter Lamp Location.\\hint(1.1)");
Scanner devicelocation = new Scanner(System.in);
location = devicelocation.nextDouble();
System.out.println("Enter Lamp Mode.(1 for Night 2 for Soft 3 for Standard)");
Scanner lampmode = new Scanner(System.in);
mode = lampmode.nextInt();
System.out.println("Enter Lamp status.1 for ON, 0 for OFF.");
Scanner devicestatus = new Scanner(System.in);
int currentstatus = devicestatus.nextInt();
if (currentstatus == 1) {
status = true;
}
else if (currentstatus == 0) {
status = false;
}
LightModes light = new LightModes(); // Change here.
light.setNIGHT_MODE(light.getNIGHT_MODE()); // Change here.
smartLamp[j] = new SmartLamp(light, name, location, status); // Change here.
}
//////////////Display Data////////////////////////////
for(int i=0;i<size;i++)
{
System.out.println("-Smart lamp "+displayindex+" -");
System.out.println(smartLamp[i].toString());
System.out.println("---------------------------------------------");
displayindex++;
}
}
}
class LightModes {
String NIGHT_MODE;
String SOFT_MODE;
String STANDARD_MODE;
public String getNIGHT_MODE() {
return NIGHT_MODE;
}
public void setNIGHT_MODE(String NIGHT_MODE) {
this.NIGHT_MODE = NIGHT_MODE;
}
public String getSOFT_MODE() {
return SOFT_MODE;
}
public void setSOFT_MODE(String SOFT_MODE) {
this.SOFT_MODE = SOFT_MODE;
}
public String getSTANDARD_MODE() {
return STANDARD_MODE;
}
public void setSTANDARD_MODE(String STANDARD_MODE) {
this.STANDARD_MODE = STANDARD_MODE;
}
public LightModes() {
this.NIGHT_MODE = "NIGHT";
this.STANDARD_MODE = "STANDARD";
this.SOFT_MODE = "SOFT";
}
}
class SmartDevice {
private String name;
private double location;
private boolean switchedOn;
public SmartDevice(String name, double location, boolean switchedOn) {
this.name = name;
this.location = location;
this.switchedOn = switchedOn;
}
public String getName() {
return name;
}
public double getLocation() {
return location;
}
public boolean isSwitchedOn() {
return switchedOn;
}
}
class SmartLamp extends SmartDevice {
private LightModes lightModes;
public LightModes getLightModes() {
return lightModes;
}
public void setLightModes(LightModes lightModes) {
this.lightModes = lightModes;
}
public SmartLamp(String name, double location, boolean switchedOn) {
super(name, location, switchedOn);
}
public SmartLamp(LightModes lightModes, String name, double location, boolean switchedOn) {
super(name, location, switchedOn);
this.lightModes = lightModes;
}
#Override
public String toString() {
return "SmartLamp{" + "\nName." + getName() + "\nLocation." + getLocation()
+ "\nSwitchedOn." + isSwitchedOn() + "\nMode=" + getLightModes() + '}';
}
}
I am making a PVP RPG game and the display box comes out with "null" instead of the variable I have already declared.
I have declared the variable as the user's next input and stored that information in the variable. Then when I try to display the variable, it only shows "null",
System.out.println("Welcome, Player One and Player Two!");
delay(1500);
System.out.println("What is your name, Player One?");
playerOne.name = userInput.nextLine();
I already declared playerOne as a new character(different class)
System.out.println("Your turn, " + playerOne.name+".");
if (p1Swordgo == 1) {
This is the problem I'm coming up with. It is in the same main method and the variables are declared in the main method, and yes I imported scanner and declared the variable userInput
I expected it to be what the user typed in, but it came up with null. As I've said previous, it's in the same main method and nothing should go wrong, but it comes up with "null"
import java.util.Random;
import java.util.Scanner;
public class Arena {
Random generator = new Random();
public static void main(String[] args) {
Character playerOne = new Character(10,10,0);
Character playerTwo = new Character(10,10,0);
boolean P1hasClass = false;
boolean P2hasClass = false;
int p1Swordgo = 0;
int p2Alchgo = 0;
int p2Archgo = 0;
Scanner userInput = new Scanner(System.in);
System.out.println("Welcome, Player One and Player Two!");
delay(1500);
System.out.println("What is your name, Player One?");
playerOne.name = userInput.nextLine();
delay(1000);
System.out.println("Hello, " +playerOne.name +".");
delay(1000);
System.out.println("What is your name, Player Two?");
playerTwo.name = userInput.nextLine();
delay(1000);
System.out.println("Hello, " +playerTwo.name +".");
delay(1500);
countdown();
System.out.println("Your turn, " + playerOne.name+".");
if (p1Swordgo == 1) {
if (p2Archgo == 1 || p2Alchgo == 1) {
if (playerOne.move == 1){
System.out.println("What do you want to do?" +'\n' +"1 = Move into range of " +playerTwo.name +'\n' +"2 = Heal" +'\n' +"3 = Forfeit");
int P1Choice = userInput.nextInt();
if (P1Choice == 1) {
playerOne.move --;
System.out.println(playerOne.move);
}
}
}
}
}
public static void delay ( int time){
try {
Thread.sleep(time);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
public static void countdown() {
delay(500);
System.out.println("Get ready to fight in 5,");
delay(1000);
System.out.println("4");
delay(1000);
System.out.println("3");
delay(1000);
System.out.println("2");
delay(1000);
System.out.println("1");
delay(1000);
System.out.println("Fight!");
delay(750);
}
}
And then in a class called Character
public class Character {
public int strength;
public double health;
public int move;
public String name;
public Character(double health, int strength, int move) {
this.health = health;
this.strength = strength;
this.name = name;
this.move = move;
}
}
And in a class called SwordFighter
public class SwordFighter extends Character {
public SwordFighter() {
super(60,15, 1);
}
}
And in a class called Archer
public class Archer extends Character{
public Archer() {
super(45,20, 0);
}
}
And finally, in a class called Alchemist
public class Alchemist extends Character {
public Alchemist() {
super(50,15, 0);
}
}
Thank you for your patience, by the way
Once the two players have chosen their name and you have set it using playerOne.name = userInput.nextLine();, you assign a different object, with a null name, to playerOne:
playerOne = new SwordFighter();
So, after this line has been executed, playerOne.name is null.
I am working on an assignment and I can not figure out what to do. I have three different Java classes. And I am trying to use the methods in one class to do something in a different class. I am making a very primitive playlist program. I have to check to see if the playlist is full, if its not i have to ask the title and artist. Then I have to call my method using the title and artist as parameters. I was wondering if anyone could point me in the right direction as to what I had to do to call the method? I still don't completely understand loops either but i know that I have to use a for loop in order to do this. Thankyou for your time.
Here is my code:
Main Class
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
PlayList p = new PlayList (5);
Scanner sc = new Scanner(System.in);
String command;
String title;
String artist;
System.out.println("Enter a to add, r to remove, d to display,or q to
quit:");
command = sc.nextLine();
while (!command.equals("q")) {
// Interpret command
if (command.equals("a")) {
//add song
for (int i = 0; i <= PlayList.isFull(title, artist);i++) {
if(songs[i])== null {
songs[i] = filled;
}
}
} else if (command.equals("r")) {
// Remove a song
System.out.print("Title: ");
title = sc.nextLine();
p.remove(title);
} else if (command.equals("d")) {
// Fill this in
}
// Get the next command
System.out.println("Enter a to add, r to remove, d to display, or q to
quit:");
command = sc.nextLine();
}
System.out.println("Program Ended");
}
}
PlayList Class
public class PlayList {
private Song [] songs;
private int filled;
public PlayList (int size){
songs = new Song[size];
}
public boolean isFull() {
return (filled >= songs.length);
}
public void add(String t, String a) {
for (int i = 0; i < songs.length; i++){
if (songs[i] == null){
songs[i] = new Song(t,a);
filled++;
}
}
}
public void display() {
for (int i = 0; i < songs.length; i++){
if (songs[i] != null) {
System.out.println(songs[i]);
}
}
}
public void remove(String t) {
//return t?
for (int i = 0; i < songs.length; i--){
if (songs[i] == null){
songs[i] = null;
break;
}
}
}
}
Song Class
public class Song {
String title;
String artist;
public Song (String t, String a) {
title = t;
artist = a;
}
public String toString() {
return "Title: " + title + " " + "Artist: " + artist;
}
}
First of all you are using isFull function of class PlayList wrong.
for (int i = 0; i <= PlayList.isFull(title, artist);i++)
isFull is a no argument function, and you are using it with passing 2 arguments.
isFull function returns a boolean value (i.e. true/false), but you are comparing it with an int, which does not make any sense.
isFull is not a static function. Therefore you cannot use it directly with class name.
-either you will need to declare function isFull as static.
public static boolean isFull()
-or you will need to create an object of class PlayList in class Main and then call the java function using that java object.
Also, your Function remove is not performing any task
if (songs[i] == null){
songs[i] = null;
}
It is checking if songs[i] is already null and then it sets it back to null, which does not make any sense.
And you should increment i (i.e. i++) not decrement it (i.e. i--)
for (int i = 0; i < songs.length; i--)
If you want to call method from another class that method must be a static method. Then you can call it using Class name and Method name.
For an example;
public class main(){
A a = new A();
a.x();
}
public class A{
public static void x(){};
}
You called isFull method with two parameters but your PlayList class does not have any parameter for isFull method. That is an error.
I re-write your assignment class set using ArrayList for PlayList class. Follow this codes. Hope you can understand it's concept of OOP(Follow this tutorials. https://www.javatpoint.com/java-oops-concepts).
Main Class
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
PlayList p = new PlayList (5);
Scanner sc = new Scanner(System.in);
String command;
String title;
String artist;
System.out.println("Enter a to add, r to remove, d to display,or q to quit:");
command = sc.nextLine();
while (!command.equals("q")) {
// Interpret command
if (command.equals("a")) {
//add song
System.out.println("Enter Title:");
title = sc.nextLine();
System.out.println("Enter Artist:");
artist = sc.nextLine();
if(!p.isFull()) {
p.add(title, artist);
System.out.println("Added Success!");
}
else
System.out.println("Sorry,Playlist is full");
} else if (command.equals("r")) {
// Remove a song
System.out.print("Title: ");
title = sc.nextLine();
p.remove(title);
} else if (command.equals("d")) {
// Fill this in
p.display();
}
// Get the next command
System.out.println("Enter a to add, r to remove, d to display, or q to quit:");
command = sc.nextLine();
}
System.out.println("Program Ended");
}
}
PlayList Class
import java.util.ArrayList;
import java.util.List;
public class PlayList {
private static List<Song> songs;
private static int filled;
private static int size = 0;
public PlayList (int s){
songs = new ArrayList<>();
size = s;
}
public static boolean isFull() {
return (filled == size);
}
public static void add(String t, String a) {
songs.add(new Song(t,a));
filled++;
}
public void display() {
for (int i = 0; i < songs.size(); i++){
if (songs.get(i) != null) {
System.out.println(songs.get(i));
}
}
}
public void remove(String t) {
//return t?
for (int i = 0; i < songs.size(); i++){
if (songs.get(i).title == t){
songs.remove(i);
break;
}
}
}
public static int getSize(){
return songs.size();
}
}
Song Class is same as you wrote.
I have a Enum Class, a Player Class, and a class called Lisa that extends Player class. Im trying to randomly generate a value (PAPER, ROCK, or SCISSORS) from the Enum. Error: "The primitive type int of Roshambo does not have a field ROCK." Any advice or pointers would be greatly appreciated. It may be apparent, but this is my fists Java class and Google and Stackoverflow searches have not helped. Here is what I have coded so far:
UPDATE: Thanks for all the assistance. I've updated my whole program below. I was wondering if anyone could suggest the best way/place possible to implement logic to determine the winner/loser of the game? Here is the full code:
MAIN
package gameOfRoshambo;
import java.util.Scanner;
public class RoshamboApp {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to Roshambo!");
System.out.println("Enter your name:");
//Create a new payer
Player1 player1 = new Player1();
String name = sc.nextLine();
player1.setName(name);
String choice = "y";
while (choice.equalsIgnoreCase("y")) {
System.out.println("Hello " + name + ". " + "Would you like to play against Bart or Lisa? (B/L)");
String opponent = sc.next();
if(opponent.equalsIgnoreCase("B")){
//Create a new Bart opponent
Bart bart = new Bart();
System.out.println(player1.getName() + ": " + player1.getChoice());
System.out.println("Bart: " + bart.getRoshambo());
}
else if (opponent.equalsIgnoreCase("L")){
//Create a new Lisa opponent
Lisa lisa = new Lisa();
System.out.println(player1.getName() + ": " + player1.getChoice());
System.out.println("Lisa: " + lisa.getRoshambo());
}
// Ask user if they want to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
//Close Scanner
System.out.println("Thanks for playing! Goodbye!");
sc.close();
}
}
ENUM
package gameOfRoshambo;
public enum Roshambo
{ROCK, PAPER, SCISSORS;
public String toString() {
switch(this) {
case ROCK: return "Rock";
case PAPER: return "Paper";
case SCISSORS: return "Scissors";
default: throw new IllegalArgumentException();
}
}
}
PLAYER
package gameOfRoshambo;
abstract class Player {
String name;
Roshambo roshambo;
abstract int generateRoshambo();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Roshambo getRoshambo() {
return roshambo;
}
public void setRoshambo(Roshambo newRoshambo) {
roshambo = newRoshambo;
}
}
PLAYER1
package gameOfRoshambo;
import java.util.Scanner;
public class Player1 extends Player{
String player1 = "";
public Player1(){
super();
}
Scanner scan = new Scanner(System.in);
public Roshambo getChoice(){
System.out.println("Enter Choice: Paper, Rock, Scissors (r/p/s): ");
char playerChoice = scan.nextLine().toUpperCase().charAt(0);
switch (playerChoice){
case 'R':
return Roshambo.ROCK;
case 'P':
return Roshambo.PAPER;
case 'S':
return Roshambo.SCISSORS;
}
System.out.println("Invalid input!");
return getChoice();
}
public String getPlayer1() {
return player1;
}
public void setPlayer1(String player1) {
this.player1 = player1;
}
#Override
int generateRoshambo() {
// TODO Auto-generated method stub
return 0;
}
}
BART
package gameOfRoshambo;
public class Bart extends Player {
public Bart(){
super();
}
public Roshambo getRoshambo(){
return Roshambo.ROCK;
}
#Override
int generateRoshambo() {
// TODO Auto-generated method stub
return 0;
}
}
LISA
package gameOfRoshambo;
import java.util.Random;
public class Lisa extends Player {
private Random rand;
public Lisa(){
super();
rand = new Random();
}
public Roshambo getRoshambo(){
int shoot = rand.nextInt(3);
return Roshambo.values()[shoot];
}
#Override
int generateRoshambo() {
return 0;
}
}
You should store your roshambo field as a Roshambo not an int and update your setter and getter accordingly. This is because in Java Enums cannot be casted to int. See the below stack overflow link for explanation:
Cast Int to enum in Java
Field names should start with a lower case
Use Roshambo.values()[choice]
Get rid of the 1 + in 1 + rand.nextInt(3); because the nextInt() method has the first enum value in position 0. So
Roshambo.values()[0] = ROCK
Roshambo.values()[1] = PAPER
Roshambo.values()[2] = SCISSORS
In the Lisa constructor, change to rand = new Random() instead of Random rand = new Random() to avoid assigning to a new local variable which you lose once the constructor finishes
See the code snippets I've attached below for you
Player Class
package gameOfRoshambo;
abstract class Player {
String name;
Roshambo roshambo;
abstract int generateRoshambo();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Roshambo getRoshambo() {
return roshambo;
}
public void setRoshambo(Roshambo newRoshambo) {
roshambo = newRoshambo;
}
}
Lisa Class
package gameOfRoshambo;
import java.util.Random;
public class Lisa extends Player {
private Random rand;
public Lisa(){
super();
rand = new Random();
}
public Roshambo getRoshambo(){
int choice = rand.nextInt(3);
return Roshambo.values()[choice];
}
#Override
int generateRoshambo() {
return 0;
}
}
Also with the new above implementation you don't use the abstract int generateRoshambo() method so consider removing it and its implementation in Lisa...
Your field Roshambo is of type int. I think you want to declare it as something more like this:
Roshambo roshambo;
It is bad practice to capitalize field names. In this case, it confused you because you mixed up the field name with the type. You will have to replace int with Roshambo in several other places in your code.
I'm not sure how eloquently I can really explain what I don't understand/need help with, I'm still Very new to Object Oriented Programming. This is regarding my coursework and I don't expect anyone to do it for me, I just need help understanding how to move on, and if I'm even on the right track.
Ok, so on to my question. Basically, I am attempting to create an arraylist which will hold a few objects which themselves has a bunch of information(obviously), my spec said to create an abstract class, which will be extended by my constructor class, which I did. The abstract class has a few variables (decided by spec) But I dont know how to move them over to my extended class.
I'll post my code below, and I hope it makes sense. I'd be very thankful for any help you all could provide. I'm very confused right now.
Basically, I would love to know, A) How do I create an object in my arraylist which will be able to contain everything in SportsClub and FootballClub, and preferably all the variables user inputted.
And B) I don't know how to print The object, When I print right now I get coursework.FootballClub#49233bdc, Which I'm sure there's a reason for but I need the information in the objects to display, E.g. name. And if possible to sort the results by alphabetical order with respect to name? I hope this is all written ok. Sorry and Thank you in advance.
package coursework;
import java.util.*;
/**
*
* #author w1469384
*/
public class PremierLeagueManager implements LeagueManager{
public static void main(String[] args) {
Scanner c1 = new Scanner(System.in);
Scanner c2 = new Scanner(System.in);
ArrayList<FootballClub> PL = new ArrayList<FootballClub>();
int choice;
System.out.println("Enter 1; To create a club, 2; To Delete a Club, 3; To display all clubs and 99 to close the program");
choice = c1.nextInt();
//Creates and adds a new FootballClub Object
while (choice != 99){
if (choice == 1){
System.out.println("Please Enter The games played for the club");
int played = c1.nextInt();
System.out.println("Please enter the number of wins");
int wins = c1.nextInt();
System.out.println("please enter the number of losses");
int losses = c1.nextInt();
System.out.println("please enter the number of draws");
int draws = c1.nextInt();
System.out.println("please enter the number of goals for");
int goalsFor = c1.nextInt();
System.out.println("please enter the number of goals against");
int goalsAgainst = c1.nextInt();
FootballClub club = new FootballClub(played, wins, losses, draws, goalsFor, goalsAgainst);
PL.add(club);
System.out.println("check");
}
//Deletes a FootballClub Object
if (choice == 2){
}
//Displays all Football Clubs in the PremierLeague array
if (choice == 3){
System.out.println(PL);
}
//Closes the Program 1
choice = c1.nextInt();
}
}
}
public abstract class SportsClub {
public String name;
public String location;
public int capacity;
public void setName(String Name){
name = Name;
}
public void setLocation(String Location){
location = Location;
}
public void setCapacity(int Capacity){
capacity = Capacity;
}
public String getName(){
return name;
}
public String getLocation(){
return location;
}
public int getCapacity(){
return capacity;
}
}
public class FootballClub extends SportsClub {
//Statistics for the club.
int played;
int wins;
int losses;
int draws;
int goalsFor;
int goalsAgainst;
public FootballClub(int gPlayed, int gWins, int gLosses, int gDraws, int gFor, int gAgainst){
played = gPlayed;
wins = gWins;
losses = gLosses;
draws = gDraws;
goalsFor = gFor;
goalsAgainst = gAgainst;
}
public void setPlayed(int newPlayed){
played = newPlayed;
}
public void setWins(int newWins){
wins = newWins;
}
public void setLosses(int newLosses){
losses = newLosses;
}
public void setDraws(int newDraws){
draws = newDraws;
}
public void setGoalsFor(int newGoalsFor){
goalsFor = newGoalsFor;
}
public void setGoalsAgainst(int newGoalsAgainst){
goalsAgainst = newGoalsAgainst;
}
public int getPlayed(){
return played;
}
public int getWins(){
return wins;
}
public int getLosses(){
return losses;
}
public int getDraws(){
return draws;
}
public int getGoalsFor(){
return goalsFor;
}
public int getGoalsAgainst(){
return goalsAgainst;
}
}
FootballClub inherits the variables declared in SportsClub so you can set them as you please.
public FootballClub(
int gPlayed, int gWins, int gLosses, int gDraws, int gFor, int gAgainst,
String inName, String inLocation, int inCapacity
) {
played = gPlayed;
wins = gWins;
losses = gLosses;
draws = gDraws;
goalsFor = gFor;
goalsAgainst = gAgainst;
// set the variables from the superclass
name = inName;
location = inLocation;
capacity = inCapacity;
}
FootballClub also inherits the methods declared in SportsClub so you can use the setters and getters too.
Normally you would create a constructor for SportsClub that sets these and then call that constructor from the FootballClub constructor.
// in SportsClub
protected SportsClub(
String inName, String inLocation, int inCapacity
) {
name = inName;
location = inLocation;
capacity = inCapacity;
}
// in FootballClub
public FootballClub(
int gPlayed, int gWins, int gLosses, int gDraws, int gFor, int gAgainst,
String inName, String inLocation, int inCapacity
) {
super(inName, inLocation, inCapacity);
played = gPlayed;
wins = gWins;
losses = gLosses;
draws = gDraws;
goalsFor = gFor;
goalsAgainst = gAgainst;
}
You should also make your member variables protected or private if you are using setters and getters.
I don't know how to print The object
You need to override toString. There is a short tutorial here.
Also unrelated side note: all Java variable identifiers should start with a lowercase letter.
When you have a method like this:
public void setName(String Name) { name = Name; }
It should be:
public void setName(String inName) { name = inName; }
Or:
public void setName(String name){ this.name = name; }