Writing a .class file? - java

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.

Related

How can I make this program run when it says could not find or load main class?

I'm very new to Java and I keep getting this error and I can't figure it out.
Error: Could not find or load main class
restaurantclient.RestaurantClient
Java Result: 1
This is on Netbeans and I'm sure I've done everything right. This is for my homework for a Java class and I would really appreciate your help. I have been working on this problem for days now.
import java.text.DecimalFormat;
public class RestaurantClient {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Restaurant r1;
Restaurant r2;
r1 = new Restaurant("PizzaHut", 152, (float) 4.95); //instantiating
r2 = new Restaurant("Dominos", 10, (float) 3.657);
System.out.print(r1.toString());
System.out.print(r2.toString());
r2.setPeopleServed(r1.getPeopleServed());
r2.setAveragePrice(r1.getAverageMeal());
if (r1.equals(r2)) //checking if equal
System.out.println("\nThe two objects are the same");
else
System.out.println("\nThe two objects are NOT the same");
r2.setName(r1.getName());
if (r1.equals(r2)) //checking if equal
System.out.println("\nThe two objects are the same");
else
System.out.println("\nThe two objects are NOT the same");
DecimalFormat pricePattern = new DecimalFormat("$###,###,000.00");
System.out.println("Tax paid per year: " + pricePattern.format(r1.averageTaxes()));
}
}
//Restaurant.java
public class Restaurant extends Store {
private int peopleServed;
private float avgmeal;
public Restaurant(String newName, int peopleServed, float avgmeal) {
super(newName);
setPeopleServed(peopleServed);
setAveragePrice(avgmeal);
}
public void setPeopleServed(int newpeopleServed) {
if (newpeopleServed >= 0)
peopleServed = newpeopleServed; //mutator alows client to change the value of name
else
System.out.println("Number has to be greater than zero");
}
public void setAveragePrice(float newprice) {
if (newprice >= 0)
avgmeal = newprice; //mutator alows client to change the value of name
else
System.out.println("Number has to be greater than zero");
}
public int getPeopleServed() {
return peopleServed; //accessor; returns current value
}
public float getAverageMeal() {
return avgmeal; //accessor; returns current value
}
public String toString() {
return "Name of store is: " + super.getName() +
"\nNumber of people served is " + peopleServed +
"\nAverage price per person is " + avgmeal + "\n";
}
public boolean equals(Object o) {
if (!(o instanceof Restaurant))
return false;
else {
Restaurant objRest = (Restaurant) o;
if (avgmeal == objRest.avgmeal && peopleServed == objRest.peopleServed && super.equals(objRest))
return true;
else
return false;
}
}
public double averageTaxes() {
double avgtaxes = (double)(super.taxrate * (peopleServed * avgmeal * 365));
return avgtaxes; //accessor; returns current value
}
}
//Store.java
public class Store {
private String storename;
public final float taxrate = (float) .08000;
public Store(String newName) //constructor
{
setName(newName);
}
public String getName() {
return storename; //accessor; returns current value
}
public void setName(String newName) {
storename = newName; //mutator alows client to change the value of name
}
public String toString() {
return "Name of store is: " + storename;
}
public boolean equals(Object o) {
if (!(o instanceof Store))
return false;
else {
Store objStore = (Store) o;
if (storename.equals(objStore.storename))
return true;
else
return false;
}
}
}
The system is looking for a main class restaurantclient.RestaurantClient, so a class RestaurantClient in package restaurantClient, but your class RestaurantClient seems to be in the default package.
try this if you are not getting any compilation issues.
You can :
RightClick on project node and go to Set configuration.
Select the main class for your application.
Then clean and build.
Even if the above steps don't work for you then then delete the Netbeans cache by deleting the (index) folder
Fore more details
Follow the stackOverflow question
Netbeans - Error: Could not find or load main class

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;
}

Is it a good way to implement Distance with diffrent units

I was looking for some good patterns to have possibility to express distance in different units. I found Martin Fowler article about quantities and I programmed something like:
Here is Distance class ( I think it is not necessery to make it abstract ):
public class Distance {
double mValue;
DistanceUnit mUnit;
public Distance(double value, DistanceUnit unit){
this.mValue = value;
this.mUnit = unit;
}
public Distance toUnit(DistanceUnit unit){
double factor = this.mUnit.getMetresFactor()/unit.getMetresFactor();
double newValue = this.mValue * factor;
Distance distance = new Distance(newValue, unit);
return distance;
}
#Override
public String toString(){
return String.valueOf(mValue);
}
}
It looks very simple. Conversion toUnit is based on DistanceUnit method getMetresFactor. Each Unit class implements DistanceUnit interface and has method getMetresFactor() like:
public interface DistanceUnit {
double getMetresFactor();
}
public class Inch implements DistanceUnit {
#Override
public double getMetresFactor() {
return 0.0254;
}
}
public class Kilometer implements DistanceUnit {
#Override
public double getMetresFactor() {
return 1000.0;
}
}
And the usage is for example:
Distance inches = new Distance(300.0, new Inch());
Distance kilometres = inches.toUnit(new Kilometres());
So it returns the correct value.
Is it good way to store distance in this way? Maybe you know some weaknesses of this approach. Maybe is a good idea to use here a FactoryMethod pattern to construct distance based on unit shortcut like "m" for meter. I think about the amount of classes if I would have a lot of units... Is it good idea to have factory which return factor of meters based on unit name? There will be no classes for units then?
Hm, i would use enum instead of DistanceUnit classes, because there is no different instances of them.
You can set a value to enum like here
and then call enum.getValue() instead of unit.getMetresFactor().
Also it is a little bit confusing, is the mValue value in meters or in DistanceUnit's, if in meters, you must have
double factor = unit.getMetresFactor();
there
Ok and now with any convertion function support:
import java.util.HashMap;
import java.util.Map;
public abstract class MeasureConverter {
public abstract double valueToBasic(double value);
public abstract double basictoValue(double basic);
/**
*
*/
public static Map<String, MeasureConverter> converters;
public static Map<String, MeasureConverter> getConverters() {
if (converters == null) {
converters = new HashMap<String, MeasureConverter>();
converters.put("kilo", new MeasureConverter() {
#Override
public double valueToBasic(double value) {
return value * 1000;
}
#Override
public double basictoValue(double basic) {
return basic / 0.001;
}
});
// taking the basic temperature value in kelvines
converters.put("kelvine", new MeasureConverter() {
#Override
public double valueToBasic(double value) {
return value;
}
#Override
public double basictoValue(double basic) {
return basic;
}
});
converters.put("celsius", new MeasureConverter() {
#Override
public double valueToBasic(double value) {
return value + 273.15;
}
#Override
public double basictoValue(double basic) {
return basic - 273.15;
}
});
converters.put("faren", new MeasureConverter() {
#Override
public double valueToBasic(double value) {
return value * 1.8 - 459.67 ; // or whatever is there?
}
#Override
public double basictoValue(double basic) {
return (basic + 459.67 ) / 1.8;// or whatever is there?
}
});
}
return converters;
}
}
And then :
import java.util.Objects;
public class MeasurePattern {
double value;
String name;
public MeasurePattern(double value, String name) {
this.value = value;
this.name = name;
}
#Override
public String toString() {
return "MeasurePattern{" + "value=" + value + ", name=" + name + '}';
}
#Override
public int hashCode() {
int hash = 7;
hash = 29 * hash + (int) (Double.doubleToLongBits(this.value) ^ (Double.doubleToLongBits(this.value) >>> 32));
hash = 29 * hash + Objects.hashCode(this.name);
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final MeasurePattern other = (MeasurePattern) obj;
if (Double.doubleToLongBits(this.value) != Double.doubleToLongBits(other.value)) {
return false;
}
if (!Objects.equals(this.name, other.name)) {
return false;
}
return true;
}
public MeasurePattern convertTo(String converter) {
MeasureConverter mycon = MeasureConverter.getConverters().get(name);
MeasureConverter hiscon = MeasureConverter.getConverters().get(converter);
double basic = mycon.valueToBasic(value);
double hisValue = hiscon.basictoValue(basic);
return new MeasurePattern(hisValue, converter);
}
public static void main(String[] args) {
//trying temperatures;
MeasurePattern temp = new MeasurePattern(10, "celsius");
MeasurePattern kelvine = temp.convertTo("kelvine");
MeasurePattern faren = kelvine.convertTo("faren");
MeasurePattern cels = faren.convertTo("celsius");
System.out.println("kelvine = " + kelvine);
System.out.println("faren = " + faren);
System.out.println("cels = " + cels);
}
}
Output:
kelvine = MeasurePattern{value=283.15, name=kelvine}
faren = MeasurePattern{value=412.67777777777775, name=faren}
cels = MeasurePattern{value=9.999999999999943, name=celsius}
You can implement it analog to java.util.concurrent.TimeUnit as an enum. E.g.
public enum DistanceUnit {
KILOMETER {
#Override
protected double conversionFactor(DistanceUnit toDistanceUnit) {
switch (toDistanceUnit) {
case KILOMETER:
return 1;
case MILE:
return 0.621371;
default:
throw new UnsupportedOperationException(toDistanceUnit + " is not supported");
}
}
},
MILE {
#Override
protected double conversionFactor(DistanceUnit toDistanceUnit) {
switch (toDistanceUnit) {
case KILOMETER:
return 1.60934;
case MILE:
return 1;
default:
throw new UnsupportedOperationException(toDistanceUnit + " is not supported");
}
}
};
public double toDistance(double value, DistanceUnit targetDistance) {
return value * conversionFactor(targetDistance);
}
protected abstract double conversionFactor(DistanceUnit toDistanceUnit);
}
change your Distance class to
public class Distance {
double mValue;
DistanceUnit mUnit;
public Distance(double value, DistanceUnit unit){
this.mValue = value;
this.mUnit = unit;
}
public Distance toUnit(DistanceUnit unit){
double newValue = mUnit.toDistance(mValue, unit);
Distance distance = new Distance(newValue, unit);
return distance;
}
#Override
public String toString(){
return String.valueOf(mValue);
}
}
and the client code will look very clear
public class Main {
public static void main(String[] args) {
Distance kilometers = new Distance(265.35, DistanceUnit.KILOMETER);
Distance miles = kilometers.toUnit(DistanceUnit.MILE);
System.out.println(miles);
}
}
will output
164.88079485000003
Java convention does not use a m(ember) prefix (but say a this. qualification), and convention is taken quite seriously in java (as opposed to C++ for instance).
toString misses the unit.
JScience offers more, the capability to calculate in different units, m/s², and so on. Your class is a nice abstraction. But in a wider context, you probably will want to have math operations, powers of units (-2 for s above).
Take a look at your own usage ideas first:
(Just garbage:)
U speedUnit = U.of(Distance::km, Time::h.up(-1));
double timeInS = U.mile(40).div(speedunit(30)).in(U.m);
I think you should use the "Strategy" pattern.
An interface:
public interface DistanceUnit {
double getDistance(int metres);
}
The Inch class:
public class Inch implements DistanceUnit {
#Override
public double getDistance(int metres) {
return meters*39; //do conversion here
}
}
The Kilometers class:
public class Kilometres implements DistanceUnit {
#Override
public double getDistance(int metres) {
return meters/1000; //do conversion here
}
}
Then:
List<DistanceUnit> distanceList = new ArrayList<>();
distanceList.add(new Inch());
distanceList.add(new Kilometres());
for (DistanceUnit item : distanceList) {
System.out.println(item.getDistance(1000));
}
If I understand you, I think it is a simple and clean solution.
You can follow this model for conversion between others units.

Fill in the blank

I'm having a problem replacing my String.
This is the Question class method.
public class Question
{
private String text;
private String answer;
/**
Constructs a question with empty question and answer.
*/
public Question(String qText)
{
text = qText;
answer = "";
}
/**
Sets the answer for this question.
#param correctResponse the answer
*/
public void setAnswer(String correctResponse)
{
answer = correctResponse;
}
/**
Checks a given response for correctness.
#param response the response to check
#return true if the response was correct, false otherwise
*/
public boolean checkAnswer(String response)
{
return response.equals(answer);
}
/**
Displays this question.
*/
public void display()
{
System.out.println(text);
}
}
And this is my method
This is my blankQuestions class
import java.util.ArrayList;
public class BlankQuestion extends Question {
public BlankQuestion(String qText) {
return qText.replaceAll("_+\\d+_+", "_____");
String tempSplit[] = questionText.split("_");
setAnswer(tempSplit[1]);
}
public void setAnswer(String correctChoice){
super.setAnswer( correctChoice );
}
#Override
public boolean checkAnswer (String response){
return super.checkAnswer(response);
}
public String toString(){
return super.toString();
}
}
This is my main class
import java.util.Scanner;
public class QuestionDemo
{
public static void main(String[] args)
{
Question[] quiz = new Question[2];
BlankQuestion question0 = new BlankQuestion(
"2 + 2 = _4_");
quiz[0] = question0;
BlankQuestion question1 = new BlankQuestion(
"The color of the sky is _blue_.");
quiz[1] = question1;
Scanner in = new Scanner(System.in);
for (Question q : quiz)
{
q.display();
System.out.println("Your answer: ");
String response = in.nextLine();
System.out.println(q.checkAnswer(response));
}
}
}
From what I understand, I'm replace [underscore]4[underscore] with 5x[underscore], this is similar to filling in the blank, I store the 4. and replace the part of the string with _____. Unfortado, that is my result. I think my logic is right, but I have no idea why my return is not what I expected.
Just do it all at once:
return qText.replaceAll("_+\\d+_+", "_____");
It replaces one or more underscores followed by one or more digits followed by one or more underscores with five underscores.

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