Setter being told it hasn't be created but it has - java

pretty much I've made a program that goes a little like this
Players are added to an array
they are then all placed against each other(just like a football match, every team plays every team)
They are then randomized
the program should display the end result(if you win a game you get 3 points) etc..
I keep getting a message from Eclipse saying ".setScore has NOT been coded..
TestGame.java
public class TestGame {
static Players ceri = new Players("Ceri", 0);
static Players harry = new Players("Harry", 0);
static Players matthew = new Players("Matthew", 0);
static Players james = new Players("James",0);
static Players kwok = new Players("Kwok",0);
static Players lewis = new Players("Lewis",0 );
static Game League = new Game();
int Ceri = 0;
public static void main(String[] args) {
League.addPlayers(ceri);
League.addPlayers(matthew);
League.addPlayers(james);
League.addPlayers(kwok);
League.addPlayers(lewis);
League.addPlayers(harry);
League.randomize();
League.Results();
}
}
Game.java
public class Game extends TestGame {
Scanner s = new Scanner(System.in);
private Players[] people = new Players[6];
private int counter = 0;
List<String> Matches = new ArrayList<String>();
public void addPlayers(Players obj){
people[counter] = obj;
counter++;
System.out.println(obj.getName());
}
public String randomize(){
for(int i = 0; i < people.length; i++){
for(int j = i + 1; j < people.length; j++){
if(people[i].equals(people[j].getName())){
continue;
} else {
Matches.add(people[i].getName() + " V " + people[j].getName());
}
}
}
return null;
}
public String Results(){
while(!Matches.isEmpty()){
int Game = (int)(Math.random() * Matches.size());
String Verses = (String)Matches.get(Game);
System.out.println(Verses);
System.out.println("Who has won?");
String name = s.nextLine();
//**ISSUE LIES HERE**
if(Verses.contains(name)){
if(name == "ceri"){
ceri.setScore(3);
} else if(name == "harry"){
harry.setScore(3);
}else if (name == "matthew"){
matthew.setScore(3)
} else if(name == "lewis"){
lewis.setScore(3)
}else if ( name == "james"){
james.setScore(3)
}else if(name == "kwok"){
kwok.setScore(3);
}
}
Matches.remove(Game);
System.out.println(one);
return null;
}
return null;
}
}
WHERE ECLIPSE SAYS .setScore ISNT.
Players.java
public class Players {
private String name;
private int score;
public Players(String name, int score){
this.name = name;
this.score = score;
}
public String getName(){
return this.name;
}
public int getScore() {
return this.score;
}
public void setScore(int score) {
this.score =+ score;
}
}

All the players are static members of TestGame class. They can access only static methods of Players now. So that is why you are getting the error.

First off, there are compile errors. Please see merlin2011's answer for reference.
As to your actual issue, your Players (ceri, harry, matthew, etc.) are static members of TestGame...but are not publicly exposed. This means that other objects can't see them, and so can't access them. Add the public keyword to them:
public class TestGame {
public static Players ceri = new Players("Ceri", 0);
public static Players harry = new Players("Harry", 0);
public static Players matthew = new Players("Matthew", 0);
public static Players james = new Players("James",0);
public static Players kwok = new Players("Kwok",0);
public static Players lewis = new Players("Lewis",0 );
...
}
Now that they are publicly exposed, you need to reference them correctly. Your Game class doesn't know what ceri is when you call setScore(3), Since it is not a member of that class. Instead, you need to tell it where ceri is located; in your TestGame class. For reference, I've also used the traditional string equality comparison function.
if(name.equals("ceri")){
TestGame.ceri.setScore(3);
}
Use this format for the other IF statements you have.

Your code has a couple of issues, but neither of them is related to setScore not being defined.
You are missing semicolons in the following block.
if(Verses.contains(name)){
if(name == "ceri"){
ceri.setScore(3);
} else if(name == "harry"){
harry.setScore(3);
}else if (name == "matthew"){
matthew.setScore(3)
} else if(name == "lewis"){
lewis.setScore(3)
}else if ( name == "james"){
james.setScore(3)
}else if(name == "kwok"){
kwok.setScore(3);
}
}
You are not using equals for String comparison in the block above.
Here is a corrected version:
if(Verses.contains(name)){
if(name.equals("ceri")){
ceri.setScore(3);
} else if(name.equals("harry")){
harry.setScore(3);
} else if (name.equals("matthew")){
matthew.setScore(3);
} else if(name.equals("lewis")){
lewis.setScore(3);
} else if ( name.equals("james")){
james.setScore(3);
} else if(name.equals("kwok")){
kwok.setScore(3);
}
}

Related

How would I make a loop in java that will ask the user to pick a class from the array list and if they enter an invalid value to ask again?

My code:
import java.util.Scanner;
public class PartyTest {
public static void main(String[] args) {
Party party = new Party();
String[] classNames = {"theif","warrior","wizard","steve","bard"};
Hero Carmilla = new Hero("Carmilla");
Hero Alucard = new Hero("Alucard");
Hero Steve = new Hero("steve");
Hero Sypha = new Hero("sypha");
System.out.println("The avaliable classes are:\n" );
for(int i = 0; i < classNames.length; i++) {
System.out.println(classNames[i]);
}
Scanner ask = new Scanner(System.in);
System.out.println("Enter the class for Carmilla\n");
String nameC = ask.next();
Boolean temp;
I was attempting to do a while loop but I was not sure what conditions to use
while(temp = true) {
if(nameC.equalsIgnoreCase("theif")) {
Carmilla.sethClass(nameC);
temp = false;;
break;
} else {
System.out.println("Invalid class try again");
}
}
System.out.println(Carmilla);
Hero class just sets the values for everything, I would use (depending on the name of the person I'm calling) `Carmilla.sethClass(nameC)', which just sets the name of the chosen class to the hero class.
I want to ask the user what class they would like to set for each person(they are the names stated with Hero in front of them)and if the user does not type one of the classNames value then they are told that its an invalid statement and to try again, which will then ask again what class they want for (in this example) Carmilla.
Here is one way to accomplish it.
The class with main method is below. A few notes about it. First, I made the Party class just an ArrayList of Hero objects, since I'm assuming that a party is just a collection of heroes. This makes asking names for each of the four heroes easier because we can loop through the party list.
Next, I moved the instantiation of the Hero objects into the initialization of the party so that the list already contains our Hero objects.
I utilized a for-each loop to check and assign classes to each Hero and a while loop to redirect the user back if they entered an invalid class. I check whether the class is valid using the boolean validClass. The final output of running this is shown at the very bottom.
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class PartyTest {
public static void main(String[] args) {
List<Hero> party = Arrays.asList(new Hero("Carmilla"),
new Hero("Alucard"),
new Hero("steve"),
new Hero("sypha"));
String[] classNames = { "theif", "warrior", "wizard", "steve", "bard" };
Scanner ask = new Scanner(System.in);
for (Hero hero : party) {
if (hero.getHclass()
.equals("Default")) {
boolean validClass = false;
while (!validClass) {
System.out.println("Enter the class for " + hero.getName());
String hClass = ask.nextLine();
for (String name : classNames) {
if (hClass.equals(name)) {
validClass = true;
}
}
if (validClass) {
hero.setHclass(hClass);
}
}
}
}
party.forEach(hero -> {
System.out.println(hero.getName() + " has class " + hero.getHclass());
});
}
}
The Hero class:
public class Hero {
private String name;
private String hclass = "Default";
public Hero(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHclass() {
return hclass;
}
public void setHclass(String hclass) {
this.hclass = hclass;
}
}
Output:
Use for-each loop to match the entered name against the classNames
Code:
import java.util.Scanner;
import java.io.*;
//Hero class replace with your class
class Hero{
String name="";
String className="";
public Hero(){}
public Hero(String name){
this.name=name;
}
public void sethClass(String className){
this.className=className;
}
#Override
public String toString(){
return "Name : "+name+" className : "+className;
}
}
public class PartyTest {
public static void main(String[] args) throws IOException{
//Party party = new Party();
String[] classNames = {"theif","warrior","wizard","steve","bard"};
Hero Carmilla = new Hero("Carmilla");
Hero Alucard = new Hero("Alucard");
Hero Steve = new Hero("steve");
Hero Sypha = new Hero("sypha");
System.out.println("The avaliable classes are:\n" );
for(int i = 0; i < classNames.length; i++) {
System.out.println(classNames[i]);
}
//Scanner ask = new Scanner(System.in);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the class for Carmilla\n");
boolean matched=false;
while(!matched) {
String nameC = br.readLine();
//Use for-each loop to match the entered name
for(String name : classNames){
if(nameC.equalsIgnoreCase(name)) {
Carmilla.sethClass(nameC);
matched=true;//Matched
break;
}
}
if(matched)break;
System.out.println("Invalid class try again\n");
}
System.out.println(Carmilla);
}
}
OUTPUT:
$ javac PartyTest.java && java PartyTest
The avaliable classes are:
theif
warrior
wizard
steve
bard
Enter the class for Carmilla
blaba
Invalid class try again
qwertr
Invalid class try again
Wizard
Name : Carmilla className : Wizard

Problems creating an object using a class and then putting it on a array

So I'm trying to do a User class and then trying to do an array for it
however every time I create a student it don't add to the array.
I tried to change names etc but its really a problem in code.
public class UsersList {
User student;
User[] studentList = new User[49];
public UsersList() {
}
public void createUser(int userNumber) {
String numberToString = String.valueOf(userNumber);
if (numberToString.length() == 9) {
for (int i = 0; i < 49; i++) {
if (studentList[i] == null) {
studentList[i] = new User(userNumber);
}
}
}
}
}
public class User {
public int userNumber;
private boolean isolation;
private String state;
public User(int number) {
userNumber = number;
isolation = false;
}
}
If someone can help me I would be greatful.
I added the following simple test method to UsersList class to demonstrate that the code is fine and you need to provide appropriate userNumber value when calling createUser method:
public static void main(String[] args) {
UsersList list = new UsersList();
int userNumber = 1;
list.createUser(userNumber); // insufficient length
System.out.printf("all nulls for %d? %s%n", userNumber, Arrays.stream(list.studentList).filter(Objects::isNull).count() == list.studentList.length);
userNumber = 123_456_789;
list.createUser(userNumber); // length of the number is 9
System.out.printf("no nulls for %d? %s%n", userNumber, Arrays.stream(list.studentList).filter(Objects::nonNull).count() == list.studentList.length);
}
Output:
all nulls for 1? true
no nulls for 123456789? true
However, you may want also to initialize the instance variable student.

Object Interaction n Java

I'm making a pokemon game for fun and I want to be able to reduce the HP of the two pokemon fighting. What i'm doing is calling a method inside an 'if statement',which is inside of a loop, an have Java call a method from another class to reduce the HP.
Below is the Code as I have it...
import java.util.Scanner;
public class gameTester {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner inputSystem = new Scanner(System.in);
Scanner playerName = inputSystem;
System.out.println("Hello Player please type in the name of your pokemon.");
pokemon playerOne = new pokemon(playerName.nextLine());
pokemon playerTwo = new pokemon();
System.out.println(playerOne.toString());//shows player pokemon
System.out.println(playerTwo.toString());//shows enemy pokemon
System.out.println("Let's Battle! What do you do?");
while (playerOne.getHealthPoints() >= 0 || playerTwo.getHealthPoints() >= 0){
System.out.println("1. Bite 2. Slash 3. Flee");
int userChoice = inputSystem.nextInt();
if (userChoice == 3){
break;
}
else if (userChoice == 1 || userChoice == 2){
//playerTwo.getHealthPoints()
}
}
}
}
Also like I said above i'm calling a method from another class..
public class pokemon {
private String pokemonSpecies;
private String nameOfpokemon;
private int attackDamage;
private int healthPoints;
public pokemon (){
nameOfpokemon = "Enemy";
attackDamage = 1;
healthPoints = 3;
}
public pokemon (String desiredName){
nameOfpokemon = desiredName;
attackDamage = 1;
healthPoints = 3;
}
public String getPokemonSpecies() {
return pokemonSpecies;
}
public void setPokemonSpecies(String pokemonSpecies) {
this.pokemonSpecies = pokemonSpecies;
}
public String getNameOfpokemon() {
return nameOfpokemon;
}
public void setNameOfpokemon(String nameOfpokemon) {
this.nameOfpokemon = nameOfpokemon;
}
public int getAttackDamage() {
return attackDamage;
}
public void setAttackDamage(int attackDamage) {
this.attackDamage = attackDamage;
}
public int getHealthPoints() {
return healthPoints;
}
public void setHealthPoints() {
this.healthPoints = healthPoints;
}
#Override
public String toString(){
return "Name of Pokemon: " + nameOfpokemon + " Attack Damage: " + attackDamage + " Health Points: " + healthPoints;
}
public int enemyDamage(int damage){
setHealthPoints() = getAttackDamage() - getHealthPoints();
}
}
The last bit about public in enemyDamage(...) is where I'm stuck. I don't know if I should send an integer that can reduce the HP. Or is I should use this method to call other methods...
Any advice?
First use can change your setHealthPoints() method to
public void setHealthPoints(int healthPoints) {
this.healthPoints = healthPoints;
}
Here I assume
damage = attack/damage done by opponent's pokemon.
getHealthPoints() = my pokemon's health.
Then enemyDamage() goes in this way.
public void enemyDamage(int damage){
setHealthPoints(getHealthPoints() - damage);
}

Calling variables between different classes through methods

I'm doing an assignment for my computer science class.
I've done quite a bit of the assignment, but I'm having a little bit of trouble pulling the individual variables from the classes. We are just getting into classes and objects and this is our first assignment regarding them so I don't completely understand all of it. So far I've been able to print out the teams, but I haven't been able to pull the individual wins, losses, OTL and OTW so that I can compute whether or not each individual team is a winning team.
What I have done so far is create a class called winningRecord and getPoints, which returns a boolean deciding whether it's a winning team or not. (The formula for a winning team is if the points are > Games Played * 1.5 (as that is an even record).
I don't know how to pull the stats, as it has to be written in the HockeyTeam class. I have set it up so that the constructor sets the variables publicly so that the can be accessed, but as far as accessing them, I'm stumped.
As far as storing them once I am able to access them, would I just make a parallel method that has the points for each team, with just one digit assigned to each bin?
Here is all of the code, thanks for looking.
public class A1Q2fixed {
public static void main(String[] parms) { // main method
processHockeyTeams();
}
/*****************************/
public static void processHockeyTeams() { // processing method
boolean[] winningRecord;
HockeyTeam[] hockeyTeams;
hockeyTeams = createTeams();
printTeams(hockeyTeams);
System.out.print("*********************\n");
printWinningTeams();
winningRecord = HockeyTeam.winningRecord(hockeyTeams);
// printWinningTeams(hockeyTeams);
}
/*********************************/
public static void printTeams(HockeyTeam[] hockeyTeams) {
for (int i = 0; i < hockeyTeams.length; i++) {
System.out.println(hockeyTeams[i]);
}
}
public static void printWinningTeams() {
}
public static HockeyTeam[] createTeams() {
HockeyTeam[] teams;
HockeyTeam team;
int count;
teams = new HockeyTeam[HockeyTeams.getNumberTeams()];
team = HockeyTeams.getTeam();
for (count = 0; (count < teams.length) && (team != null); count++) {
teams[count] = team;
team = HockeyTeams.getTeam();
}
return teams;
}
}
/* hockey team class *******/
class HockeyTeam {
public String name;
public int wins;
public int otw;
public int otl;
public int losses;
public HockeyTeam(String name, int wins, int otw, int otl, int losses) {
this.name = name;
this.wins = wins;
this.otw = otw;
this.otl = otl;
this.losses = losses;
}
public String toString() {
System.out.println(name);
return " W:" + wins + " OTW:" + otw + " OTL:" + otl + " L:" + losses;
}
public static boolean[] winningRecord(HockeyTeam[] hockeyTeam) {
boolean array[] = new boolean[hockeyTeam.length];
String name;
int wins;
int otw;
int otl;
int losses;
for (int i = 0; i < hockeyTeam.length; i++) {
System.out.println(HockeyTeam.name);
}
return array;
}
public static int getPoints() {
int points = 0;
return points;
}
}
/* hockey teams class *******************/
class HockeyTeams {
private static int count = 0;
private static HockeyTeam[] hockeyTeams = {
new HockeyTeam("Canada", 5, 3, 0, 0),
new HockeyTeam("Russia", 5, 1, 1, 2),
new HockeyTeam("Finland", 3, 2, 1, 3),
new HockeyTeam("Sweden", 4, 1, 1, 4),
new HockeyTeam("USA", 1, 2, 2, 3), };
public static int getNumberTeams() {
return hockeyTeams.length;
}
public static HockeyTeam getTeam() {
HockeyTeam hockeyTeam;
hockeyTeam = null;
if (count < hockeyTeams.length) {
hockeyTeam = hockeyTeams[count];
count++;
}
return hockeyTeam;
}
}
Thanks,
Matt.
Sorry but I was only able to understand only a part of your question,from what I understood it seems you are not able to access individual wins, losses, OTL and OTW. I hope this answers your question if not please clarify a bit
To access OTL,OTW have a loop as below:
public class A1Q2fixed
{
public static void main(String[] parms) // main method
{
processHockeyTeams();
}
/*****************************/
public static void processHockeyTeams() // processing method
{
boolean[] winningRecord;
HockeyTeam[] hockeyTeams;
hockeyTeams = createTeams();
printTeams(hockeyTeams);
System.out.print("*********************\n");
printWinningTeams();
winningRecord = HockeyTeam.winningRecord(hockeyTeams);
for(HockeyTeam h:hockeyTeams)
{
System.out.println(h.losses);//To access and print losses
System.out.println(h.otw);//To access and print otw
System.out.println(h.otl);//To access and print otl
}
// printWinningTeams(hockeyTeams);
}
/*********************************/
public static void printTeams(HockeyTeam[] hockeyTeams)
{
for (int i = 0; i < hockeyTeams.length; i++)
{
System.out.println(hockeyTeams[i]);
}
}
public static void printWinningTeams()
{
}
public static HockeyTeam[] createTeams()
{
HockeyTeam[] teams;
HockeyTeam team;
int count;
teams = new HockeyTeam[HockeyTeams.getNumberTeams()];
team = HockeyTeams.getTeam();
for (count=0; (count<teams.length) && (team!=null); count++)
{
teams[count] = team;
team = HockeyTeams.getTeam();
}
return teams;
}
}
Also declare name as Static in HockeyTeam

Add weapons to inventory

I am trying to add weapons to a player inventory. It's kind of hard to explain, so I'll try my best. What I have are a class for each weapon, a class for Combat, and a class for the Player. I am trying to get it to where when the Random number equals a certain number, it will add a weapon to the player inventory. I will put my code Below.
Combat Class:
public class Combat {
M4 m4 = new M4();
M16 m16 = new M16();
M9 m9 = new M9();
Glock glock = new Glock();
SCAR Scar = new SCAR();
Player player = new Player();
final int chanceOfDrop = 3;
static boolean[] hasWeapon = {false, true};
public static int ranNumberGen(int chanceOfDrop) {
return (int) (Math.random()*5);
}
private void enemyDead() {
boolean canDrop = false;
if(ranNumberGen(chanceOfDrop)==0){
canDrop = true;
}
if(canDrop == true){
if(ranNumberGen(0) == 1) {
Player.addInvetory(m4.weaponName(wepName), m4.weaponAmmo(wepAmmo)); //Issues here. wepName & wepAmmo cannot be resolved into variable
//Should I just delete the line?
//Trying to get it to add the weapon M4 to the player inventory.
//Maybe use an ArrayList? If so I need a couple pointers on how to implement this.
}
}
}
}
M4 Class:
public class M4 implements Armory {
//Weapon classes are practically identical except for differences in the name wepDamage and wepAmmo.
public Integer weaponAmmo(int wepAmmo) {
wepAmmo = 10;
return wepAmmo;
}
public Integer weaponDamage(int wepDamage) {
wepDamage = 5;
return wepDamage;
}
public String weaponName(String wepName) {
wepName = "M4";
return wepName;
}
Player Class:
public class Player {
public static int health = 100;
//Player Class.
public static void addInvetory(String wepName, int wepAmmo) {
Player.addInvetory(wepName, wepAmmo);
}
public static void removeInventory(String wepName, int wepAmmo) {
Player.addInvetory(wepName, wepAmmo);
}
public static void removeAll(String wepName, int wepAmmo) {
Player.removeAll(wepName, wepAmmo);
}
Interface:
public interface Armory {
//Interface implemented by all of the weapons classes.
public Integer weaponAmmo(int wepAmmo);
public Integer weaponDamage(int wepDamage);
public String weaponName(String wepName);
Hope you can help!
class Weapon {
private final String name;
private final int damage;
private final int ammo;
public Weapon(final String name,final int damage,final int ammo) {
this.name = name;
this.damage = damage;
this.ammo = ammo;
}
public Weapon clone() {
return new Weapon(this.name,this.damage,this.ammo);
}
public String getName() {
return this.name;
}
public int getAmmo() {
return this.ammo;
}
public int getDamage() {
return this.damage;
}
}
class WeaponFactory {
static WeaponFactory factory;
public static WeaponFactory getWeaponFactory() {
if(factory == null) {
factory = new WeaponFactory();
}
return factory;
}
private ArrayList<Weapon> weapons = new ArrayList<Weapon>();
private Random random;
private WeaponFactory() {
//TODO: Fix Ammo and Damage
weapons.add(new Weapon("M4",0,0));
weapons.add(new Weapon("M16",0,0));
weapons.add(new Weapon("M9",0,0));
weapons.add(new Weapon("Glock",0,0));
weapons.add(new Weapon("SCAR",0,0));
}
public Weapon getWeapon() {
int w = random.nextInt(weapons.length);
return weapons.get(w).clone();
}
}
class Combat {
...
private void enemyDead() {
if(ranNumberGen(chanceOfDrop)==0){
Player.addInventory(WeaponFactory.getWeaponFactory().getWeapon());
}
}
}
You can use an array of Armory and the generate a random number from 0 to the size of the array as an index to the array to decide which weapon to add.
Okay dude, since your question about creating a programming language was closed, I'm answering it through here:
I think that your idea is great! Don't give up on it, yet don't get too excited. I would try all the options that you have heard of(interpreted route AND the Compiled route). If you can get either of those to work, then you may proceed to go into further detail with the language creation. It's going to take a while though. Be patient!

Categories