So for an assignment, we were tasked with building generic functions to handle objects. which in this case are 2 different card decks. One was your standard 52 playing card deck, the other was a deck of our choise. I chose Star Trek next Generation cards. (disclaimer, i know very little about junit test. it was never covered in my classes and what little i do know came from experimentation) Anyway, I have a method that will deal X amount of cards. I need help figuring out how to print out the output of the method in junit test. here is my code for the junit test and the method.
'''public void test_cardPile_dealNum() {
aceOfHearts = new StandardCard ("Hearts", "Ace");
aceOfDiamonds = new StandardCard ("Montrial", "Ace");
aceOfClubs = new StandardCard("Clubs", "Ace");
fedCaptain = new starTrekCards("Federation", "Jean Luc Picard");
fedFirstOff = new starTrekCards("Federation","Willian Riker");
fedDoctor = new starTrekCards("Federation", "Beverly Crusher");
fedCounciler = new starTrekCards("Federation","Diana Troy");
contArse = new starTrekCards ("Continuum", "Q");
romCommander = new starTrekCards("Romulan Star Empire", "Commander Sela");
romSupport = new starTrekCards ("Romulan Star Empire", "Kimara Cretak");
klingLeader = new starTrekCards ("Klingon Empire", "Chancelor Garon");
int number = 3;
CardPile test3 =new CardPile ();
LinkedStack Holder;
test3.add(aceOfHearts);
test3.add(aceOfDiamonds);
test3.add(aceOfClubs);
test3.add(fedCaptain);
test3.add(fedFirstOff);
test3.add(fedDoctor);
test3.add(fedCounciler);
test3.add(contArse);
test3.add(romCommander);
test3.add(romSupport);
test3.add(klingLeader);
Holder = test3.dealNumb(3);
System.out.println(Holder.toString());
}''''
and my method
'''
public LinkedStack<T> dealNumb(int number)
{
if(!card.isEmpty()){
LinkedStack<T> cardTwo = new LinkedStack<T>();
for(int i = 0; i< number; i++)
{
T count = card.top();
card.pop();
cardTwo.push(count);
}
return cardTwo;
}
else {
return null;
}
}'''
Thanks in advance
There's an old saying that always bears repeating :
Anything that relies on human reliability is inherently unreliable.
Everybody makes mistakes - You, me, everybody. When you run the test above, you are relying on your human reliability to spot any output that differs from what should be expected. That's unreliable, and bugs will get through (not to mention painfully boring for you ! )
The power of unit tests (such as JUnit) is that they are automated. In business, they often run entirely unattended, built into the build process that runs automatically in the background on some server machine every time anybody commits some piece of code.
As such, the tests are not for displaying the results for humans to check, but rather the test checks the results itself, typically through "Assert" statements. You'll find Junit has a few of these ("AssertThat", "AssertEquals", etc), and Hamcrest is also useful (see http://hamcrest.org/JavaHamcrest/ )
So, instead of your println, what you want to do instead is assert that you have been given the three cards you expect, and that these are no longer in your CardPile - eg :
// nb variable names like "holder" should start with lower-case
AssertThat(holder, is(equalTo(List.of(romCommander, romSupport, klingLeader))));
AssertThat(test3.size(), is(equalTo(8))));
AssertThat(test3.pop(), is(equalTo(contArse))));
(btw, the is(equalTo(List.of may not work with whatever your implementation of LinkedStack is, but hopefully you get the idea :) )
Also, personally I always prefer AssertThat over AssertEquals as it's more readable, as well as avoiding a common mistake where people write things like stuff like :
AssertEquals(test3.size(), 3);
which is the wrong way around ! The expected result should come first, so it should be :
AssertEquals(3, test3.size());
.... but better to stick with AssertThat
Related
I'd like some help with a Java assignment, if it's no problem. We've just been getting started, but my teacher wants us to do a bunch of research on our own and I can't figure out how to do the homework.
We have an assignment where he's given us the lines to 10 different speeches, and we have to use objective oriented coding to display the entire thing. I figured out so far how to set up variables to link to the first file and have things displayed on the screen, but he wants us to limit how many characters are on each line so he doesn't have to scroll sideways forever to read a speech on a single line. This leaves me in a position where I'd be making new variables for every sentence of every speech for the next few hours, and I figure there has to be a more efficient way. So, I asked my friend (who took the class last year) for advice, and he recommended using a for loop to scan for spaces after a certain amount of characters and jump to the next line to continue, but I have no idea how to do any of this. All I have so far is the base file that our teacher told us to use, and the beginning of the first of 10 speeches.
/**
* TextWriter is a program that uses objective coding to display 10 political speeches
* #author ()
* #version (10/12/16)
*/
public class TextWriter {
private String textToDisplay;//text to be displayed
public TextWriter() {
textToDisplay = "";
}
public TextWriter(String inputText) {
textToDisplay = inputText;
}
public void clearTextToDisplay() {
textToDisplay = "";
}
public void setTextToDisplay(String inputText) {
textToDisplay = inputText;
}
public String getTextToDisplay() {
return textToDisplay;
}
public void display() {
System.out.println(textToDisplay);
}
}
and the second one,
/**
* Displays Washington's Farewell speech using objective oriented coding.
* #author ()
* #version (10/12/16)
*/
public class WashingtonFarewellDriver {
public static void main(String[] args) {
TextWriter wf1;
wf1 = new TextWriter();
wf1.setTextToDisplay("Friends and Citizens: The period for a new election of a citizen to administer the executive government of the United States being not far distant, and the time actually arrived when your thoughts must be employed in designating the person who is to be clothed with that important trust, it appears to me proper, especially as it may conduce to a more distinct expression of the public voice, that I should now apprise you of the resolution I have formed, to decline being considered among the number of those out of whom a choice is to be made.");
wf1.display();
TextWriter wf2;
wf2 = new TextWriter("I beg you, at the same time, to do me the justice to be assured that this resolution has not been taken without a strict regard to all the considerations appertaining to the relation which binds a dutiful citizen to his country; and that in withdrawing the tender of service, which silence in my situation might imply, I am influenced by no diminution of zeal for your future interest, no deficiency of grateful respect for your past kindness, but am supported by a full conviction that the step is compatible with both.");
wf2.display();
TextWriter wf3;
wf3 = new TextWriter("The acceptance of, and continuance hitherto in, the office to which your suffrages have twice called me have been a uniform sacrifice of inclination to the opinion of duty and to a deference for what appeared to be your desire. I constantly hoped that it would have been much earlier in my power, consistently with motives which I was not at liberty to disregard, to return to that retirement from which I had been reluctantly drawn.");
wf3.display();
}
}
(hopefully that's formatted right)
I hope that it's ok that I'm asking for homework help, because it does seem to be kind of looked down upon, but I'm pretty confused and hopefully someone can explain what's going on a little more than my teacher.
Thank you! If there's any questions, I might be able to answer them too.
Loop thru the string character by character using String.charAt(). Keep track of how many characters you've put out. After say 25 characters the next time you see a space spit out a newline character, reset your counter to 0, and start printing it out again.
String in = "This is a run on sentence that is too long for a single line and should be broken up into multiple lines because I said so. This is a run on sentence that is too long for a single line and should be broken up into multiple lines because I said so.";
int counter=0;
for(int i=0;i<in.length();i++){
Char c=in.charAt(i);
counter++;
System.out.print(c+"");
if((counter>25)&&(c=' ')){
System.out.println();
counter=0;
}
}
There are many ways to approach this.
You can add this function in your TextWriter class for adding lines something like this:
public void addLines(int maxChars){
int lines = 1;
String[] lineStrings;
if(maxChars <= textToDisplay.length()){
if(textToDisplay.length() % maxChars > 0) lines = textToDisplay.length()/maxChars + 1;
else lines = textToDisplay.length()/maxChars;
lineStrings = new String[lines];
for(int i = 0; i < lines; i++){
if(i == (lines - 1)) lineStrings[i] = textToDisplay.substring(i*maxChars, i*maxChars + (textToDisplay.length() % maxChars)) + "\r\n";
else lineStrings[i] = textToDisplay.substring(i*maxChars, i*maxChars + maxChars) + "\r\n";
}
textToDisplay = "";
for(int i=0; i < lines; i++){
textToDisplay += lineStrings[i];
}
}
}
and in your Main function, maybe:
public class WashingtonFarewellDriver {
public static void main(String[] args) {
TextWriter wf1;
wf1 = new TextWriter();
wf1.setTextToDisplay("Friends and Citizens: The period for a new election of a citizen to administer the executive government of the United States being not far distant, and the time actually arrived when your thoughts must be employed in designating the person who is to be clothed with that important trust, it appears to me proper, especially as it may conduce to a more distinct expression of the public voice, that I should now apprise you of the resolution I have formed, to decline being considered among the number of those out of whom a choice is to be made.");
wf1.addLines(50);
wf1.display();
TextWriter wf2;
wf2 = new TextWriter("I beg you, at the same time, to do me the justice to be assured that this resolution has not been taken without a strict regard to all the considerations appertaining to the relation which binds a dutiful citizen to his country; and that in withdrawing the tender of service, which silence in my situation might imply, I am influenced by no diminution of zeal for your future interest, no deficiency of grateful respect for your past kindness, but am supported by a full conviction that the step is compatible with both.");
wf2.addLines(50);
wf2.display();
TextWriter wf3;
wf3 = new TextWriter("The acceptance of, and continuance hitherto in, the office to which your suffrages have twice called me have been a uniform sacrifice of inclination to the opinion of duty and to a deference for what appeared to be your desire. I constantly hoped that it would have been much earlier in my power, consistently with motives which I was not at liberty to disregard, to return to that retirement from which I had been reluctantly drawn.");
wf3.addLines(50);
wf3.display();
}
}
This should work, but some words will be cut off, because this just roughly separates lines by a maximum characters in a line.
thanks for all the feedback, it helped me, but ultimately there was another pretty easy way my that friend walked me through using the main.org.apache.commons.lang3.text.WordUtils package that he downloaded!
import java.io.IOException;
import org.apache.commons.lang3.text.WordUtils;
public class WashingtonFarewellDriver {
public static void main(String[] args) throws IOException {
int wwl = 110;
TextWriter wf1;
wf1 = new TextWriter(WordUtils.wrap("long sentences",wwl));
wf1.display();
}
}
I'm afraid this is a terribly stupid question. However, I can't find an answer to it and therefore require some help :)
Let's start with a simplification of my real problem:
Assume I have a couple of boxes each filled with a mix of different gems.
I'm now creating an object gem which has the attribute colour and a method getColour to get the colour of the gem.
Further I'm creating an object box which has a list of gems as attribute and a method getGem to get a gem from that list.
What I want to do now is to count all gems in all boxes by colour. Now I could either do something like
int sapphire = 0;
int ruby = 0;
int emerald = 0;
for(each box = i)
for(each gem = j)
if(i.getGem(j).getColour().equals(“blue”)) sapphire++;
else if(i.getGem(j).getColour().equals(“red”)) ruby++;
else if(i.getGem(j).getColour().equals(“green”)) emerald++;
or I could do
int sapphire = 0;
int ruby = 0;
int emerald = 0;
String colour;
for(each box = i)
for(each gem = j)
colour = i.getGem(j).getColour();
if(colour.equals(“blue”)) sapphire++;
else if(colour.equals(“red”)) ruby++;
else if(colour.equals(“green”)) emerald++;
My question is now if both is essentially the same or should one be preferred over the other? I understand that a lot of unnecessary new string objects are produced in the second case, but do I get a speed advantage in return as colour is more “directly” available?
I would dare to make a third improvement:
int sapphire = 0;
int ruby = 0;
int emerald = 0;
for(each box = i) {
for(each gem = j) {
String colour = i.getGem(j).getColour();
if(“blue”.equals(colour)) sapphire++;
else if(“red”.equals(colour)) ruby++;
else if(“green”.equals(colour)) emerald++;
}
}
I use a local variable inside the for-loop. Why? Because you probably need it only there.
It is generally better to put STATIC_STRING.equals(POSSIBLE_NULL_VALUE).
This has the advantage: easier to read and should have no performance problem. If you have a performance problem, then you should consider looking somewhere else in your code. Related to this: this answer.
conceptually both codes have equal complexity i.e.: O(i*j). But if calling a method and get a returned value are considered to be two processes then the complexity of your first code will be 4*O(i*j).(consider O(i*j) as a function) and of your second code will be O(i*(j+2)). although this complexity difference is not considerable enough but if you are comparing then yes your first code is more complex and not a good programming style.
The cost of your string comparisons is going to wipe out all other considerations in this sort of approach.
You would be better off using something else (for example an enum). That would also expand automatically.
(Although your for each loop isn't proper Java syntax anyway so that's a bit odd).
enum GemColour {
blue,
red,
green
}
Then in your count function:
Map<GemColour, Integer> counts = new EnumMap<GemColour, Integer>(GemColour.class);
for (Box b: box) {
for (Gem g: box.getGems() {
Integer count = counts.get(g.getColour());
if (count == null) {
count=1;
} else {
count+=1;
}
counts.put(g.getColour(), count);
}
}
Now it will automatically extend to any new colors you add without you needing to make any code changes. It will also be much faster as it does a single integer comparison rather than a string comparison and uses that to put the correct value into the correct place in the map (which behind the scenes is just an array).
To get the counts just do, for example:
counts.get(GemColour.blue);
As has been pointed out in the comments the java Stream API would allow you to do all of this in one line:
boxes.stream().map(Box::getGems).flatMap(Collection::stream).collect(groupingBy(Gem::getColour, counting()))
It's less easy to understand what it is doing that way though.
I am new to machine learning and Encog overall, but I would have expected Encog to at least give consistent results from the examples to help me learn about Encog more easily. For me Encoge will give different directional results each time it is run.
Can anyone help me better understand why this is? Below is some modified sample code that's being used.
Direction correct:10/25
Direction correct:8/25
Direction correct:6/25
...
public class MainPredict {
public static void main(String[] args) {
Co.println("--> Main Predict");
final MarketLoader marketLoader = new YahooFinanceLoader();
final MarketMLDataSet marketDataSet = new MarketMLDataSet(marketLoader, Config.INPUT_WINDOW, Config.PREDICT_WINDOW);
final MarketDataDescription marketDataDescription = new MarketDataDescription(Config.TICKER, MarketDataType.adjusted_close, true, true);
marketDataSet.addDescription(marketDataDescription);
Calendar end = new GregorianCalendar();// end today
Calendar begin = (Calendar) end.clone();// begin 30 days ago
begin.add(Calendar.DATE, -60);
end.add(Calendar.DATE, -60);
begin.add(Calendar.YEAR, -2);
marketDataSet.load(begin.getTime(), end.getTime());
marketDataSet.generate();
BasicNetwork basicNetwork = EncogUtility.simpleFeedForward(marketDataSet.getInputSize(), Config.HIDDEN1_COUNT, Config.HIDDEN2_COUNT, marketDataSet.getIdealSize(), true);
ResilientPropagation resilientPropagation = new ResilientPropagation(basicNetwork, marketDataSet);
resilientPropagation.setRPROPType(RPROPType.iRPROPp);
// EncogUtility.trainToError(resilientPropagation, 0.00008);
EncogUtility.trainConsole(basicNetwork, marketDataSet, 3);
System.out.println("Final Error: " + basicNetwork.calculateError(marketDataSet));
MarketEvaluate.evaluate(basicNetwork);
Encog.getInstance().shutdown();
}
}
It's pretty common for neural network weights to be initialized to random values, which pretty much trashes determinacy right up front. So to have repeatable results, you'd need to save a particular instance of your network whose random initial weights you liked, and then load that into other runs as a starting point.
In this case, basicNetwork would be the one to save (perhaps with createPersistor() to serialize to XML), then reload each time you later wanted to reset it, rather than constructing a fresh one from scratch.
Another test you could try is use basicNetwork.clone(), and then run your experiment on both of them and see how the results turn out.
Links:
http://www.heatonresearch.com/javadoc/encog-2.3/org/encog/neural/networks/BasicNetwork.html#clone%28%29
http://www.heatonresearch.com/javadoc/encog-2.3/org/encog/persist/Persistor.html
Which one of the following is a better practice to check if a string is float?
try{
Double.parseDouble(strVal);
}catch(NumberFormatException e){
//My Logic
}
or
if(!strVal.matches("[-+]?\\d*\\.?\\d+")){
//My Logic
}
In terms of performace, maintainence and readability?
And yeah, I would like to know which one is good coding practice?
Personal opinion - of the code I've seen, I would expect that most developers would tend towards the try - catch blocks. The try catch is in a sense also more readable and makes the assumption that for most cases the string will contain a valid number. But there are a number of things to consider with you examples which may effect which you choose.
How often do you expect the string to not contain a valid number.
Note that for bulk processing you should create a Pattern object outside of the loop. This will stop the code from having to recompile the pattern every time.
As a general rule you should never use expectations as logic flow. Your try - catch indicates logic if it's not a string, where as your regex indicates logic if it is a number. So it wasn't obvious what the context of the code is.
If you choose the regex technique, you are still probably going to have to convert at some point, so in effect, it may be a waste of effort.
And finally, is the performance requirements of the application important enough to warrant analysis at this level. Again generally speaking I'd recommend keeping things as simple as possible, making it work, then if there are performance problems, use some code analysis tools to find the bottle necks and tune them out.
Performance: Exceptions are slow, and so is exception-based logic, so second would be faster.
Maintenance / Reliability: The first one is crystal clear and will stay updated with updates to the Java Framework.
That being said, I would personally prefer the first. Performance is something you want to consider as a whole in your architecture, your data structure design, etc. not line by line. Measure for performance and optimize what is actually slow, not what you think might be slow.
The first one is going to perform better than the regex when the string matches the double. For one it's very fast to parse it when the recognizer is hard coded as it would be with Double.parse. Also there's nothing to maintain it's whatever Java defines as the Double is as a string. Not to mention Double.parseDouble() is easier to read.
The other solution isn't going to be compiled so the first thing that the regex has to do is compile and parse the regex expression, then it has to run that expression, then you'll have to execute Double.parseDouble() to get it into a double. And that's going to be done for every number passed to it. You might be able to optimize it with Pattern.compile(), but executing the expression is going to be slower. Especially when you have to run a Double.doubleParse to get the value into a double.
Yes exceptions are not super fast, but you'll only have to pay that price when you parse an error. If you don't plan on seeing lots of errors then I don't think you'll notice the slow down from gathering the stacktrace on the throw (which is why exceptions perform poorly). If you're only going to encounter a handful of exceptions then performance isn't going be a problem. The problem is you expected a double and it wasn't so probably some configuration mistake so tell the user and quit, or pick a suitable default and continue. That's all you can do in those cases.
If you use parseDouble, you will end up with what Mark said, but in a more readable way, and might profit from performance improvements and bug fixes.
Since exceptions are only costly when they are thrown, there is only need to look for a different strategy if you
expect wrong formats to happen often
expect them to fall in a specific pattern which you can catch faster and beforehand
In the end you will call parseDouble either, and therefore it is considered alright to use it that way.
Note that your pattern rejects 7. as a Double, while Java and C/C++ don't, as well as scientific notation like 4.2e8.
May be you can also try this way.But this is generic for a string containing valid number.
public static boolean isNumeric(String str)
{
str = "2.3452342323423424E8";
// str = "21414124.12412412412412";
// str = "123123";
NumberFormat formatter = NumberFormat.getInstance();
ParsePosition pos = new ParsePosition(0);
formatter.parse(str, pos);
return str.length() == pos.getIndex();
}
And yeah, I would like to know which one is good coding practice?
Either can be good coding practice, depending on the context.
If bad numbers are unlikely (i.e. it is an "exceptional" situation), then the exception-based solution is fine. (Indeed, if the probability of bad numbers is small enough, exceptions might even be faster on average. It depends on the relative speed of Double.parseDouble() and a compiled regex for typical input strings. That would need to be measured ...)
If bad numbers are reasonably (or very) likely (i.e. it is NOT an "exceptional" situation), then the regex-based solution is probably better.
If the code path that does the test is infrequently executed, then it really makes no difference which approach you use.
Below is performance test to see the performance difference between regular expression VS try catch for validating a string is numeric.
Below table shows stats with a list(100k) with three points (90%, 70%, 50%) good data(float value) and remaining bad data(strings).
**90% - 10% 70% - 30% 50% - 50%**
**Try Catch** 87234580 122297750 143470144
**Regular Expression** 202700266 192596610 162166308
Performance of try catch is better (unless the bad data is over 50%) even though try/catch may have some impact on performance. The performance impact of try catch is because try/catch prevents JVM from doing some optimizations. Joshua Bloch, in "Effective Java," said the following:. Joshua Bloch, in "Effective Java," said the following:
• Placing code inside a try-catch block inhibits certain optimizations that modern JVM implementations might otherwise perform.
public class PerformanceStats {
static final String regularExpr = "([0-9]*[.])?[0-9]+";
public static void main(String[] args) {
PerformanceStats ps = new PerformanceStats();
ps.statsFinder();
//System.out.println("123".matches(regularExpr));
}
private void statsFinder() {
int count = 200000;
int ncount = 200000;
ArrayList<String> ar = getList(count, ncount);
System.out.println("count = " + count + " ncount = " + ncount);
long t1 = System.nanoTime();
validateWithCatch(ar);
long t2 = System.nanoTime();
validateWithRegularExpression(ar);
long t3 = System.nanoTime();
System.out.println("time taken with Exception " + (t2 - t1) );
System.out.println("time taken with Regular Expression " + (t3 - t2) );
}
private ArrayList<String> getList(int count, int noiseCount) {
Random rand = new Random();
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < count; i++) {
list.add((String) ("" + Math.abs(rand.nextFloat())));
}
// adding noise
for (int i = 0; i < (noiseCount); i++) {
list.add((String) ("sdss" + rand.nextInt() ));
}
return list;
}
private void validateWithRegularExpression(ArrayList<String> list) {
ArrayList<Float> ar = new ArrayList<>();
for (String s : list) {
if (s.matches(regularExpr)) {
ar.add(Float.parseFloat(s));
}
}
System.out.println("the size is in regular expression " + ar.size());
}
private void validateWithCatch(ArrayList<String> list) {
ArrayList<Float> ar = new ArrayList<>();
for (String s : list) {
try {
float e = Float.parseFloat(s);
ar.add(e);
} catch (Exception e) {
}
}
System.out.println("the size is in catch block " + ar.size());
}
}
public boolean catDog(String str)
{
int count = 0;
for (int i = 0; i < str.length(); i++)
{
String sub = str.substring(i, i+1);
if (sub.equals("cat") && sub.equals("dog"))
count++;
}
return count == 0;
}
There's my code for catDog, have been working on it for a while and just cannot find out what's wrong. Help would be much appreciated!*/
EDIT- I want to Return true if the string "cat" and "dog" appear the same number of times in the given string.
One problem is that this will never be true:
if (sub.equals("cat") && sub.equals("dog"))
&& means and. || means or.
However, another problem is that your code looks like your are flailing around randomly trying to get it to work. Everyone does this to some extent in their first programming class, but it's a bad habit. Try to come up with a clear mental picture of how to solve the problem before you write any code, then write the code, then verify that the code actually does what you think it should do and that your initial solution was correct.
EDIT: What I said goes double now that you've clarified what your function is supposed to do. Your approach to solving the problem is not correct, so you need to rethink how to solve the problem, not futz with the implementation.
Here's a critique since I don't believe in giving code for homework. But you have at least tried which is better than most of the clowns posting homework here.
you need two variables, one for storing cat occurrences, one for dog, or a way of telling the difference.
your substring isn't getting enough characters.
a string can never be both cat and dog, you need to check them independently and update the right count.
your return statement should return true if catcount is equal to dogcount, although your version would work if you stored the differences between cats and dogs.
Other than those, I'd be using string searches rather than checking every position but that may be your next assignment. The method you've chosen is perfectly adequate for CS101-type homework.
It should be reasonably easy to get yours working if you address the points I gave above. One thing you may want to try is inserting debugging statements at important places in your code such as:
System.out.println(
"i = " + Integer.toString (i) +
", sub = ["+sub+"]" +
", count = " + Integer.toString(count));
immediately before the closing brace of the for loop. This is invaluable in figuring out what your code is doing wrong.
Here's my ROT13 version if you run into too much trouble and want something to compare it to, but please don't use it without getting yours working first. That doesn't help you in the long run. And, it's almost certain that your educators are tracking StackOverflow to detect plagiarism anyway, so it wouldn't even help you in the short term.
Not that I really care, the more dumb coders in the employment pool, the better it is for me :-)
choyvp obbyrna pngQbt(Fgevat fge) {
vag qvssrerapr = 0;
sbe (vag v = 0; v < fge.yratgu() - 2; v++) {
Fgevat fho = fge.fhofgevat(v, v+3);
vs (fho.rdhnyf("png")) {
qvssrerapr++;
} ryfr {
vs (fho.rdhnyf("qbt")) {
qvssrerapr--;
}
}
}
erghea qvssrerapr == 0;
}
Another thing to note here is that substring in Java's built-in String class is exclusive on the upper bound.
That is, for String str = "abcdefg", str.substring( 0, 2 ) retrieves "ab" rather than "abc." To match 3 characters, you need to get the substring from i to i+3.
My code for do this:
public boolean catDog(String str) {
if ((new StringTokenizer(str, "cat")).countTokens() ==
(new StringTokenizer(str, "dog")).countTokens()) {
return true;
}
return false;
}
Hope this will help you
EDIT: Sorry this code will not work since you can have 2 tokens side by side in your string. Best if you use countMatches from StringUtils Apache commons library.
String sub = str.substring(i, i+1);
The above line is only getting a 2-character substring so instead of getting "cat" you'll get "ca" and it will never match. Fix this by changing 'i+1' to 'i+2'.
Edit: Now that you've clarified your question in the comments: You should have two counter variables, one to count the 'dog's and one to count the 'cat's. Then at the end return true if count_cats == count_dogs.