So I want to implement a code that would scramble the words!!
It is a homework assignment question.
Although we are not given the liberty of creating another Method in the class, nor are we allowed to create another field in the class. Everything that we want has to be enclosed within the Constructor parameters.
and then send the word as an argument for super(arg);
Although would it not be illegal and an error if I put any code before super???
Note: I also cannot create any variables outside the constructor.
Note2: ScrambledWordPuzzle is a contructor for class ScrambledWordPuzzle that extends another abstract class
Edit 2: Extra Info
Class to make changes:
public class ScrambledWordPuzzle extends AbstractWordPuzzle {
/**
* The solution to the puzzle
*/
private String solution;
/**
* Creates a scrambled word puzzle given the solution word.
*
* #param solutionWord
* the puzzle word
*/
public ScrambledWordPuzzle(String solutionWord) {
// COMPLETE THIS
// Hint: You need to scramble the letters of the solution word
// to generate the puzzle word and then set the puzzle word.
// The easiest way to scramble the letters is to put them
// into a list, use Collections.shuffle, and then convert the
// the shuffled list of letters back into a string.
super();
this.solution = solutionWord;
}
/**
* Get the solution for this reverse word puzzle.
*
* #return the solution for this reverse word puzzle
*/
#Override
public String getSolution() {
// COMPLETE THIS
return this.solution;
}
}
Abstract Class:
public abstract class AbstractWordPuzzle {
/**
* The puzzle word.
*/
private String puzzle;
/**
* Initializes this puzzle to the empty string.
*/
public AbstractWordPuzzle() {
// COMPLETE THIS
this.puzzle="";
}
/**
* Initializes this puzzle to the specified puzzle word.
*
* #param puzzleWord
* the puzzle word
*/
public AbstractWordPuzzle(String puzzleWord) {
// COMPLETE THIS
this.puzzle=puzzleWord;
}
/**
* Get the solution word. For word puzzles with more than one solution this
* method returns the solution that comes first in dictionary order.
*
* #return the solution word that comes first in dictionary order
*/
public abstract String getSolution();
/**
* Get the puzzle word
*
* #return the puzzle word
*/
public final String getPuzzleWord() {
// ALREADY IMPLEMENTED; DO NOT MODIFY
return this.puzzle;
}
/**
* Set the puzzle word for this puzzle.
*
* #param puzzleWord
* the puzzle word
*/
public final void setPuzzleWord(String puzzleWord) {
// COMPLETE THIS
this.puzzle=puzzleWord;
}
}
I need the code before super() because, if it is after the super code, I will not be able to call the variable or whatever it would be in the super(arg).
Ok, so no methods allowed. Then everything should be inline.
public ScrambledWordPuzzle(String solutionWord) {
super(new MyCollection(solutionWord.split("")).shuffle().toString());
}
Related
I am starting to learn Java and the content in which we learn from I just CANNOT get on with, it doesn't explain much but just gives you a mild example and tells you to do it yourself with something completely different. as above I need to take the 'longNumber' string and take the last character off it.
* Write a description of class CreditCardChecker here.
*
* #author Craig Beverley
* #version 03/12/2020
*/
public class CreditCardChecker
{
// Variable for long numbers to be checked
public String longNumber;
public StringBuilder firstFifteen;
/**
* Constructor for objects of class CreditCardChecker
* including long number and first fifteen
*/
public CreditCardChecker(String longNumber)
{
// initialise long number variable
this.longNumber=longNumber;
}
/**
* Sets the value of long number
*/
public void setLongNumber(String aLongNumber)
{
this.longNumber=aLongNumber;
}
/**
* method to get the long number
*/
public String getLongNumber()
{
return this.longNumber;
}
/**
* method to check that long number has exactly 16 digits
*/
public boolean isCorrectLength()
{
if (longNumber.length() == 16)
{
return (true);
}
else
{
return (false);
}
}
/**
* Method to get the first 15 characters of long number
*/
public String firstFifteen(String longNumber)
{
firstFifteen=longNumber.deleteCharAt(16);
}
}```
I'm not entirely sure you need firstFifteen as a field. You can simply grab the first 15 characters
return longNumber.substring(0, 15);
You also don't need a parameter for that method, since longNumber is a field
I'm making an RPG game in Java for a school assignment. In the game I take user input and the first word is the "command word", so I create an enum to convert the strings for user input to enum constants:
public enum CommandWord
{
GO("go"), QUIT("quit"), HELP("help"), BACK("back"), LOOK("look"), DROP("drop"), GRAB("grab"), USE("use"), UNKNOWN("?");
private String commandString;
/*
* Initialize with the corresponding command string.
* #param commandString the command string.
*/
CommandWord(String commandString) {
this.commandString = commandString;
}
public String toString()
{
return commandString;
}
Sometimes the second word is a direction following "go" so I have a second enum for directions with more constants:
UP("up"), DOWN("down"), NORTH("north"), SOUTH("south"), EAST("east"), WEST("west"), UNKNOWN("unknown");
I'm trying to come up with the best method for building a HashMap to store strings and the related enum constants. For command words I have this class:
public class CommandWords
{
// A mapping between a command word and the CommandWord
// that is associated with it
private HashMap<String, CommandWord> validCommands;
/**
* Constructor - initialise the command words.
*/
public CommandWords()
{
validCommands = new HashMap<>();
for (CommandWord command : CommandWord.values()) {
if(command != CommandWord.UNKNOWN) {
validCommands.put(command.toString(), command);
}
}
}
/**
* Searches the HashMap of valid commands for the supplied word.
* #param commandWord The word we're searching for.
* #return The CommandWord that is mapped to the supplied string commandWord,
* or UNKNOWN if it is not in valid command.
*/
public CommandWord getCommandWord(String commandWord)
{
CommandWord command = validCommands.get(commandWord);
if (command!= null) {
return command;
}
else {
return CommandWord.UNKNOWN;
}
}
}
Then I can take userinput and search for the command word, but I can't reuse it for directions, or items, characters etc. I looked at using a generic class but I can't call methods like .values() on it, is there a good way to do this so I can reuse the CommandWords class on different enums?
We have valueOf(String) method on Enum, you don't have to build that map.
For your case, you have a value, and you know which Enum type you would like to convert to. So, just use:
CommandWord.valueOf("QUIT");
Items.valueOf("GEM");
etc..
Enums must be determined at compile-time.
Scenario:
I've two reports: Main Report (let's call it, A) and sub-report (let's call it, B).
Report A contains sub-report B at the detail band, so sub-report B is displayed for each element at the Report A datasource. Sub-report B also returns a variable to the Main report A.
What I want is to sum those return values from sub-report B and totalize them at the Main report summary.
To do that, I have tried to create a new report variable that sum those returns values... Something like this:
However, I've found that such variables expression are always evaluated before the band detail is rendered, so I always miss the first sub-report return value...
Sadly, the evaluation time (as this link says) cannot be changed on those kind of variables, so I'm stuck...
After been struggling with this for some hours... and searching the internet for a solution... I came with a Workaround (the enlightening forums were these ones: one and two).
First, you need to define a java Class Helper that allows you calculate some arithmetic operation, in my case a Sum operation. I defined these classes:
package reports.utils;
import java.util.Map;
/**
* Utility that allows you to sum Integer values.
*/
public class SumCalculator {
/**
* Stores a map of {#code SumCalculator} instances (A Map instance per thread).
*/
private static final ThreadLocalMap<String, SumCalculator> calculatorsIndex = new ThreadLocalMap<>();
/**
* The sum total.
*/
private int total = 0;
/**
* No arguments class constructor.
*/
private SumCalculator() {
super();
}
/**
* Instance a new {#code SumCalculator} with the given ID.
*
* #param id {#code SumCalculator}'s ID
* #return the new {#code SumCalculator} instance
*/
public static SumCalculator get(String id) {
Map<String, SumCalculator> map = calculatorsIndex.get();
SumCalculator calculator = map.get(id);
if (calculator == null) {
calculator = new SumCalculator();
map.put(id, calculator);
}
return calculator;
}
/**
* Destroy the {#code SumCalculator} associated to the given ID.
*
* #param id {#code SumCalculator}'s ID
* #return {#code null}
*/
public static String destroy(String id) {
Map<String, SumCalculator> map;
map = calculatorsIndex.get();
map.remove(id);
if (map.isEmpty()) {
calculatorsIndex.remove();
}
return null;
}
/**
* Resets the {#code SumCalculator} total.
*
* #return {#code null}
*/
public String reset() {
total = 0;
return null;
}
/**
* Adds the given integer value to the accumulated total.
*
* #param i an integer value (can be null)
* #return {#code null}
*/
public String add(Integer i) {
this.total += (i != null) ? i.intValue() : 0;
return null;
}
/**
* Return the accumulated total.
*
* #return an Integer value (won't be null, never!)
*/
public Integer getTotal() {
return this.total;
}
}
package reports.utils;
import java.util.HashMap;
import java.util.Map;
/**
* Thread Local variable that holds a {#code java.util.Map}.
*/
class ThreadLocalMap<K, V> extends ThreadLocal<Map<K, V>> {
/**
* Class Constructor.
*/
public ThreadLocalMap() {
super();
}
/* (non-Javadoc)
* #see java.lang.ThreadLocal#initialValue()
*/
#Override
protected Map<K, V> initialValue() {
return new HashMap<>();
}
}
Second, at your jasper report, you need to define four text fields:
1) A text field that iniatializes your calculator; it should be (ideally) at the title section of the report and should have an expression like this: SumCalculator.get("$V{SUB_REPORT_RETURN_VALUE}").reset(). This text field should have the evaluation time: NOW.
2) A text field that calls the increment function (i.e. SumCalculator.get("$V{SUB_REPORT_RETURN_VALUE}").add($V{SUB_REPORT_RETURN_VALUE}). This text field will reside at your detail band, after the subreport element; and it should have the evaluation time: BAND (this is very important!!)
3) A text field that prints the calculator total. This text field will reside at your summary band, it will evaluate to NOW. Its expression will be: SumCalculator.get("$V{SUB_REPORT_RETURN_VALUE}").getTotal()
4) A text field that destroy the calculator. This text field will also reside at your summary band and must appear after the text field 3. The text field should have an expression like: SumCalculator.destroy("$V{SUB_REPORT_RETURN_VALUE}"). This text field should have the evaluation time: NOW.
Also, the text fields: 1, 2, and 4, should have the attribute "Blank when Null", so they will never be printed (that's why those java operations always return null).
And That's it. Then, your report can look something like this:
if i understand the problem, you can not summarize the amount returned by the sub report in the main report, i had the same problem and i solved in this way.
1.- Create a class which extends from net.sf.jasperreports.engine.JRDefaultScriptlet. and override the method beforeReportInit()
this is the code from this class.
package com.mem.utils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import net.sf.jasperreports.engine.JRDefaultScriptlet;
public class SumarizacionSubtotales extends JRDefaultScriptlet {
private final Log log = LogFactory.getLog(getClass());
private Double total;
public Double getTotal() {
return total;
}
public Double add(Double cantidad) {
if(log.isDebugEnabled())log.debug("AGREGANDO LA CANTIDAD : " + cantidad);
this.total += cantidad;
return cantidad;
}
#Override
public void beforeReportInit() throws JRScriptletException {
if(log.isDebugEnabled())log.debug("beforeReportInit");
total = 0.0D;
}
}
2.- add your project's jar in your ireport's classpath.
3.- Replace the class of the REPORT scriptlet.
in the properties with your class.
3.- add in the group footer where you want to print the value returned by the sub-report a textfield with the following expression.
$P{REPORT_SCRIPTLET}.add( $V{sum_detalles} )
In this case $V{sum_detalles} is a variable in the main report which contains the value returned by the sub-report.
4.- Add in the Last page footer another textfield with the following expression.
$P{REPORT_SCRIPTLET}.getTotal()
first off this is an assignment so I'm more looking for help then coded answers (don't want to cheat!). My assignment is to create a program that processes a train/railway network of stations. The section i'm stuck on adds the stations, their connections, and returns these connections as an Array List of Strings. I've included below the code I have so far, and also an extract from the assignment (related to the section I'm on now). I've been struggling with this bit all weekend, so any help would be hugely appreciated.
It's only the implementation of the interface I need to edit, the "MyNetwork" class. I just feel I've been going in circles, and may not have even gotten off on the right foot?
From the assignment;
Create a class MyNetwork that implements the Network interface.
The getConnections method of this class should return an array containing only those stations directly connected to the fromStation argument.
Hint 1: you can do this using a HashMap, with the keys being Strings (representing stations) and the values being ArrayLists of Strings (representing the stations to which there is a direct connection).
Hint 2: Although the getConnections method returns an array of Strings, it would be better for the values in the HashMap to be ArrayLists of Strings
The Interface;
public interface Network {
/**
* Add a station to the network.
* #param station The station to be added.
*/
public void addStation(String station);
/**
* Add a direct connection from one station to another.
* #pre both fromStation and toStation have already been added by the method
* addStation.
* #param fromStation The station from which the connection begins.
* #param toStation The station at which the connection ends.
*/
public void addConnection(String fromStation, String toStation);
/**
* Get a list of all stations directly connected to a given station.
* #pre fromStation has been added to the network by the method addStation.
* #param fromStation
* #return A list of all the stations to which there is a direct connection
* from fromStation.
*/
public String[] getConnections(String fromStation);
/**
* Search for a station in the network.
* #param station Station to be searched for,
* #return true if the Station exists in the network, false otherwise.
*/
public boolean hasStation(String station);
/**
* Get all stations in the network.
* #return An array containing all the stations in the network, with no
* duplicates.
*/
public String[] getStations();
The Implementation:
public class MyNetwork implements Network {
#Override
public void addStation(String station) {
ArrayList<String> Stations = new ArrayList<>();
Stations.add(station);
}
#Override
public void addConnection(String fromStation, String toStation) {
Map<String,String> Connections = new HashMap<>();
Connections.put(fromStation, toStation);
}
#Override
public String[] getConnections(String fromStation) {
return null; // dummy value!
}
#Override
public boolean hasStation(String station) {
return false; // dummy value!
}
#Override
public String[] getStations() {
return null; // dummy value!
}
}
Your network needs to have a state, using one or several instance field(s).
As is, it doesn't have any state. Each method creates a local variable of type List or Map, adds something to this List or Map, and returns. So the List or Map directly goes out of scope and is garbage collected.
private Map<String, List<String>> stations = new HashMap<>();
// now all your methods should use the above map.
See http://docs.oracle.com/javase/tutorial/java/javaOO/classes.html
I have been trying to figure out how to add runner information into an array of runner information. It should contain at most 100 runners.
This is part of a larger project that must fulfill these requirements:
Operations (methods):
• A constructor that takes in a race name and distance.
• Getters and setters for both the name and distance instance variables.
• Method to return the count of the number of RunnerResult objects added to the array.
• Method to add a RunnerResult to the array (given an instance of Runner and the runner’s finishing time).
• Methods to get a RunnerResult object; one that takes in the position in which the RunnerResult was added (to directly access the object from the array) and one that takes in a runner name (to use to search for the matching runner). The first runner’s index is 0, the second is 1, etc.
• A method with conditional logic to give a count of all runners for a certain category (youth, adult, senior, male, female, all) triggered by a flag passed in as a whole number (1, 2, 3, 4, 5, 6, respectively, implemented as public constants). A similar method provides the average race result (time to finish race) for each potential category.
• A method with conditional logic finds runners with a race time less than the specified minutes per mile. For example, find all runners who finished the race with a time of less than 8 minutes per mile.
• A toString method that simply gives the race name, race distance, a count of total runners in the race, and the average time of all runners in the race.
So far, this is what I have:
public class Race
{
// instance variables
private String name;
private double distance;
private int nextPos;
private RunnerResult [] results;
// public constants
/**
* Flag to signify YOUTH.
*/
public static final int YOUTH = 1;
/**
* Flag to signify ADULT.
*/
public static final int ADULT = 2;
/**
* Flag to signify SENIOR.
*/
public static final int SENIOR = 3;
/**
* Flag to signify MALE.
*/
public static final int MALE = 4;
/**
* Flag to signify FEMALE.
*/
public static final int FEMALE = 5;
/**
* Flag to signify ALL.
*/
public static final int ALL = 6;
/**
* Array limit.
*/
public static final int MAX_COUNT = 100;
/**
* Constructor for objects of class Race.
*
* #param inName the race name.
* #param inDist the distance of the race.
*
*/
public Race(String inName, double inDist)
{
// initialize the instance variables and
// empty array of results, initalize nextPos
this.name = inName;
this.distance = inDist;
RunnerResult[] results = new RunnerResult[100];
}
/**
* Set the race Name.
*
* #param inName the race name.
*
*/
public void setName(String inName)
{
this.name = inName;
}
/**
* Get the race Name.
*
* #return String The race name.
*
*/
public String getName()
{
return this.name;
}
/**
* Set the race distance.
*
* #param inDist the distance of the Race.
*
*/
public void setDist(double inDist)
{
this.distance = inDist;
}
/**
* Get the race distance.
*
* #return double the distance of the race.
*
*/
public double getDist()
{
return this.distance;
}
/**
* Add a runner to the results
* (runners are NOT entered in order of finish).
*
* #param inChip the runner's chip id.
* #param inRunner a Runner object.
* #param inStart the start time for the runner.
* #param inEnd the end time for the runner.
*
*/
public void addRunner(String inChip, Runner inRunner, Time inStart, Time inEnd)
{
if (this.nextPos < MAX_COUNT)
{
// set the instance field element to a "copy" of passed-in object
// add to array, increment counter
for(int i = 0; i < results.length; i++);
{
RunnerResult[] results = { copyinChip, copyinRunner, copyinStart,
copyinEnd };
i++;
}
}
}
}
I just cannot figure out how to get these values into the array. (I get an incompatible type error. Any input would be greatly appreciated.
two things here.
1.) when you re-declare results, you are not referencing the same object that you declare as a field, but an entirely new object that then has no purpose, because it only lives within addRunner.
2.) When you assign results = { ---, ---, ---, ---}; You aren't adding a new runner to the array. Rather, you are reassigning the entire array every single time you do that loop. You would want to create a new RunnerResult object, add the necessary data to it, and then put that at results[];
An example here:
public void addRunner(String inChip, Runner inRunner, Time inStart, Time inEnd)
{
if (this.nextPos < MAX_COUNT)
{
// set the instance field element to a "copy" of passed-in object
// add to array, increment counter
for(int i = 0; i < results.length; i++);
{
results[i] = new RunnerResult(<your params>);
}
}
}