Okay, so this is my first time implementing classes, and everything's going wrong. I'm implimenting a different class, PhraseGenerator, and the method inherited which I wish to define here is getPhrase(). It needs to return theArcha. Instead of working within it, I chose to wrap its braces around my work afterwards, and now, no matter where I put it, a different error arises. Before dealing with any of these, I want to make sure I'm putting it in the right place. To my understanding, it would go within public....FromFile implements PhraseGenerator. Any thoughts on where it should go?
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PhraseGeneratorFromFile implements PhraseGenerator {
private ParserHelperImpl parserHelper;
public String getPhrase() {
public PhraseGeneratorFromFile(String filename) {
// read file
StringBuilder fileContent = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(filename));
try {
String line = br.readLine();
while (line != null) {
fileContent.append(line);
fileContent.append('\n');
line = br.readLine();
}
String everything = fileContent.toString();
} finally {
br.close();
}
parserHelper = new ParserHelperImpl();
List<String> phraseCollection = parserHelper.getPhrases(fileContent,"phrases:");
String archetype = parserHelper.getRandomElement(phraseCollection);
boolean flagga = true;
while(flagga = true){
Pattern ptrn = Pattern.compile("#[^#]+#");
Matcher m = ptrn.matcher(archetype);
String fromMatcher = m.group(0);
String col = ":";
String token = fromMatcher+col;
List<String> pCol = parserHelper.getPhrases(fileContent, token);
String repl = parserHelper.getRandomElement(pCol);
String hash = "#";
String tk2 = hash + token + hash;
archetype = parserHelper.replace(archetype, tk2, repl);
flagga = m.find();
}
String theArcha = archetype;
return theArcha;
}
}
}
A good practice while posting a question here is :
(1). Explain in brief what you expect off your code to do.
(2). If you are experiencing certain errors, copy them here so that it can be understood what is going wrong in your code.
I seriously did not understood what you were trying to achieve but I see a missing closing bracket in
public String getPhrase()
It should be :
public String getPhrase()
{
//logic here
}
Hope this helps
Yes, it is in the right place but you are missing the closing }, which should come directly after the {. You can't put a method inside another method like that.
Because you want to return theArcha, you should instead make it what we call "an instance variable" - you may not have heard of this? If not, look it up.
Your interface is probably like this
interface PhraseGenerator {
String getPhrase();
}
Then the implementing class you wrote will take the form
class PhraseGeneratorImpl implements PhraseGenerator {
private ParserHelperImpl parserHelper;
#Override //Used for an overridden or implemented method
public String getPhrase() {
//Put all the code you want to implement here..
//If you want to make use of a helper Class the clean way is to use an instance of it(You tried it with Helper)
//If you want to make use of a utility method within the same class,
//say reading something from the file system define a private method below this method
String filePhrase = phraseGeneratorFromFile();
//Now use the filePhrase do do other stuff
}
//
private String phraseGeneratorFromFile(){
//Do all the stuff and return phrase/string so declare return type. you havent done it in the code above
}
}
Related
I have an android java pattern that I would like to convert to something similar in flutter. It's pretty straight forward but I am having difficulty finding a clear example. What this involves is having a utility class that does repetitive string manipulation routines that I can use anywhere in the project.
Here is an example. I use the CapEachWord routine in a lot of source members. See the arrow below.
import com.auto.accident.report.util.utils;
#Override
public void onResults(Bundle results) {
ArrayList<String> result = results
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
switch (REQ_CODE) {
case REQ_CODE_NOTE_SUBJECT: {
DA_RESULT = utils.capEachWord(DA_RESULT); <-------------------
tieAN_SUBJECT.setText(DA_RESULT);
startNoteInput();
break;
}
}
CapEachWord resides in a source member called utils and looks like this.
public class utils {
public static String capEachWord(String DA_RESULT) {
int splitLength;
int index = 0;
String[] words = DA_RESULT.split(" ");
splitLength = words.length;
StringBuilder DA_RESULTBuilder = new StringBuilder();
while (index < splitLength) {
int DA_SIZE = words[index].length();
words[index] = words[index].substring(0,
1).toUpperCase() +
words[index].substring(1,
DA_SIZE);
DA_RESULTBuilder.append(words[index]);
if (index != splitLength) {
DA_RESULTBuilder.append(" ");
}
index++;
}
DA_RESULT = DA_RESULTBuilder.toString();
return DA_RESULT;
}
}
What I need to know is how to properly include the utils, structure the utils member and
and ask for the conversion result. The actual conversion code I can work out myself.
You can include your utils file with import './utils.dart'; (by relative path) or import 'package:your_package_name:path/to/utils.dart'; (for path from lib folder).
In your case I would make just class Utils or something, with static methods that I could use.
Usage would be simple after proper importing to some source file:
//...
myString = Utils.capEachWord(otherString);
I'm currently in a High School level Java course. I've been doing plenty of research here, on Stack Overflow, trying to work through a project i'm currently assigned. The project consists of making modifications to, and searching through, various words pulled from an encyclopedia file. This is what I am having trouble with, the very basic form of this project. I already found the method in which to solve this problem, but i wasn't able to find a good way of implementing it. This is a copy of the code i found here: (the third method down contains the portion i took from this site)
class word
{
public String newString;
EasyReader fileIn = new EasyReader("Encyclopedia.txt");
EasyWriter fileOut = new EasyWriter("writeHere.txt");
String fileName="Encyclopedia.txt";
private String onFile;
public word()
{
onFile="";
}
public word(String s)
{
onFile=s;
}
String file = "Encyclopedia.txt";
private String readFile(String file) throws IOException
{
BufferedReader reader = new BufferedReader(new FileReader(file));
String line=null;
StringBuilder stringBuilder = new StringBuilder();
String is=System.getProperty("line.seperator");
while((line=reader.readLine())!=null)
{
stringBuilder.append(line);
stringBuilder.append(is);
}
newString=stringBuilder.toString();
return stringBuilder.toString();
}
}
So, the question: how do i use this method? i know it sounds silly, but how do run this method and then use the data later? It is supposed to take a given text file and return a string, but i'm not even sure how to get the return value after it has processed.
Any help would be greatly appreciated. I made an account here just to ask this question. If i need to post this somewhere else, or if there is a better site to use to find an answer and some more basic help, please let me know. Thanks,
-Ethan
The readFile method seems to be doing multiple things at once. It accepts a file argument which overrides the member variable with the same name. Then it reads the file into a String and sets the newString member variable to the result before returning the same result.
So I would recommend first deciding whether the method should return the data or set the member variable. If multiple methods are going to be using the result, it might be useful to use the member variable, otherwise go the return route. Also, you can probably remove the file member variable since it is ignored by the method.
You can rewrite the method to look like this (I just removed the newString=stringBuilder.toString(); line, and I changed it to static since it can be):
private static String readFile(String file) throws IOException
{
BufferedReader reader = new BufferedReader(new FileReader(file));
String line=null;
StringBuilder stringBuilder = new StringBuilder();
String is=System.getProperty("line.seperator");
while((line=reader.readLine())!=null)
{
stringBuilder.append(line);
stringBuilder.append(is);
}
return stringBuilder.toString();
}
And wherever you need to use it call it like this (remember to catch the IOException):
try {
String someString = readFile("filename.txt");
} catch(IOException e) {
// handle error
}
Remember it must be called from inside the same class unless you change private to public.
Also, it might be worth reading and following a standard code style. It can really help by distinguishing between different types of variable for example.
Actual method that read string from file is: "readFile". And in your class, you are not calling that.
private String readFile(String file) throws IOException
You can pass file name as parameter, and It will returns read string.
So, how about modify your word(String s), and add method that will return actual result of read file?
public word(String s)
{
onFile=s;
newString = readfile(onFile);
}
public getNewString(){
return newString;
}
Try this:
String file ="/path/to/file.csv"
word myWord = new word();
o = myWord.getClass().getDeclaredMethod("readFile");
o.setAccessible(true);
Object r = o.invoke(myWord);
//print result
I am taking in an array of methods and I want to chain them together to modify an object that I am working in.
For example I start with
"getStuff().get(1).get(3).setMoreStuff().put(stuff,6)"
I split it into an array called methods, and clean up the parameters inside each method and I try to modify this.
Object res = this;
String[] methods = targetString.split("\\.(?=\\D)");
for (String m : methods){
List<Object> params = new ArrayList<Object>();
List<Object> params = new ArrayList<Object>();
for (String p : m.split("\\(|,|\\)")) {
try {
if (p.indexOf(".") != -1){
double tempD = Double.parseDouble(p);
params.add(tempD);
} else {
int tempP = Integer.parseInt(p);
params.add(tempP);
}
} catch (Exception ex) { //not a number
params.add(p);
}
}
switch (params.size()) {
case 1:
res = res.getClass().getMethod(
params.get(0)
).invoke(res);
break;
case 2:
res = res.getClass().getMethod(
params.get(0),
params.get(1).getClass()
).invoke(res, params.get(1));
break;
case 3:
res = res.getClass().getMethod(
params.get(0),
params.get(1).getClass(),
params.get(2).getClass()
).invoke(res, params.get(1), params.get(2));
break;
}
in the end I notice that res has been modified the way that I expect. All the getters and setters are called correctly. But of course the underlying object "this" refers to has not been changed!
I guess I'm just calling the getters and setters of the copy I made in the first line!
now I can't just use
this.getClass().getMethod(...).invoke(...)
because I need to call the same getMethod on the object returned by this call.
To clarify:
Object res = this;
creates a "pointer" to this. So that when I call
res.getStuff().setStuff(foo)
this will also be modified.
but it seem that when I call
res = res.getStuff();
res = res.setStuff();
like I do in my loop,
this does not modify the underlying object this refers to?
Edit: Included more code as per request.
Edit2: added anther example, to clarify my problem.
Edit3: tried to add more code, its a bit hard to add a working program without including every class
Your general approach should be fine (although your approach to parameter conversion is somewhat ugly) - it's the specifics that are presumably causing you problems. Here's a short but complete program demonstrating calling methods and then seeing the difference afterwards:
import java.lang.reflect.*;
class Person {
private String name = "default";
public String getName() {
return name;
}
// Obviously this would normally take a parameter
public void setName() {
name = "name has been set";
}
}
class Test {
private Person person = new Person();
public Person getPerson() {
return person;
}
// Note that we're only declaring throws Exception for convenience
// here - diagnostic code only, *not* production code!
public void callMethods(String... methodNames) throws Exception {
Object res = this;
for (String methodName : methodNames) {
Method method = res.getClass().getMethod(methodName);
res = method.invoke(res);
}
}
public static void main(String[] args) throws Exception {
Test test = new Test();
test.callMethods("getPerson", "setName");
System.out.println(test.getPerson().getName());
}
}
The output is "name has been set" just as I'd expect. So see if you can simplify your code bit by bit, removing extra dependencies etc until you've got something similarly short but complete, but which doesn't work. I suspect you'll actually find the problem as you go.
Object does not change reference, its VALUE changes. So if you will call this.get("some key"), you will get value that the same value that you put using reflection.
Right?
I am trying to port a function I wrote in ActionScript to Java and I am having a bit of trouble. I have included the function below. I found this response to question #375420, but do I really need to write a separate class? Thanks.
public static function replaceXML(str:String):String {
return str.replace(/[\"'&<>]/g, function($0:String):String {
return StringUtil.substitute('&#{0};', $0.charCodeAt(0));
});
}
Input
<root><child id="foo">Bar</child></root>
Output
<root><child id="foo">Bar</child></root>
UPDATE
Here is my solution if anyone is wondering. Thanks Sri Harsha Chilakapati.
public static String replaceXML(final String inputStr) {
String outputStr = inputStr;
Matcher m = Pattern.compile("[&<>'\"]").matcher(outputStr);
String found = "";
while (m.find()) {
found = m.group();
outputStr = outputStr.replaceAll(found,
String.format("&#%d;", (int)found.charAt(0)));
}
return outputStr;
}
You can use regex for that.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
String myString = "<root><child id=\"foo\">Bar</child></root>";
Matcher m = Pattern.compile("[^\\p{L}\\p{N};\"+*/-]").matcher(myString);
while (m.find()) {
String found = m.group();
myString = myString.replaceAll(found, "&#" + (int)found.charAt(0) + ";");
}
System.out.println(myString);
It's working.
Output is
<root><child id="foo">Bar</child>&60;/root>
Well Java is an object oriented language, and therefore working with objects. Usually you can create a Util class, e.g. RegExUtil and provide a static method to invoke the method from any other class. The util class itself, shouldn't be instantiated. You can achieve that with a private Constructor.
public class RegExUtil {
private RegExUtil(){
//do nth.
}
public static String replaceXML(String input){
//do sth.
}
}
You should lookup Apache Commons first, because they may already provide a solution for your objective or at least you see how Util classes are made up.
These two urls should be the same:
http://localhost?asdf=1&qwer=2
http://localhost?qwer=2&asdf=1
But using 'equals()' from the URL class, I get that they're different. How can I compare them?
EDIT: Some background on this question
I'm creating a Selenium test for some url mapping. I have old url, url it should get mapped to and the actual url. I need to compare the should-be url to the actual url. List of urls is created by client. Urls with the same parameters and values are considered valid if the list of parameters is the same, and they all have the right values (order of those parameters is irrelevant)
So if I get it right, you want to compare two URL's, regardless of the order of the query part.
There does not seem to be a method for this in the URL class, so you'll have to write your own.
Also, URL is final, you cannot override URL.equals(Object).
Your method could start with calling sameFile().
If that evaluates to true, you then call getQuery(), and split it into it's components - probably with String.split("\&"). From there on, you evaluate if the parameters are the same.
Also, don't forget to check if the "#fragment" is equal, if that is important to your application.
I don't think you're going to like it, but you could do something like
URL url = new URL("http://localhost?asdf=1&qwer=2");
URL url2 = new URL("http://localhost?qwer=2&asdf=1");
System.out.println(isEqual(url, url2));
public static boolean isEqual(URL url1, URL url2) {
boolean isEqual = url1.getAuthority().equals(url2.getAuthority()) &&
url1.getPort() == url2.getPort() &&
url1.getHost().equals(url2.getHost()) &&
url1.getProtocol().equals(url2.getProtocol());
if (isEqual) {
String query1 = url1.getQuery();
String query2 = url2.getQuery();
if (query1 != null && query2 != null) {
if (query1.length() == query2.length()) {
List<String> list1 = getParameters(query1);
List<String> list2 = getParameters(query2);
for (int index = 0; index < list1.size(); index++) {
String value1 = list1.get(index);
String value2 = list2.get(index);
if (!value1.equals(value2)) {
isEqual = false;
break;
}
}
} else {
isEqual = false;
}
} else {
isEqual = false;
}
}
return isEqual;
}
protected static List<String> getParameters(String value) {
List<String> parameters = new ArrayList<String>(25);
String[] values = value.split("&");
for (String par : values) {
if (!par.contains("=")) {
par += "=null";
}
parameters.add(par);
}
Collections.sort(parameters);
return parameters;
}
URL/URI equals method is broken. At least it doesn't provide results as you would expect.
There are a lot of weird things with it. You might be interested to read
Mr. Gosling – why did you make URL equals suck?!?
or maybe
How to compare two URLs in java?
So, don't expect it would be easy.
You can create your custom comparator for your particular case but in general you might have to parse the url string.
Hope this helps
You can accomplish this with functionality available in the String class.
This approach splits the URLs into two parts, the one before the "?" and the one after (it's fine if no "?" or parameters are present). If the URLs before the "?" are equivalent, the two are "equal" for our purposes.
public boolean urlsMatchWithoutQueryParameters(String firstUrl, secondUrl) {
// Get the portion of the URLs before the "?", and before all parameters.
String firstUrlWithoutParameters = firstUrl.split("\\?", 2)[0];
String secondUrlWithoutParameters = secondUrl.split("\\?", 2)[0];
return firstUrlWithoutParameters.equals(secondUrlWithoutParameters);
}
The code is a little crowded, so you could do something pull out the String logic into a helper like so:
public boolean urlsMatchWithoutQueryParameters(String firstUrl, secondUrl) {
return getUrlWithoutParameters(firstUrl).equals(getUrlWithoutParameters(secondUrl));
}
public String getUrlWithoutParameters(String url) {
// Get the portion of the URL before the "?", and before all parameters.
return url.split("\\?", 2)[0];
}
Note: This ignores URL anchors (e.g., #photos in the url www.example.com/profiles/user123#friends).
To for anchors, simply replace "\\?" with "#" in split("\\?", 2).
I like this question so I wrote this little demo. (Sorry, I used the StringUtils class for the substrings)
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang.StringUtils;
public class URLDemo
{
/**
* #param args
* #throws MalformedURLException
*/
public static void main(String[] args)
throws MalformedURLException
{
String url1 = "http://localhost?asdf=1&qwer=2";
String url2 = "http://localhost?qwer=2&asdf=1";
URL url11 = new URL(StringUtils.substringBefore(url1, "?"));
URL url22 = new URL(StringUtils.substringBefore(url2, "?"));
if (url11.equals(url22))
{
// url are equal but still need to check the parameters
List<String> params1 = Arrays.asList(StringUtils.split(StringUtils.substringAfter(url1, "?"), "&"));
List<String> params2 = Arrays.asList(StringUtils.split(StringUtils.substringAfter(url2, "?"), "&"));
// need to check both ways
if (params1.containsAll(params2) && params2.containsAll(params1))
{
System.out.println("URLs are the same");
}
else
{
System.out.println("URLs are different");
}
}
}
}
Well these two url are infact different
http://localhost?asdf=1&qwer=2
http://localhost?qwer=2&asdf=1
//////// EDITED PART //////////
Try this....
- Use openStream() on both the url.
- Save both of them as 2 String Objects, or StringBuilder instead.
- Now compare both of them using equals().
- This will solve the problem, i think so....