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.
Related
Sorry as I know this is obvious but I cant figure it out!
I have a parent class named 'Set', representing a set of a tennis match.
public class Set {
private String set1;
private String set2;
private String set3;
//private Object[] match;
public Set() {
setSet1(set1);
setSet2(set2);
setSet3(set3);
}
public void setSet1(String set1) {
this.set1 = set1;
}
public String getSet1() {
return set1;
}
public void setSet2(String set2) {
this.set2 = set2;
}
public String getSet2() {
return set2;
}
public void setSet3(String set3) {
this.set3 = set3;
}
public String getSet3() {
return set3;
}
public String toString(){
return String.format("set1: %s, set2: %s, set3: %s", set1, set2, set3);
}
}
And a sub class of 'Set' named 'SingleSet', where i try to add the sets into an array named 'game':
public class SingleSet extends Set{
private Object homePlayer;
private Object awayPlayer;
private String[] game;
public SingleSet(Object homePlayer, Object awayPlayer){
super();
game = new String[3];
game[0] = super.getSet1();
game[1] = super.getSet2();
game[2] = super.getSet3();
setHomePlayer(homePlayer);
setAwayPlayer(awayPlayer);
}
public void setHomePlayer(Object homePlayer) {
this.homePlayer = homePlayer;
}
public Object getHomePlayer() {
return homePlayer;
}
public void setAwayPlayer(Object awayPlayer) {
this.awayPlayer = awayPlayer;
}
public Object getAwayPlayer() {
return awayPlayer;
}
public void setGame(String[] game) {
this.game = game;
}
public String[] getGame() {
return game;
}
public String toString(){
return String.format("Player: %s Vs. Player: %s, Single set game: %s, %s, %s", homePlayer, awayPlayer, game[0], game[1], game[2]);
}
}
And this is where I am trying to add the Sets from my parents class into my sub class (this is for FXML, so the code is in my controller):
public void submit() {
SingleSet game1 = new SingleSet(homePlayer1Dropdown.getValue(), awayPlayer1Dropdown.getValue());
game1.setSet1(set1Box1.getText());
game1.setSet2(set1Box2.getText());
game1.setSet3(set1Box3.getText());
System.out.println(game1);
When I print the result, all my values are null. I tried printing them individually and that worked fine, so I know the 'set1Box.getText()' is working fine.
Again sorry for any obvious rookie error!
I've updated my code and same issue. Thank you for the composition answer, I will need it for my project, but this is a IS-A relationship
Make sure that the toString() methods of the following attributes exist and return a correct string.
It seems as if there is no way to get a String from homePlayer, awayPlayer and all indices of game[x].
public String toString(){
return String.format("Player: %s Vs. Player: %s, Single set game: %s, %s, %s", homePlayer, awayPlayer, game[0], game[1], game[2]);
}
I'm writing a dictionary for Vietnamese but my Treeset just add 1 object. I've been searching for 2 days but i cant figure it out how. hope you guys help me.
public class Word implements Comparable<Word> {
private static String word_target, word_explain;
public static void setWord_target(String word_target) {
Word.word_target = word_target;
}
public static void setWord_explain(String word_explain) {
Word.word_explain = word_explain;
}
public String getWord_explain() {
return word_explain;
}
public String getWord_target() {
return word_target;
}
#Override
public int compareTo(Word word) {
return this.getWord_target().compareTo(word.getWord_target());
}
}
public class Dictionary {
private TreeSet<Word> words = new TreeSet<Word>();
public TreeSet<Word> getWords() {
return words;
}
}
public class DictionaryManagement {
static Scanner reader = new Scanner(System.in);
public static int numbers;
public static void insertFromCommandline(Dictionary dic) {
numbers = reader.nextInt();
reader.nextLine();
for (int i = 0; i < numbers; i++) {
Word putInWord = new Word();
String en_word, vn_word;
System.out.print("English Word: ");
en_word = reader.nextLine();
putInWord.setWord_target(en_word);
System.out.print("VietNameses Word: ");
vn_word = reader.nextLine();
putInWord.setWord_explain(vn_word);
dic.getWords().add(putInWord);
}
}
}
public class DictionaryCommandline {
private static int num = 1;
public static Dictionary showWord = new Dictionary();
public static void showAllWords() {
System.out.println("No |English |Vietnamese");
for (Word wr : showWord.getWords()) {
System.out.println( num++ + " |" + wr.getWord_target() + " |" + wr.getWord_explain());
}
}
public static void dictionaryBasic() {
DictionaryManagement.insertFromCommandline(showWord);
DictionaryCommandline.showAllWords();
}
}
public class Main {
public static void main(String []args) throws Exception {
DictionaryCommandline.dictionaryBasic();
}
}
Example:
Input:
2
English Word:
house
VietNameses Word:
ngoi nha
English Word:
name
VietNameses Word:
ten
-Actual Output:
No English Vietnam
1 name ten
-Expected Output:
No English Vietnam
1 house ngoi nha
2 name ten
#Huy, note that you are using static variables, try using only instance variables for your Word, instances.
This makes your compareTo method always compare the latest words you inserted because static variables are associated only with a class, representing a single value/instance at a time.
Take a look here for a few more words on static # java
I am trying to write a method that search an ArrayList of a particular word and then prints the location of all of the occurrences of the word.
Here is what I have, it works fine until I enter the word I want to search but then it prints nothing:
import java.util.ArrayList;
import java.util.Scanner;
public class W7E2 {
public static void main(String[]args) {
System.out.println("Please anter words: ");
Scanner sc = new Scanner(System.in);
String []w = sc.nextLine().split(" ");
ArrayList<Words> word = new ArrayList<Words>();
for(int i=0; i<w.length; i++) {
word.add(new Words(w[i]));
}
System.out.println(word);
System.out.println("Please enter the word you want to search: ");
String search = sc.nextLine();
for(Words ws: word) {
if(ws.equals(search)) {
System.out.println(ws.getLocation());
}
}
}
static class Words{
private String wor;
private static int number = -1;
public Words(String wor) {
this.wor = wor;
number++;
}
public int getLocation() {
return number;
}
public String toString() {
return wor;
}
}
}
In your if statement to see if the ArrayList contains the word you have:
if(ws.equals(search)) {
System.out.println(ws.getLocation());
}
But ws is a Word object and unless you override the equals() method, it will never equal the String object. You need to do something like:
if(ws.getwor().equals(search)) {
System.out.println(ws.getLocation());
}
This is assuming that you create a get method for wor.
Besides GBlodgett's answer,the number in class Word is static,so each Word instance will have a same number,you need to use a no-static variable to store the location
static class Words{
private String wor;
private static int number = -1;
private int location;
public Words(String wor) {
this.wor = wor;
number++;
location = number;
}
public int getLocation() {
return location;
}
public String toString() {
return wor;
}
}
Your code should be like this :
for(Words ws: word) {
if(ws.toString().equals(search)) { //to change
System.out.println(ws.getLocation());
}
}
ws is the object of Words class, you have to change it to toString()
What you should do is instead of
ws.equals(search)
you need to add
ws.toString().equals(search)
as you return the word from the
toString()
method in the Words Class.
So the code should look something like this,
for(Words ws: word) {
if(ws.toString().equals(search)) {
System.out.println(ws.getLocation());
}
}
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.
Im parsing an xml file. My XML handler, my object that holds an Arraylist of arrays, and the main class that runs everything and prints it. The problem is, every time I add an array to my arraylist, it changes the all of the previously added arrays to the same as the current. I thought it was just a static problem but once I took static out of everything it still is doing the same thing. Help please I need to have this done asap.
Here is my handler:
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class MyXMLHandler extends DefaultHandler {
public int counter = 0;
public String[] part = new String[4];
Boolean currentElement = false;
String currentValue = null;
public SitesList sitesList = null; /this used to be static
public SitesList getSitesList() { //this used to be static
return sitesList;
}
public void setSitesList(SitesList sitesList) { //this used to be static
MyXMLHandler handle = new MyXMLHandler(); //thats why the object
handle.sitesList = sitesList;
}
/**
* Called when tag starts ( ex:- <name>text</name> -- <name> )
*/
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentElement = true;
if (localName.equals("string-array")) {
/** Start */
String attr = attributes.getValue("name");
sitesList = new SitesList(attr);
}
}
/**
* Called when tag closing ( ex:- <name>text</name> -- </name> )
*/
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentElement = false;
/** set value */
if (counter == 4) {
sitesList.addPart(part);
counter = 0;
}
if (localName.equalsIgnoreCase("item")) {
part[counter] = currentValue;
counter++;
}
currentValue = "";
}
/**
* Called to get tag characters ( ex:- <name>text</name> -- to get
* text Character )
*/
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currentElement) {
currentValue = new String(ch, start, length);
currentElement = false;
}
}
}
Here is my SitesList object
import java.util.ArrayList;
/** Contains getter and setter method for varialbles */
public class SitesList {
/** Variables */
private ArrayList<String[]> part = new ArrayList<String[]>();
/**
* In Setter method default it will return arraylist change that to add
*/
public SitesList(String c) {
String[] comp = new String[1];
comp[0] = c;
part.add(comp);
// company name is part(0)[0]
}
public String getCompany() {
return this.part.get(0)[0];
}
public ArrayList<String[]> getPart() {
return part;
}
public void addPart(String[] name) {
part.add(name);
}
public String getName(int i) {
return this.part.get(i)[0];
}
public String getComp1(int i) {
return this.part.get(i)[1];
}
public String getComp2(int i) {
return this.part.get(i)[2];
}
public String getComp3(int i) {
return this.part.get(i)[3];
}
public int getSize() {
return this.part.size();
}
}
You're reusing part, i.e. you add it multiple times but overwrite its contents. ArrayList is innocent here :)
Change the adding part to this:
if (counter == 4) {
sitesList.addPart(part);
//create a new array
part = new String[4];
counter = 0;
}
Or, as of Java 6:
if (counter == 4) {
//add a copy to the list
sitesList.addPart(Arrays.copyof(part, part.length));
counter = 0;
}
In reality, the List's values are not changing when the next value is added, but the array part is changed. What I mean is, the List has, at each location, a reference to the same array, which you call part. In other words, the List does not actually copy of the object but stores something (think of it as a "variable") that refers to the object.
So naturally, if you change the object the List is referring to at any index, you will see those changes when you pull out of the List. To solve this problem, create a new array every time you add to the list explicitly using the new keyword (or you can clone the array every time you add).