Java - Illegal Start of Expression - java

so I did a few searches for this error and found a few results. However, none of them seem to be an answer. I'm sure the problem is simple and that I'm just too tired to figure it out, but I dunno what my mistake is. The methods are meant to be mutator methods to increase or decrease the volume.
Television.java:94: error: illegal start of expression
public int increaseVolume()
^
Television.java:94: error: ';' expected
public int increaseVolume()
^
Television.java:103: error: illegal start of expression
public int decreaseVolume()
^
Television.java:103: error: ';' expected
public int decreaseVolume()
^
Television.java:106: error: reached end of file while parsing
}
^
5 errors
Here is the end of the code where the errors are occuring:
public class Television
{
private String MANUFACTURER = "None"; // This represents the manufacturer of the TV set.
private int SCREEN_SIZE = 0; // This represents the size of screen of the TV set.
private boolean powerOn; // This represents the state the TV is in (On or Off)
private int channel; // This represents the channel the TV set is on.
private int volume; // This represents the volume value of the TV set.
public static void main(String[] args)
{
}
/**
Constructor
#param brand The manufacturer brand of the TV set.
#param size The screen size of the TV set.
*/
public Television(String brand, int size)
{
MANUFACTURER = brand;
SCREEN_SIZE = size;
powerOn = false;
volume = 20;
channel = 2;
}
/**
The getVolume method gets the volume of the TV set.
#return The current volume on the TV set as an integer.
*/
public int getVolume()
{
return volume;
}
/**
The getChannel method gets the channel of the TV set.
#return The current channel on the TV set as an integer.
*/
public int getChannel()
{
return channel;
}
/**
The getScreenSize method gets the screen size of the TV set.
#return The screen size as an integer.
*/
public int getScreenSize()
{
return SCREEN_SIZE;
}
/**
The getManufacturer method gets the brand manufacturer of the TV set.
#return The manufacturer name as a string.
*/
public String getManufacturer()
{
return MANUFACTURER;
}
/**
The setChannel method is designed to set the channel for the user.
#return The channel on the TV that is set.
*/
public int setChannel(int chan)
{
return channel = chan;
}
/**
The power method is designed to take the current power state and turn it on or off based on its current state.
#return The power state after it is changed.
*/
public boolean power()
{
if (powerOn = true)
{
return powerOn = !powerOn;
}
else
{
return powerOn = false;
}
/**
The increaseVolume method is designed to increase the volume of the TV set in increments of 1.
#return The volume of the TV set as it is after being increased.
*/
public int increaseVolume()
{
return volume += 1;
}
/**
The decreaseVolume method is designed to decrease the volume of the TV set in increments of 1.
#return The volume of the TV set as it is after being decreased.
*/
public int decreaseVolume()
{
return volume -= 1;
}
}
}
I'm either really tired or an idiot. Sorry if it's so obvious.

You forgot to close the method power() and remove one } at the end of the class
Adding to that, you need to change this if (powerOn = true) to if (powerOn == true). You are assigning the value to powerOn instead of testing equality

you have missing one close braces at public boolean power() method
public class Television
{
private String MANUFACTURER = "None"; // This represents the manufacturer of the TV set.
private int SCREEN_SIZE = 0; // This represents the size of screen of the TV set.
private boolean powerOn; // This represents the state the TV is in (On or Off)
private int channel; // This represents the channel the TV set is on.
private int volume; // This represents the volume value of the TV set.
public static void main(String[] args)
{
}
/**
Constructor
#param brand The manufacturer brand of the TV set.
#param size The screen size of the TV set.
*/
public Television(String brand, int size)
{
MANUFACTURER = brand;
SCREEN_SIZE = size;
powerOn = false;
volume = 20;
channel = 2;
}
/**
The getVolume method gets the volume of the TV set.
#return The current volume on the TV set as an integer.
*/
public int getVolume()
{
return volume;
}
/**
The getChannel method gets the channel of the TV set.
#return The current channel on the TV set as an integer.
*/
public int getChannel()
{
return channel;
}
/**
The getScreenSize method gets the screen size of the TV set.
#return The screen size as an integer.
*/
public int getScreenSize()
{
return SCREEN_SIZE;
}
/**
The getManufacturer method gets the brand manufacturer of the TV set.
#return The manufacturer name as a string.
*/
public String getManufacturer()
{
return MANUFACTURER;
}
/**
The setChannel method is designed to set the channel for the user.
#return The channel on the TV that is set.
*/
public int setChannel(int chan)
{
return channel = chan;
}
/**
The power method is designed to take the current power state and turn it on or off based on its current state.
#return The power state after it is changed.
*/
public boolean power()
{
if (powerOn == true)
{
return powerOn = !powerOn;
}
else
{
return powerOn = false;
}
}////here is missing breces
/**
The increaseVolume method is designed to increase the volume of the TV set in increments of 1.
#return The volume of the TV set as it is after being increased.
*/
public int increaseVolume()
{
return volume += 1;
}
/**
The decreaseVolume method is designed to decrease the volume of the TV set in increments of 1.
#return The volume of the TV set as it is after being decreased.
*/
public int decreaseVolume()
{
return volume -= 1;
}
}
}

You miss a } in here:
public boolean power()
{
if (powerOn = true)
{
return powerOn = !powerOn;
}
else
{
return powerOn = false;
}
//
//Here is } missing
//
/**
The increaseVolume method is designed to increase the volume of the TV set in increments of 1.
#return The volume of the TV set as it is after being increased.
*/
public int increaseVolume()
{
return volume += 1;
}
Anyway, if you have errors in compile time I recomend you to use an IDE to check the sintax errors if you stock again with these kind of errors

Related

Trying to get an animated object to jump in Java

You are now going to write the various methods in WizardController that animate the wizards. In order to follow the motion of the wizards properly you will need to slow the animation down. To help you do this we have provided a class method delay() in the WizardController class.
WizardController.delay(100);
So the question is write a public class method jump() that returns nothing. It should make the wizard passed as argument jump up one cell position from its current cell then return to its original cell. I have tried the code below and it compiles but not 100% sure if its correct..
public static void jump(Wizard wizard1)
{
wizard1.up();
WizardController.delay(1000);
wizard1.down(1);
}
...also I need to create an instance of wizard and execute the jump() method passing it as argument to check this works as expected. This I am unsure how to do.
here is the full code:
public class WizardController
{
/**
* instance variables
*/
private Wizard wizard1;
private Wizard wizard2;
private int numOfRepeats;
private static final int MIN_NUM_REPEATS = 1;
private static final int MAX_NUM_REPEATS = 3;
public static final int LAST_CELL = 11;
/**
* Constructor for objects of class WizardController.
*/
public WizardController(Wizard aWizard1, Wizard aWizard2)
{
super();
this.wizard1 = aWizard1;
this.wizard2 = aWizard2;
this.numOfRepeats = 0;
}
/* instance methods */
/**
* Prompts the user for a number of action repeats
* in the range 1 to 3 inclusive, and returns this number.
*/
public int promptForNumOfRepeats()
{
int moves;
moves = Integer.parseInt(OUDialog.request("Please enter the number of"
+ " action repeats to be performed - between 1 and 3 (inclusive)"));
try
{
moves = Integer.parseInt(OUDialog.request("Please enter the number of"
+ " action repeats to be performed - between 1 and 3 (inclusive)"));
}
catch (NumberFormatException anException)
{
moves = 0;
}
return moves;
}
/**
* Returns true if the argument is in the range 1 to 3 (inclusive),
* otherwise false.
*/
public boolean isValidNumOfRepeats(int aNumber)
{
return ((aNumber >= WizardController.MIN_NUM_REPEATS)
&& (aNumber <= WizardController.MAX_NUM_REPEATS));
}
/**
* Repeatedly prompts the user for a number of repeats of the moves,
* until they enter a valid input representing a number in the range 1 to 3
* inclusive, and then returns this number.
*/
public int getNumOfRepeats()
{
int repeats = this.promptForNumOfRepeats();
while (!this.isValidNumOfRepeats(repeats))
{
OUDialog.alert("That is not a valid number of game repeats");
repeats = this.promptForNumOfRepeats();
}
return repeats;
}
public static void jump(Wizard wizard1)
{
wizard1.up();
WizardController.delay(1000);
wizard1.down(1);
}
public static void delay(int ms)
{
try{
Thread.sleep(ms);
}
catch(Exception e)
{
System.out.println("Problem in delay methods");
}
}
}
here is the Wizard class for any wxtra help:
public class Wizard
{
/* instance variables */
private Triangle persona;
private int startCellX;
private int startCellY;
private OUColour startColour;
public static final int CELL_SIZE_X = 20;
public static final int CELL_SIZE_Y = 30;
/**
* Constructor for objects of class Wizard
*/
public Wizard(OUColour aColour, int cellY)
{
super();
this.persona = new Triangle(30, 30, aColour);
this.persona.setXPos(0);
this.persona.setYPos(cellY * Wizard.CELL_SIZE_Y);
this.startCellX = 0;
this.startCellY = cellY;
this.startColour = aColour;
}
/* instance methods */
/**
* returns the persona of the Wizard - so that it can be displayed
* in the graphical display window
*/
public Triangle getPersona()
{
return this.persona;
}
/**
* Resets the receiver to its "home" X position of 0.
*/
public void homeX()
{
this.persona.setXPos(this.startCellX * Wizard.CELL_SIZE_X);
}
/**
* Resets the receiver to its "home" Y position of startCellY * CELL_SIZE.
*/
public void homeY()
{
this.persona.setYPos(this.startCellY * Wizard.CELL_SIZE_Y);
}
/**
* Decrements the X position of the receiver by CELL_SIZE.
*/
public void left()
{
this.persona.setXPos(this.persona.getXPos() - Wizard.CELL_SIZE_X);
}
/**
* Increments the X position of the receiver by CELL_SIZE.
*/
public void right()
{
this.persona.setXPos(this.persona.getXPos() + Wizard.CELL_SIZE_X);
}
/**
* Decrements the Y position of the receiver by CELL_SIZE.
*/
public void up()
{
this.persona.setYPos(this.persona.getYPos() - Wizard.CELL_SIZE_Y);
}
/**
* Increments the Y position of the receiver by CELL_SIZE.
*/
public void down()
{
this.persona.setYPos(this.persona.getYPos() + Wizard.CELL_SIZE_Y);
}
/**
* Decrements the X position of the receiver by CELL_SIZE
* times the value of the argument.
*/
public void leftBy(int numCells)
{
this.persona.setXPos(this.persona.getXPos() - Wizard.CELL_SIZE_X * numCells);
}
/**
* Increments the X position of the receiver by CELL_SIZE
* times the value of the argument.
*/
public void rightBy(int numCells)
{
this.persona.setXPos(this.persona.getXPos() + Wizard.CELL_SIZE_X * numCells);
}
/**
* Decrements the Y position of the receiver by CELL_SIZE
* times the value of the argument.
*/
public void upBy(int numCells)
{
this.persona.setYPos(this.persona.getYPos() - Wizard.CELL_SIZE_Y * numCells);
}
/**
* Increments the Y position of the receiver by CELL_SIZE
* times the value of the argument.
*/
public void downBy(int numCells)
{
this.persona.setYPos(this.persona.getYPos() + Wizard.CELL_SIZE_Y * numCells);
}
/**
* returns the cellX the wizard is currently on
*/
public int getCellX()
{
return this.persona.getXPos()/ Wizard.CELL_SIZE_X;
}
/**
* returns the cellY the wizard is currently on
*/
public int getCellY()
{
return this.persona.getYPos()/ Wizard.CELL_SIZE_Y;
}
/**
* sets the cellY the wizard is on to the argument
*/
public void setCellY(int aCellNumber)
{
this.persona.setYPos(aCellNumber * Wizard.CELL_SIZE_Y);
}
/**
* Returns a string representation of the receiver.
*/
#Override
public String toString()
{
return "An instance of class " + this.getClass().getName()
+ " in cell X:" + this.getCellX() + ", Y:" + this.getCellY()
+ ", colour " + this.persona.getColour();
}

Need to compare objects from an ArrayList to return the highest value

In this project (using BlueJ as I am a beginner) I am looking to add Climbers to an ArrayList with their name, gender and age. The Climbers can add what mountain they have climbed. With the mountain name and height.
I need to add a method into the Climber class to return which is the highest mountain a certain Climber has climbed.
To define the method do I define it using
public ArrayList<Mountain> getHighestMountain(Mountain mountainHeight)
I am unsure as how to check the objects in the mountain class to compare. FYI I haven't been learned the comparative keyword yet so would like to refrain from using this.
Club class:
import java.util.ArrayList;
import java.util.Scanner;
/**
* Write a description of class Club here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class Club
{
// An ArrayList for storing climber details.
private ArrayList<Climber> climbers;
/**
* Constructor for objects of class Club
*/
public Club()
{
// Initialise instance variables.
climbers = new ArrayList<Climber>();
}
public void addClimber(Climber newName)
{
climbers.add(newName);
}
public Climber getClimber(String name)
{
Climber foundClimber = null;
int index = 0;
boolean searching = true;
while(searching && index < climbers.size()) {
Climber climber = climbers.get(index);
if(climber.getName().equals(name)) {
searching = false;
foundClimber = climber;
}
else {
System.out.println(name + " not found");
index++;
}
}
return foundClimber;
}
public void displayClimberList()
{
for (int item = 0; item<climbers.size();
item++) {
Climber climber = climbers.get(item);
System.out.println(climber.getName() + (" ") + climber.getAge() + (" ")
+ climber.getGender());
}
}
}
Climber class:
import java.util.ArrayList;
/**
* Write a description of class Climber here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class Climber
{
// Instance variables.
// The climber name.
private String name;
// The climber age
private int age;
// The climber gender.
private String gender;
private ArrayList<Mountain> mountains;
/**
* Constructor for objects of class Climber
*/
public Climber (String newName, int newAge, String newGender)
{
// Initialise instance variables.
name = newName;
age = newAge;
gender = newGender;
mountains = new ArrayList<Mountain>();
}
/**
* Accessor method for climber's name.
*/
public String getName()
{
return name;
}
/**
* Set the climber's name.
*/
public void setName(String newName)
{
name = newName;
}
/**
* Accessor method for climber's age.
*/
public int getAge()
{
return age;
}
/**
* Set the climber's age.
*/
public void setAge(int newAge)
{
age = newAge;
}
/**
* Set the climer's gender.
*/
public String getGender()
{
return gender;
}
/**
* Accessor method for climber's gender.
*/
public void getGender(String newGender)
{
gender = newGender;
}
public Mountain addMountain(Mountain mountain)
{
return mountain;
}
public ArrayList<Mountain> getHighestMountain(Mountain mountainHeight)
{
double maxHeight = 1;
int index = 1;
for(int i = 0; i < mountainHeight.length; i++) {
if(mountainHeight[i].getHeight()>maxHeight) {
index = i;
}
}
}
}
Mountain class:
/**
* Write a description of class Mountain here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class Mountain
{
// Instance variables.
private double height;
private String name;
/**
* Constructor for objects of class Mountain
*/
public Mountain(String mountainName, double mountainHeight)
{
// Initialise instance variables
name = mountainName;
height = mountainHeight;
}
/**
* Accessor method for mountain name.
*/
public String getName()
{
return name;
}
/**
* Set the mountain name.
*/
public void setName(String mountainName)
{
name = mountainName;
}
/**
* Accessor method for mountain height.
*/
public double getHeight()
{
// put your code here
return height;
}
/**
* Set the mountain height.
*/
public void setHeight(double newHeight)
{
height = mountainHeight;
}
}
I've attempted to return this value but as you can see it is incomplete.
Thanks in advance!
Change:
//This does absolutely nothing. It takes a parameter and returns it.
public Mountain addMountain(Mountain mountain) {
return mountain;
}
public ArrayList<Mountain> getHighestMountain(Mountain mountainHeight) {
double maxHeight = 1;
int index = 1;
for(int i = 0; i < mountainHeight.length; i++) {
if(mountainHeight[i].getHeight()>maxHeight) {
index = i;
}
}
}
To:
//This adds the parameter mountain to the list of mountains for this climber
public void addMountain(Mountain mountain) {
mountains.add(mountain);
}
//This loops over the mountains for this climber and returns the highest one.
public Mountain getHighestMountain() {
Mountain highestMountain = null;
for(int i = 0; i < mountains.size(); i++) {
if (highestMountain == null) {
highestMountain = mountains.get(i);
}
else if(mountains.get(i).getHeight() > highestMountain.getHeight()) {
highestMountain = mounts.get(i);
}
}
return highestMountain;
}
Your code example shows a lack of understanding of basic concepts such as fields and variables, parameters and return types and so on. I would suggest reading up on the language basics here.
Comments
Get rid of your comments, they are not adding any value. Don't put or leave default comments in your code, they reduce readability. Clarifications should also be avoided, try to create a separate variable or method with a meaningful name instead. For example:
// check if the user is on the last page
if (!((count - i) < pageSize)) {
addNextButton();
}
Could become:
boolean userIsOnTheLastPage = (count - i) < pageSize;
if (!userIsOnTheLastPage) {
addNextButton();
}
Interfaces
Java collections (like ArrayList) implement interfaces (e.g. List). Usually you will want to declare and pass around the interface, not the implementation you used. Other parts of your code should only care about using the List capabilities, not how they are implemented.
So replace;
private ArrayList<Climber> climbers;
with
private List<Climber> climbers;
Also use the interface as parameter or return type in methods. A result of this approach is that if you want to use a different List implementation later on, you only have to change it in one place in your code. This is a form of decoupling in your code, which is a good thing to have. ('low coupling, high cohesion')
getClimber
Your search implementation in getClimber is a bit convoluted. I'd do it like this:
for (Climber climber : climbers) {
if(climber.getName().equals(name)) {
return climber;
}
}
System.out.println(name + " not found");
I understand you might be trying to avoid returning from an iteration but in my opinion the code gets much less readable as a result.
BTW your code would print 'not found' for every non-matching climber. I assumed that's not what you want so my code only prints it once if no matching climber is found.
displayClimberList
public void displayClimbers() {
for (Climber climber : climbers) {
System.out.println(climber);
}
}
System.out.println calls toString() on its argument, so we can leave the formating of the display String to the Climber class:
public class Climber {
private String name;
private int age;
private String gender;
// ...
public String toString() {
return String.format("%s %s %s", name, age, gender);
}
Don't mention types in your variable/method names if not needed. The fact that a List is returned is already apparent from the method signature.
foreach is more readable an iteration with an index so use it when you can. Sometimes you cannot avoid using an index, for example when iterating through two lists simultaneously but that's not the case here.
printf (or String.format) makes formatting an output string much easier than String concatenation. See the documentation of java.util.Formatter
Gender
I would change the gender field from String to enum:
public class Climber {
private Gender gender;
The enum could look like this:
public enum Gender {
MALE, FEMALE;
}
(that's a separate top-level class, so in a file called Gender.java). See also the Oracle tutorial about enums.
addMountain
Fix the addMountain method so it actually adds a mountain:
public void addMountain(Mountain mountain) {
mountains.add(mountain);
}
getHighestMountain
The logic of getHighestMountain is flawed (this was your question), try this:
public List<Mountain> getHighestMountain() {
Mountain highest = null;
for(Mountain mountain : mountains) {
if(highest == null || mountain.getHeight() > highest.getHeight()) {
highest = mountain;
}
}
return highest;
}

Very weird NPE when trying to copy an object

I'm trying to copy an object while passing in a parameter to the method I'm using to copy with. In the constructor for the object after I try to copy it the parameter becomes null.
This is the class that I'm trying to copy:
/**
* Represents the extra health perk
*/
public class ArrowRegen implements Perk
{
private int id = 0;
private double chance = 0.15;
private int level = 0;
private int price = 1000;
private int arrowGain = 0;
private GamePlayer ourPlayer;
public ArrowRegen(){}
public ArrowRegen(GamePlayer ourPlayer)
{
this.ourPlayer = ourPlayer;
if(this.ourPlayer == null)
aa.debug("its null");
}
#Override
public Perk getThisPerk(GamePlayer player)
{
aa.debug("returning an arrow regen");
if(player == null)
aa.debug("player is null? somehow?");
return new ArrowRegen(ourPlayer);
}
}
nothing is null up until the point in the constructor at the "its null" comment. *
This is where I call the copy from:
player.addActivePerks(PerkEngine.getPerk(1).getThisPerk(player));
(player is a GamePlayer object)
Here is the PerkEngine bit:
/**
* Gets a perk by it's ID
* #param id The Perk's ID
* #return The Perk with the specified ID
*/
public static Perk getPerk(int id)
{
for(Perk perk : perks)
{
if(perk.getID() == id)
{
return perk;
}
}
// This will never return null
return null;
}
EDIT:
I just realized my mistake was in the "getThisPerk" method. When returning the new object, I pass in the wrong variable.
I just realized my mistake was in the "getThisPerk" method. When returning the new object, I pass in the wrong variable.

Writing a .class file?

Currently, I'm working on a project where a user can enter in custom values in a GUI then those values will be translated into a .class file for the runtime to read when the program starts up. I realize that writing a .txt file would be much easier, but that is not what I want to do. The new .class file I will be making will extend from an abstract class called "Problem" also. Can someone point me in the right direction for writing the aforementioned file? Thanks in advance for helpers!
By the way, even if I have to construct a .java file then compile that somehow, that could be a solution also. But still, I don't know how to do that :/
More code:
package resources;
import java.awt.Image;
import java.io.File;
import java.io.Serializable;
public abstract class Problem implements Comparable<Problem>, Serializable{
private static final long serialVersionUID = 42L;
private File locatedAt;
public static final int EASY = 0;
public static final int MEDIUM = 1;
public static final int HARD = 2;
public abstract String getTitle();
public abstract String getQuestion();
public abstract Image getQuestionImage();
public abstract int getDifficulty();
public abstract Topic getTopic();
public abstract String getAuthor();
public abstract boolean isCorrect(String answer);
public final int compareTo(Problem p){
return this.getTitle().compareTo(p.getTitle());
}
public final String toString(){
return getTitle();
}
public final void setLocatedAt(File file){
locatedAt = file;
}
}
package resources;
import java.util.StringTokenizer;
public abstract class NumericProblem extends Problem{
/**
* You must specify the number of significant digits the answer should contain.
* If you don't want to check for significant digits, simply return 0
*
* #return the number of significant digits the answer should have
*
* #since V 1.0
*/
public abstract boolean checkSigfigs();
/**
* You must specify the amount of error from the answer the user can be within
* to remain correct. Your number should be represented as X% and not the decimal
* format.
*
* #return the amount of error the submitted answer can deviate from the specified answer
*
* #since V 1.0
*/
public abstract double getErrorPercentage();
/**
* You must specify the type of units the problem should contain.
* If the answer doesn't have any units return "". Also if the units shouldn't
* be checked, return null.
*
* #return the unit type the answer should contain
*
* #since V 1.0
*/
public abstract String getUnits();
/**
* You must specify the answer for the problem being asked. The number is
* represented as a String because of significant digits.
*
* #return the answer for the given problem
*
* #since V 1.0
*/
public abstract String getAnswer();
public final boolean isCorrect(String userAnswer){
String answer = getAnswer().trim();
userAnswer = userAnswer.trim();
StringTokenizer tokener = new StringTokenizer(userAnswer, " ");
if(tokener.countTokens() != 2){
System.err.println("Failed at formatting");
return false;
}
userAnswer = tokener.nextToken();
String userUnits = tokener.nextToken();
System.out.println(sigfigsIn(answer));
System.out.println(sigfigsIn(userAnswer));
// Checks sigificant digits
if(checkSigfigs()){
if(!(sigfigsIn(userAnswer) == sigfigsIn(answer))){
System.err.println("Failed at sig figs");
return false;
}
}
// Checks numeric
if(!checkNumeric(userAnswer, answer)){
System.err.println("Failed at numeric");
return false;
}
//Checks units
if(getUnits() != null){
if(!userUnits.equals(getUnits())){
System.err.println("Failed at units");
return false;
}
}
System.out.println("Passed!");
return true;
}
private int sigfigsIn(String aNumber){
// Removes all unnecessary zeroes before answer
boolean done = false;
boolean periodHappened = false;
while(!done)
{
if(aNumber.charAt(0) == '0'){
aNumber = aNumber.replaceFirst("0", "");
}else if (aNumber.charAt(0) == '.'){
aNumber = aNumber.replaceFirst(".", "");
periodHappened = true;
}else{
done = true;
}
}
// If it's a number like 300 with only one sig fig, do dis
if(!periodHappened){
if(!aNumber.contains(".")){
done = false;
while(!done){
if(aNumber.charAt(aNumber.length() - 1) == '0'){
aNumber = aNumber.substring(0, aNumber.length() - 1);
}else{
done = true;
}
}
}
}
return aNumber.replaceAll("\\.", "").length();
}
private boolean checkNumeric(String Answer, String UserAnswer){
double answer = Double.parseDouble(Answer);
double userAnswer = Double.parseDouble(UserAnswer);
double ep = getErrorPercentage() / 100;
if((answer * (1+ep) >= userAnswer) && (userAnswer >= answer * (1-ep)))
return true;
return false;
}
package problems;
import java.awt.Image;
import resources.NumericProblem;
import resources.Problem;
import resources.Topic;
import resources.Formula;
public class ANumericProblem extends NumericProblem{
private final Formula formula;
public ANumericProblem(){
formula = Formula.createRandomFormula();
}
#Override
public boolean checkSigfigs() {
return true;
}
#Override
public double getErrorPercentage() {
return 200;
}
#Override
public String getUnits() {
return "mols";
}
#Override
public String getAnswer() {
return Formula.getMols();
}
#Override
public String getTitle() {
return "Formula";
}
#Override
public String getQuestion() {
return "How many moles are in 4.9g of " + formula.getFormula();
}
#Override
public Image getQuestionImage() {
return null;
}
#Override
public int getDifficulty() {
return Problem.EASY;
}
#Override
public Topic getTopic() {
return new Topic("Grams to Moles");
}
#Override
public String getAuthor() {
return "Shawn";
}
}
}
It's not really what you asked for, but this problem sounds like you want to build an object with a bunch of values, then save the result for later. If this is the case, then you would probably be interested in object serialization, which allows you to basically save an object as a byte stream, and then load the object at a later time.
As Ken Wayne suggested, you need object serialization.
A few good libraries for object serialization are
JAXB (XML Serialization) : http://jaxb.java.net/
Java normal serialization : http://java.sun.com/developer/technicalArticles/Programming/serialization/
And as suggested by everyone else, .class file is probably not the best way to go through this.

Component based composition

Can anyone assist me to implement a component-based project? I have designed two components i.e calculator and engine (source codes below) which need to be inside any of the swing components (either JList , JTree, or any). Then there should be an ability of dragging any of the two components (calculator or engine) unto the editor pane for composition using a connector (code give below). If the composition is right, let the composite return unto the palette where the initial components were dragged from.
Components:
public class Engine {
private String name = "";
private boolean running = false;
private int speed;
public Engine(String name) {
this.name = name;
}
public void start() {
if (!running) {
running = true;
System.out.println("Engine starts.");
}
else
System.out.println("Engine already starts.");
}
public void stop() {
if (running) {
running = false;
speed = 0;
System.out.println("Engine stops.");
}
else
System.out.println("Engine already stops.");
}
public void setSpeed(int speed) {
if (speed >=0)
this.speed = speed;
}
}
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
public class Calc {
public Calc() {
}
public Double squareRoot(Double a_double){
return Math.sqrt(a_double);
}
// pre an_int >= 0
public synchronized Integer factorial(Integer an_int){
int fact=1;
for(int i=1;i<=an_int;i++){
fact *= i;
}
return fact;
}
/**
*
* #param an_int
* #return the squared root of the input integer
*/
public Integer getSquareRoot(Integer an_int){
return (int) Math.sqrt(an_int);
}
public Double getSquareRoot(Double aDouble){
return Math.sqrt(aDouble);
}
/**
* Converts an Integer object into a Double object.
*
* #param an_int The Integer to be converted.
* #return The Double object representing the same value.
*
*/
public Double integerToDouble(Integer an_int){
return new Double(an_int.intValue());
}
/**
* Converts a Double object into an Integer object. Decimal digits are
* truncated. Useful when passing the output of a method as the input to another.
*
* #param a_double The Double to be converted.
* #return The Integer object representing the same value.
*
*/
public Integer doubleToInteger(Double a_double){
return new Integer(a_double.intValue());
}
public Integer sum(Integer a, Integer b) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return a+b;
}
/**
* Returns a string representation of the calculator.
*/
public String toString(){
return("Calculator computation unit:\n"+super.toString());
}
void doNothing(){
}}
/////////////////////////////////////////////////////////////////////////////////////////
Your best bet is probably to leverage an existing GUI editor, where the one in Netbeans is rumoured to be good.
You will then need to add your components to the component palette. Check the Netbeans online help for further information.
Start with NetBeans, take a look at this answer, i give full details of how to create a component in NetBeans.

Categories