I have a populate interface that will be getting the current population, setting the population and increasing the population. I have a main that has my planets set in an array list so now what I need to do is to implement the code that will help me to increase the population of that planet based on that planets methods. Here is the population interface.
/**
* This interface models the behavior of planets when travelers arrive
* and when they try to leave.
* #author
*
*/
public interface Populate {
/**
* Get the current population of the planet
* #return the current population of the planet
* #throws Exception if the value of the currentPopulation is none of your business
*/
public int getCurrentPopulation() throws Exception;
/**
* Initialize the current population to a value
* #param currentPopulation The value to initialize to
* #return The new value of the current population, will be currentPopulation
* #throws Exception if the value of the currentPopulation argument is negative
*/
public int setCurrentPopulation(int currentPopulation) throws Exception;
/***
* Increase the population of the planet as travelers arrive.
* #param populationIncrease The amount to increase the current population. Can be negative.
* #return The new current population
*/
public int IncreasePopulation(int populationIncrease);
}
Here is the main:
public class Main {
public static void main(String[] args) {
//this class will run calculations for planets
ArrayList<WorldOfAdams> myPlanets = new ArrayList<WorldOfAdams>();
myPlanets.add(new AllosimaniusSyneca());
myPlanets.add(new BlagulonKappa());
myPlanets.add(new Damogran());
myPlanets.add(new Traal());
//Get current population for each of the planets
for (int i=0; i<myPlanets.size(); i++) {
myPlanets.get(i).getCurrentPopulation();
And each planet has its own set of instructions. There is Allosimanius Syneca, Blagulon Kappa, Damogran and Traal.
Instruction for Allosimanius Syneca are
/**
* This class models the planet Allosimanius Syneca. On this planet travelers are not
*welcome. Anyone landing on the planet at any of the 3 spaceports is immediately put
*to work in the cinnamon mines. No one is ever allowed to leave.
*/
Based of the method of this planet it would appear that the current population would be set to 0 since no one is ever allowed to visit this planet but in the increase population I would need to reflect that there is an increase but that the traveler will go straight to the cinnamon mine. How can I implement this? I know that I need to create code that will increase population and then print statement showing that the increase in population goes "to the cinnamon mines". Do I put this code in the main?
The instructions for Blagulon Kappa:
/***
* All travelers who arrive on this planet are treated with kindness. They may stay as
* long as they like and leave whenever they like. However, they will not reveal the
*current population to anyone. All inquiries are ignored.
Based on this information I would need to print a statement reflecting that the population may increase but the output is "none of their business". Would this planet have a simple print statement and no code to increase population since the output isn't allowed to be known?
The instructions for Damogran:
/***
* Damogran is a mostly peaceful planet that has completely run out of livable land.
*They do not allow anyone to visit the planet or leave it. Ever.
So for this planet I would set the current population at 0 and there is no increase in population.
And lastly the instruction for Traal:
/***
* 10% of the travelers arriving on this planet are immediately fed to the Ravenous
* Bugblatter Beast. Survivors are allowed to come and go as they wish.
For this planet I would need to increase the population but divide that increase by 10% and print a statement with that remaining number that states "fed to Bugblatter Beast"
Just learning how to use interfaces and abstract classes and having a difficult time understanding how to implement all of these classes to run together and be able to give different results. Any help or guidance that you can give is much appreciated!!
Since I didn't want to seem rude, I'll make a guess and suggest your Increase population function should look like this :
#Override
public int IncreasePopulation(int populationIncrease) {
CinnamonMines CM = getCinnamonMines(); //must be defined somewhere in your code
CM.IncreasePopulation(populationIncrease);
return 0;
}
Related
So this one is a bit lengthy. I'm trying to finish off a program where ticket price varies depending on purchase date. I need the Tester.Java to take the info from the objects, and output the proper price depending on the ticket type. I have already set a set of if statements in the Tester, but I am now at an impass on how to finish this program off. I will paste my code below.
Tester (contains the main method):
package tester;
import java.util.Scanner;
public class Tester extends Ticket{
/**
* #param args the command line arguments
*/
public static void main(String[] args){
Scanner db = new Scanner(System.in);
Ticket firstTicket = new Ticket();
System.out.println("The first ticket: "+firstTicket.toString());
int x = 0;
while(x!=2){
if(x==2){
System.out.println("Goodbye.");
}
else{
System.out.println("What type of ticket are you purchasing?");
System.out.println("1.Walk Up");
System.out.println("2.Advance");
System.out.println("3.Student Advance");
int t = db.nextInt();
if(t==1){
}
if(t==2){
}
if(t==3){
}
}
System.out.println("Do you need another ticket?");
x= db.nextInt();
}
}
}
Ticket (Super class):
package tester;
import java.util.Scanner;
public class Ticket {
public int ticket;
public double price;
/**
* holds default values for ticket number and price
*/
public Ticket(){
super();
this.ticket=1;
this.price=15.0;
}
/**
* Stores the values for ticket number and the price, based upon ticket type
* #param ticket
* #param price
*/
public Ticket(int ticket, double price){
this.ticket=ticket;
this.price=price;
}
/**
* returns the value of price
* #return price
*/
public double getPrice(){
return price;
}
#Override
public String toString(){
return "Ticket #" + ticket + " Ticket price: $"+ price;
}
}
Walkup Ticket:
package tester;
/**
*
* #author dylan
*/
public class WalkupTicket extends Ticket{
/**
* holds the price of a walkup ticket 50$
*/
public WalkupTicket(){
this.price=50;
ticket++;
}
}
Advance Ticket:
package tester;
import java.util.Scanner;
public class AdvanceTicket extends Ticket {
/**
* stores the values of an advance ticket, depending on how many days before
* the event it is purchased
*/
public AdvanceTicket(){
Scanner db = new Scanner(System.in);
System.out.println("How many days before the event are you purchasing your ticket?");
int days = db.nextInt();
// days before is 10 or less days
if(days >= 10){
price=30;
ticket++;
}
// days before is more than 10
else{
this.price=40;
ticket++;
}
}
}
Student Advance Ticket:
package tester;
import java.util.Scanner;
public class StudentAdvanceTicket extends AdvanceTicket{
/**
* stores the values of an advance ticket, depending on how many days before
* the event it is purchased, with student discount.
*/
public StudentAdvanceTicket(){
Scanner db = new Scanner(System.in);
System.out.println("How many days before the event are you purchasing your ticket?");
int days = db.nextInt();
System.out.println("Are you a student?");
System.out.println("1. Yes");
System.out.println("2. No");
int stud = db.nextInt();
// days before is 10 or less days
if(days >= 10 && stud == 1){
price=15;
ticket++;
}
// days before is more than 10
if(days <= 10 && stud == 1){
this.price=20;
ticket++;
}
}
}
I feel like I'm making a simple mistake, but I am new to OOP so I'm having bit of trouble with this.
Are you supposed to be saving a total for all tickets bought or just the one ticket at a time total?
For walk-up tickets you don't have to do anything. Its a flat $50 total.
For Advance and StudentAdvance you would create a new object of that type and the way you have it the constructor will display the menu for how many days in advance and what not. You can then get the total from that.
As for the structure of your code it is not ideal. The object's constructor should not have all that code in it. They should have a ShowMenu function that will display the menu to the user and read their input. The constructor should be blank for the most part.
You also don't need three different ticket objects. One ticket object should be able to handle all this by itself. The ticket object can show the menu and handle the different prices based on user input. If you need to save a total or the different tickets you can have an array of ticket objects on the main method. You can then loop through that array to display or sum the tickets.
Hope this helps.
Your question is pretty broad, but well, some thoughts on your input:
Names matter. It is good that you made a first step and that you are using a specific package (instead of the default package); but tester says nothing. You could call it dylan.tickets for example: to make clear A) its your thing and B) it is about that ticket system
It seems that you are serious about your work, thus: do not use a static main to drive testcases. Using JUnit and simple testcases is really easy. And beyond that: driving tests "manually" using a main is cumbersome and error prone. Unit tests are almost automatically automated.
More importantly: tests that just print something are almost useless. If your code behaves unexpectedly, you might only notice when you carefully check that printed output. As said: use unit tests, and Junit assert calls to check expected versus actual results of method calls. Because then you will be told when you make changes that break functionality which was previously working.
You absolutely avoid to ask for user input in so many different places. Meaning: the reasonable thing is that a class has a constructor or setter methods; and that all the arguments required to instantiate the new object are given to that object. If at all, your main uses a scanner and asks the user for input. But all your "business logic" objects do not require any "user interaction" at all. You see, you actually want to start the whole project without using a scanner. You want to hardcode things like AdvancedTicket at = new AdvancedTicket(100); - because now you can easily code all kinds of different objects; and start your program again and again. Your current solution requires you to enter all such data manually ... every time you re-start your program! So: no scanner usage in constructors. Never!
Then: good OO is about behavior, not about state. Meaning: you dont use public fields to spread information. If at all, your fields should be protected; but even that is most often not a good idea. You want to isolate your classes from each other ...
The core problem: it seems that nobody told you yet about FCoI. You should favor composition over inheritance. Meaning: you dont just put A extends B everywhere. There is absolutely no reason that your Tester class extends Ticket. The tester is a Tester, not a ticket!
As said: that last point is the most important one. You are careful about making A a subclass of B; very often, it is more appropriate to maybe have A own a B object, but not to make A a B!
Given a 2D array of a Piece. Has location etc.
Piece[][] board = new Piece[8][8];
Given a pair-value Location object (row, col).
Given a validator that validates moves (standard chess):
public boolean isValidMove(Piece piece, Location toLocation) { ... }
I wrote this:
/**
* Generates a List of possible overtakes for a Piece.
*
* #param piece
* Piece that will be overtaking another.
* #return A List of possible overtakes the piece can make.
*/
public List<Piece> possibleMoves(Piece piece) {
return Stream.of(board.getBoard()).flatMap(Stream::of).filter(
p -> p != null && isValidMove(piece, p.getLocation())).collect(
Collectors.toList());
}
But this will only return the Piece that it can overtake. How can I get only the Location?
Also another question, this looks fancy and all but performance-wise. Is it better or worse than a double for loop in anyway?
I am basically being asked to take the Unicode value of a string, multiply it by 10% and add whatever level the object currently has. It's frustrating because as it turns out I have the logic down including the code yet I still get an error that says: expected:<0> but was:<8>. Any suggestions, maybe it's just a slight nuance I have to make in the logic, although I'm fairly certain it's right. Take note of the getLevel method because that's where the error is
public class PouchCreature implements Battleable {
private String name;
private int strength;
private int levelUps;
private int victoriesSinceLevelUp;
/**
* Standard constructor. levelUps and victoriesSinceLevelUp start at 0.
*
* #param nameIn desired name for this PouchCreature
* #param strengthIn starting strength for this PouchCreature
*/
public PouchCreature(String nameIn, int strengthIn) {
this.name = nameIn;
this.strength = strengthIn;
this.levelUps = 0;
this.victoriesSinceLevelUp = 0;
}
/**
* Copy constructor.
*
* #param other reference to the existing object which is the basis of the new one
*/
public PouchCreature(PouchCreature other) {
this.name=other.name;
this.strength=other.strength;
this.levelUps=other.levelUps;
this.victoriesSinceLevelUp=other.victoriesSinceLevelUp;
}
/**
* Getter for skill level of the PouchCreature, which is based on the
* first character of its name and the number of levelUps it has.
* Specifically, the UNICODE value of the first character in its name
* taken %10 plus the levelUps.
*
* #return skill level of the PouchCreature
*/
public int getLevel() {
int value = (int)((int)(getName().charAt(0)) * 0.1);
return value + this.levelUps;
}
You've said you're supposed to increase the value by 10%. What you're actually doing, though, is reducing it 90% by taking just 10% of it (and then truncating that to an int). 67.0 * 0.1 = 6.7, which when truncated to an int is 6.
Change the 0.1 to 1.1 to increase it by 10%:
int value = (int)((int)(getName().charAt(0)) * 1.1);
// --------------------------------------------^
There, if getName() returns "Centaur" (for instance), the C has the Unicode value 67, and value ends up being 73.
We need to see the code you're calling the class with and that is generating your error message. Why is it expecting 0? 8 seems like a valid return value from the information you've given.
I'm building a Sudoku Game. I came here to get some help because I'm completely stuck in my code. I'm not asking for you to complete my code, I know that's not your job. Just few hints as what to do next would be great!
I use MVC and Swing Components for GUI to make the code lighter. I divided each field and method so I can understand what to do next but I'm confused. I'm particularly having trouble understanding how to do the following methods:
initializeGrid
chooseGameDifficulty
makeMove
cancelMove
Model
public class GameSudokuModel {
// states -- fields
Scanner userInput = new Scanner (System.in); // accept user input
// int levelDifficulty = 0; // level of difficulties
int [] gridSize ; // Sudoku 9x9 == 81 cells -- used to initialize grid or solve puzzle --
int [] subGridSize ; // a sub-grid = 9 cells
int gameMove = 0; // calculate the total number of moves per game // ++makeMove and --cancelMove
int [] gameCell = {1, 2, 3, 4, 5, 6, 7, 8, 9}; // a cell contain a list of choices numbers 1-9
int currentGameTime = 0; // calculates the total time to complete a puzzle
String currentPlayerName = userInput.nextLine(); // player name
// end of fields
//behaviors -- methods
/******************************************************
*
* Method calculateGameTime (initialiserGrille)
*
*
* Calculates time
*
* The stopwatch starts when the player makes his first move
*
*
*
******************************************************/
public class calculateGameTime{
}
/******************************************************
*
* Method initializeGrid (initialiserGrille)
*
*
* Used to initialize a grid
*
* Reset the grid ( back to the original Sudoku grid ) using the list of moves .
*
*
*
*
*
******************************************************/
public class initializeGrid {
}
/******************************************************
*
* Method levelDifficulty
*
*
* Established the parameters of level of difficulty
*
*
* #param beginner
* #param expert
* #return
******************************************************/
public int levelDifficulty (int beginner, int expert){
while(true)
{
int levelDifficulty = 0;
levelDifficulty= userInput.nextInt();
System.out.println (" ");
if(levelDifficulty < beginner || levelDifficulty> expert){
System.out.print (" You must choose 1, 2 or 3." + "Please try again : ");
System.out.println (" ");
}
else
return levelDifficulty;
}
}
/****************************************************
* Method chooseGameDifficulty (chosisirNiveauDifficulte)
*
* The method makes possible to choose the level of complexity of a grid
*
* (1) beginner: the player starts the game with a grid made up to 75% (81 * 0.75)
*
* (2) Intermediate : the player starts the game with a grid made up to 50% (81 * 0.50)
*
* (3) Expert : the player starts the game with a grid made up to 25% (81 * 0.25)
*
* Numbers are set randomly on the grid every new game
*
* #param beginner
* #param intermediate
* #param expert
******************************************************/
public void chooseGameDifficulty(int beginner, int intermediate, int expert){
boolean entreeValide;
int levelDifficulty;
String reponse;
levelDifficulty= levelDifficulty(beginner,expert); // call function levelDifficulty()
if(levelDifficulty==beginner)
//get easy level grid (getter)
//set easy level grid (setter)
if(levelDifficulty==intermediate)
//get intermediate level grid (getter)
//set intermediate level grid (setter)
if(levelDifficulty==expert)
//get expert level grid (getter)
//set easy expert grid (setter)
}
/****************************************************
* Method solvePuzzle (resoudrePuzzle)
*
* This method makes possible to solve the entire grid meaning all the 81 cells
*
******************************************************/
public class solvePuzzle {
}
/****************************************************
* Method makeMove (fairePlacement)
*
* Save a record of the player's actions on the grid.
*
*
*
* (1) make move on the grid ;
* (2) save moves in an array list
*
******************************************************/
public class makeMove {
//choose a cell , enter a number on the cell and confirm the selection
// adds move to the array list
int makeMove = gameMove++;
}
/****************************************************
* Method cancelMove (annulerPlacement)
*
*
*
* (1) retrieve the last instance in the arraylist (using the remove method and the size method to determine the number of elements )
* (2) cancel the move in the grid.
*
******************************************************/
public class cancelMove {
//choose a cell , remove the number on the cell and confirm the cancellation
//substracts move from array list
int cancelMove = gameMove--;
}
}
initializeGrid and chooseGameDifficulty aren't really features of the model. The model maintains the current state of the data and the rules uses to manage it.
Technically, these features should be functions of some kind of factory that given a difficult level will return a instance of the model
public class SudokuFactory {
public enum Difficulty {
HARD,
MODERATE,
EASY
}
public SudokuModel createModel(Difficulty difficult) {
// Make a new model based on the rules for your difficulty
// settings
}
}
The model would then simply contain the information and functionality to manage it
You should also avoid static where practically possible, it should never be used as a cross class communication mechanism, if you need to share data, you should pass it. static just makes the whole thing a lot more difficult to manage and debug
The view would get the information from the user (like the difficulty level), which would be used by the controller to build a new model. The model would then be passed to a new controller, which would generate a new view, which should present the current state of the model.
The controller would then respond to changes in the view, updating the model and the controller would respond to changes in the model and update the view.
You should also prefer using interfaces over implementation
So, based on my (rather pathetic) understanding of Sudoku you could use a model as simple as ...
public interface SudokuModel {
public void setValueAt(int value, int row, int col) throws IllegalArgumentException;
public int getValueAt(int row, int col);
}
Now, me, personally, I'd have an implementation that had two buffers, one which represents the actual game/solution and one which represents the player data (pre-filled based on the difficulty level), now you could have a single buffer, but you'd have constantly scan the grid to see if the new value was valid and I'm just too lazy ;)
I know we aren't suppose to post homework problems but I am having issues I have talked with him and after 45 minutes I am more confused then I was before he said that this was suppose to be confusing.
So we are working on making our own classes and one of them was making a class to later be used in a weight converter on other planets (mainly the Moon, Mercury, Venus, Jupiter and Saturn) I have managed to make the class (code below)
/*
* WeightConverter class
* Class Description - A Java class for converting weight on different plants
* Author: J. Wilson
* Date: 2/24/2015
* Filename: WeightConverter.java
*/
// class beginning
class WeightConverter {
//create the variable that stores the conversion rate
private double weightchange;
//the constructor
public WeightConverter(double weight){
weightchange=weight;
}
//accessor
public double smallstep(){
return weightchange;
}
//mutator for the needed variable
public void setweightratio(double number){
weightchange=number;
}
//and the method convert.
public double convert(double planet){
return planet*weightchange;
}
}
//end of class
but he added the stipulation that "In this WeightCalculator class, I expect you to use each method you created at least once.or lose a point for each one your don't use " I asked him how I go about it and after a 45 minute talk i'm more confused then before after he mentioned I can take my mutator and just manipulate that here is what I have currently and it works so far
/*
* WeightConverter on other planets
* Program Description - weightchanger
* Author: J.Wilson
* Date: 2/24/2015
* Filename: WeightCalculator.java
*/
//import statements
import java.util.*; //example
// class beginning
class WeightCalculator {
public static void main(String[] args ) {
//Declare variables area
WeightConverter test;
Scanner scan = new Scanner ( System.in );//reads what is entered into the keyboard by the user
double pounds;
//Program beginning messages to user here
System.out.println("Hello! Welcome to my weight converter program");
System.out.println();//blank space
System.out.println("Please enter your weight (in pounds): ");
pounds=scan.nextDouble();
WeightConverter moon = new WeightConverter(.167);
System.out.println("Your weight on the moon is " + moon.convert(pounds));
//Collect inputs from user or read in data here
//Echo input values back to user here
//Main calculations and code to
//Output results here
//End program message
System.out.println();
System.out.println("Hope you enjoyed using this program!");
}// end main method
}// end class
can anyone explain by what he means by using my mutator more than once? or in laymans terms how to go about doing it?
It sounds like you should be using setWeightRatio() each time you want to get the weight on a new planet.
You first created the moon object and set its weight and then later used that set weight in moon.convert()
Next you should setWeightRatio() to a different amount (for Jupiter or Venus or whatever) and that will set the weightChange variable to the new double you just passed in. Then when you use convert() it will access the new weightChange variable and compute based on that.
I would create a single planet object and then reset its weightChange variable through the mutator as necessary. Then use convert() between setting new weight ratio.
You professor said that you have to use all the methods in your class at least once, correct?
your setweightratio method is useless (this should be obvious, as you havent used it !). it sets the class variable weightchange to its input argument, but the same thing happens in the constructor, so you would not need to call it again.
You have two options:
You've already returned moon weight to the user. When the next planet is in question, keep your WeightConverter instance and call moon.setweightratio(ratio of Venus or whatever). Using moon.convert(pounds) will then use the new ratio.
Alternatively, remove the setweightratio method all together (so you don't get points off for not using it) and create WeightConverter objects for each planet. This is less elegant.