City cannot be converted to summable - java

So I'm supposed to use a "Summable" interface to add up the populations of the cities. I've been staring at it for an hour but still can't find my error. Please Help!
This is my tester
public class SummableTester extends ConsoleProgram
{
public void run()
{
City cookie = new City("Coookie", 20000);
City taco = new City("Taco", 10000);
System.out.println(taco.getValue());
}
}
City Class:
public class City
{
private String name;
private int population;
public City(String name, int population)
{
this.name = name;
this.population = population;
}
public String getName()
{
return this.name;
}
public int getValue()
{
return this.population;
}
public int add(Summable other)
{
return getValue() + other.getValue();
}
}
Summable:
public interface Summable
{
public int add(Summable other);
public int getValue();
}

You implemented Summable interface in your City class, but forgot to include implements Summable in city class.
public class City implements Summable {
}

Related

Issue with Varargs with multiple classes in Java

So I'm having an issue when I create Variable Arguments with multiple classes. As you can see on the code below, I'm just trying to take in multiple cities and districts in a random order and try to print out the population of the entire state. Except the issue is I have no idea how to iterate through my CAndD array in order to add all of the populations together.
Code:
public class Main {
public static void main(String args[]) {
State S = new State("Florida", new District("Miami-Dade", 2752000),
new City("Miami", 463347),
new City("Tampa", 385430),
new District("Broward", 1936000));
System.out.println("The Population is: " + S.getPopulation());
}
}
class CitiesAndDistricts {
}
class City extends CitiesAndDistricts{
String name;
int population;
public City(String name, int population) {
this.name = name;
this.population = population;
}
}
class District extends CitiesAndDistricts{
String name;
int population;
public District(String name, int population) {
this.name = name;
this.population = population;
}
}
class State {
String name;
int population;
CitiesAndDistricts[] CAndD;
public State(String name, CitiesAndDistricts ... entities) {
this.name = name;
CAndD = entities;
for(int i = 0; i < CAndD.length; i++) {
this.population += CAndD[i].population;
}
}
public int getPopulation() {
return population;
}
}
If anyone can help me solve this problem that'd be great!
Please Have a look at below code, I have moved population variable from City and District to parent class:
public class Main {
public static void main(String args[]) {
State S = new State("Florida", new District("Miami-Dade", 2752000),
new City("Miami", 463347),
new City("Tampa", 385430),
new District("Broward", 1936000));
System.out.println("The Population is: " + S.getPopulation());
}
}
class CitiesAndDistricts {
int population;
}
class City extends CitiesAndDistricts{
String name;
public City(String name, int population) {
this.name = name;
this.population = population;
}
}
class District extends CitiesAndDistricts{
String name;
public District(String name, int population) {
this.name = name;
this.population = population;
}
}
class State {
String name;
int population;
CitiesAndDistricts[] CAndD;
public State(String name, CitiesAndDistricts ... entities) {
this.name = name;
CAndD = entities;
for(int i = 0; i < CAndD.length; i++) {
this.population += CAndD[i].population;
}
}
public int getPopulation() {
return population;
}
}
Designing an empty parent class seems not good. In your code, the class City and District are the same. I assume that you want to know the type of place (City or District). The better solution is moving all the properties of the child class to the parent class. The class CitiesAndDistricts would be:
class CitiesAndDistricts {
String name;
int population;
public CitiesAndDistricts(String name, int population} {
this.name = name;
this.population = population;
}
}
From this parent class, you can extend to class City and District as below:
class City extends CitiesAndDistricts{
public City(String name, int population) {
super(name, population);
}
}
class District extends CitiesAndDistricts{
public District(String name, int population) {
super(name, population);
}
}

UML with subclasses

public class Student {
private String name;
private long id;
private String grade;
private int[] test;
private int NUM_TESTS;
public Student(){
name="Un";
id=0;
grade="Un";
test=new int[0];
NUM_TESTS=5;
}
public Student(String x, long z) {
name=x;
id=z;
}
public void setName(String n) {
name=n;
}
public void setID(long i) {
id=i;
}
public void setGrade(String g) {
grade=g;
}
/*public void setTestScore(int t,int s) {
test=t;
test=s;
}
public int getTestScore(int) {
return test;
}*/
public int getNumTests() {
return NUM_TESTS;
}
public String getName() {
return name;
}
public long getID() {
return id;
}
public String getGrade() {
return grade;
}
public String toString() {
return getTestScore()+getNumTests()+getName()+getID()+getGrade();
}
/*public void calculateResult() {
int sum=0;
for (int t:test)sum+=t;
double average= 1.0t*sum/5;*/
}
}
Here is my code I have spaced out the places where I am having the issues. I am writing a Student subclass with subclasses undergrad and postgrad.
Here is the UML
I don't understand how to correctly implement testScore if it is not one of the variables? Nevermind the calculate result I'll fix that myself. I am also unsure if my constructors are accurate. All the students do five exams that's a constant
setTestScore(int t, int s)... I do recommend to use carefully chosen names (identifiers). For example if you just rename the parameters to: setTestScore(int testNumber, int score) you can be more familiar what should you inplement.
test = new int[0];isn't what you want. You want test = new int[NUM_TESTS]
Try to reconsider method setTestScore(int testNumber, int score)
first parameter is actually the index in the array of test and the second is the value.
So, your method should be something like this:
public void setTestScore(int testNumber, int score) {
test[testNumber] = score;
}
I just gave you some guidance for your own implementation...
First of all, It seems that Student class should be abstract. because each student is UnderGraduate or PostGraduate.
Secondly, you should extend the child classes from Student class.
I hope the below code be helpful:
abstract class Student {
private String name;
private long id;
private String grade;
private int[] test;
private final int NUM_TESTS = 5;
public Student(){
name = "UN";
id = 0;
grade = "UN";
test = new int[NUM_TESTS];
}
public Student(String name, long id){
this.name = name;
this.id = id;
}
#Override
public String toString() {
//TODO: write your desire toString method
return getNUM_TESTS()+getName()+getId()+getGrade();
}
abstract void claculateResult();
public int getTestScore(int testNumber){
if(testNumber >= NUM_TESTS)
return 0;
return test[testNumber];
}
public void setTestScore(int testNumber, int score){
if(testNumber >= NUM_TESTS)
return;
test[testNumber] = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public int[] getTest() {
return test;
}
public void setTest(int[] test) {
this.test = test;
}
public int getNUM_TESTS() {
return NUM_TESTS;
}
}
and the UnderGraduate class would be:
public class UnderGraduate extends Student{
public UnderGraduate(){
}
public UnderGraduate(String name, long id){
super();
}
#Override
void claculateResult() {
//TODO: DO whatever you want
}
}
remember that the PostGraduate class is same as UnderGraduate.

how to search recipe based on important ingredients ? java android

I want to search recipe which match with shopping list items and it will suggest recipe to user based on most important ingredients like in Banana MilkShake {milk and banana} could make banana milkshake alone {sugar and vanilla} are optional,if I add items on shopping list like {banana,milk} it will search recipe on the basis of these ingredients rather {banana,milk,sugar and vanilla}
for example:
Banana Milk Shake Ingredients:
**Ingredient Name
1.banana (important)
2.milk (important)
3.vanilla (optional/not important)
4.sugar (optional/not important)
**Shopping List**
banana
milk
egg
rice
We could also make Banana Milkshake without sugar and vanilla so important ingredients will be milk and banana.
public class Ingredient implements Serializable{
private String name;
private String quantity;
public Ingredient(){
}
public Ingredient(String name,String quantity){
this.name=name;
this.quantity=quantity;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return name;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
}
and my working code:
public Set<Recipe> searchByIngredient(List<ShoppingList> shop, List<Recipe> list) {
int matchedItems = 0;
Set<Recipe> result = new HashSet<Recipe>();
for (Recipe rn : list) {
boolean recipeMatched = false;
for (ShoppingList r : shop) {
for (int i = 0; i < rn.getIngre().size(); i++) {
if (rn.getIng(i).contains(r.getName())) {
matchedItems++;
int temp = matchedItems;
if(temp >= 2){
result.add(rn);
recipeMatched = true;
}
}
if (recipeMatched)
break;
}
if (recipeMatched)
break;
}
matchedItems = 0;
}
return result;
}
public class Recipe implements Serializable{
private String instructions;
private String recName;
private String image;
private List<Ingredient> ing = new ArrayList<Ingredient>();
public Recipe(){
}
public Recipe(String item,String quan){
this.ing.add(new Ingredient(item, quan));
}
public List<Ingredient> getIngre(){
return ing;
}
public String getIng(int i){
return ing.get(i).toString();
}
public void setIngredients(List<Ingredient> item){
this.ing = item;
}
public String getRecName() {
return recName;
}
public void setRecName(String recName) {
this.recName = recName;
}
// #Override
public String toString() {
return recName;
}
public String getInstructions() {
return instructions;
}
public void setInstructions(String instructions) {
this.instructions = instructions;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
Based on your comments. You could add another variable to your Ingredient class. Like this:
public class Ingredient implements Serializable{
private String name;
private String quantity;
private boolean isImportant;
public Ingredient(){
}
public Ingredient(String name,String quantity){
this.name=name;
this.quantity=quantity;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return name;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public boolean getIsImportant() {
return isImportant;
}
public void setIsImportant(boolean isImportant) {
this.isImportant= isImportant;
}
}
Then you could check in the recipe if all the important ingredients are present or not.

Implementing a simple text adventure game in java (working with interfaces)

I was doing some reading on ECS/Composition over inheritance and decided to modify a text adventure game that I'm currently working on to better understand the concept.
I decided to try it using a specific weapon in my game.
Now, in my game the logic is that every Weapon is considered an IGameObject. With all this in mind I came up with the following:
Weapon Interface:
public interface IWeapon {
int getWeaponDamage();
}
Weapon class:
public class Weapon implements IWeapon {
private int damage;
public Weapon(int damage)
{
this.damage = damage;
}
#Override
public int getWeaponDamage() {
return this.damage;
}
IGameObject interface:
public interface IGameObject {
String getGameObjectID();
String getGameObjectName();
String getGameObjectDescription();
}
GameObject class:
public class GameObject implements IGameObject {
private String ID;
private String name;
private String Desc;
public GameObject(String ID, String name, String Desc)
{
this.ID = ID;
this.name = name;
this.Desc = Desc;
}
The abstract class that uses all this:
public abstract class GameGun implements IGameObject, IWeapon {
IGameObject gameObj;
IWeapon weaponObj;
//Left out getters to keep it simple and easy to read.
public GameGun(IGameObject game, IWeapon weapon)
{
this.gameObj = game;
this.weaponObj = weapon;
}
public void fire()
{
System.out.println("Shot Fired");
}
public void reload()
{
//implementation for reload method
}
Putting it all together:
Main Method:
GameObject sleep = new GameObject("SLP-1","Sleep Weapon","A Custom Made Gun");
Weapon sleepDamage = new Weapon(10);
GameGun sleepWeapon = new SleepWeapon(sleep,sleepDamage);
Questions:
I just wanted to know if my implementation was correct?
If not, how would I correct it?
I've been correcting many stuff and get it working. You can play with it now :D
PLease take the gist in order to have all the working code.
CONSOLE
Revolver Gun:Gun reloaded
Revolver Gun:Gun shots => 10 damage(s)
Basic Sword:Sword cuts => 5 damage(s)
Basic Sword:Sword cuts => 5 damage(s)
Basic Sword:Sword cuts => 5 damage(s)
Revolver Gun:Gun shots => 10 damage(s)
CODE
package com.rizze.test.labs.sof.gamegun;
import org.junit.Test;
public class GameGunTest {
#Test
public void betterCode2() {
Game sleep = new Game("SLP-1","Sleep Weapon","A Custom Made Gun");
Gun gun = new Gun();
Sword sword = new Sword();
gun.hit();
sword.hit();
sword.hit();
sword.hit();
gun.hit();
}
public class Gun implements IWeapon {
private int damage;
private String name;
public Gun(int damage)
{
this.damage = damage;
this.reload();
}
public Gun()
{
this.damage = 10;
this.name= "Revolver Gun";
this.reload();
}
#Override
public int getDamages() {
return this.damage;
}
/**
*
* #return damages
*/
#Override
public int hit() {
System.out.println( this.name + ":Gun shots => "+damage +" damage(s)");
return this.damage;
}
#Override
public void reload() {
System.out.println(this.name+":Gun reloaded");
}
}
public class Sword implements IWeapon {
private String name;
private int damage;
public Sword(String name){
this.damage = 5;
this.name=name;
}
public Sword(){
this.damage = 5;
this.name="Basic Sword";
}
#Override
public int getDamages() {
return this.damage;
}
/**
*
* #return damages
*/
#Override
public int hit() {
System.out.println( name+ ":Sword cuts => "+damage +" damage(s)");
return damage;
}
#Override
public void reload() {
System.out.println( name+ ":Sword - skipped reload" );
}
}
public class Game implements IGame {
private String id;
private String name;
private String desc;
public Game(String ID, String name, String Desc)
{
this.id = ID;
this.name = name;
this.desc = Desc;
}
#Override
public String getId() {
return this.id;
}
#Override
public String getName() {
return this.getName();
}
#Override
public String getDesc() {
return this.desc;
}
}
}
//IGAME
public interface IGame {
String getId();
String getName();
String getDesc();
}
//IWEAPON
package com.rizze.test.labs.sof.gamegun;
public interface IWeapon {
int getDamages();
int hit();
void reload();
}
GIST
here is the complete GIST :https://gist.github.com/jeorfevre/92d093853bfd3fc5c666b915b309abf1

Creating an object and calling it

this is my current code to store rooms(it compiles fine) but in the UML there is a variable called addEquipment and there is also another class called Equipment to be defined. I'm having trouble wrapping my head around what I'm supposed to do with this. Am I supposed to create and call an object called Equipment? what goes in addEquipment?
public class Room {
//begin variable listing
private String name;
private int id;
private int capacity;
private String equipmentList;
//begins get methods for variables
public String getName(){
return name;
}
public int getID(){
return id;
}
public int getCapacity(){
return capacity;
}
public String getEquipmentList(){
return equipmentList;
}
// Set the variables
public void setName(String aName){
name=aName;
}
public void setID(int anID){
id=anID;
}
public void setCapacity(int aCapacity){
capacity=aCapacity;
}
public void setEquipmentList(String anEquipmentList){
equipmentList=anEquipmentList;
}
public String addEquipment(String newEquipment, String currentEquipment){
}
//Create room object
public Room(int capacity, String equipmentList) {
setCapacity(capacity);
setEquipmentList(equipmentList);
}
//Convert variables to string version of room
public String toString(){
return "Room "+name+", capacity: "+capacity+", equipment: "+getEquipmentList();
}
}
You can create a new class Equipment and modify your attribute equipmentList to be a List:
public class Equipment {
private String name;
public Equipment(String name) {
this.name = name;
}
}
public class Room {
//begin variable listing
private String name;
private int id;
private int capacity;
private List<Equipment> equipmentList = new ArrayList<Equipment>();
//begins get methods for variables
public String getName(){
return name;
}
public int getID(){
return id;
}
public int getCapacity(){
return capacity;
}
public List<Equipment> getEquipmentList(){
return equipmentList;
}
// Set the variables
public void setName(String aName){
name=aName;
}
public void setID(int anID){
id=anID;
}
public void setCapacity(int aCapacity){
capacity=aCapacity;
}
public void setEquipmentList(List<Equipment> anEquipmentList){
equipmentList=anEquipmentList;
}
public String addEquipment(String newEquipment, String currentEquipment){
Equipment oneEquipment = new Equipment(newEquipment);
equipmentList.add(oneEquipment);
}
//Create room object
public Room() {
setCapacity(capacity);
setEquipmentList(equipmentList);
}
//Convert variables to string version of room
public String toString(){
String capacity=String.valueOf(getCapacity());
String room = "Room "+name+", capacity: "+capacity+", equipment: "+getEquipmentList();
return room;
}
}
In the method addEquipment, you can create a new Equipment and add it to equipmentList, like code above.
An Equipment class could be anything. Lets assume the "Equipment"-class has a String called "name" as it's attribute
public class Equipment {
String name;
public Equipment( String name) {
this.name = name;
}
public String getName() {
return this.name
}
}
When you extend your Room class by the requested "addEquipment" method, you can do something like this.
public class Room {
... // Your code
private int equipmentIndex = 0;
private Equipment[] equipment = new Equipment[10]; // hold 10 Equipment objects
public void addEquipment( Equipment eq ) {
if ( equipmentIndex < 10 ) {
equipment[ equipmentIndex ] = eq;
equipmentIndex++;
System.out.println("Added new equipment: " + eq.getName());
} else {
System.out.println("The equipment " + eq.getName() + " was not added (array is full)");
}
}
}
Now when you call
room.addEquipment( new Equipment("Chair") );
on your previously initialized object of the Room-class, you will get
"Added new equipment: Chair"
Hope this helps a bit.
PS: The code is untestet (maybe there hides a syntax error somewhere)

Categories

Resources