Jump to content

Java Programming Issue

Go to solution Solved by DeadlyGrnSpirit,
2 minutes ago, Undertaker225 said:

Could you give me a sample of the test code that you used to verify the output?

I did, make a new class called "Main" and paste what I posted. It outputs to the console the result.

 

EDIT: Do you want a logic check or?

Hello Everyone, I have been trying to solve a recursive issue in a java, but I can't quite get the result that I am looking for, I was wondering if there was anyone who could help me.

    public static int characterCount(final NCString s, char c){
      int charCount = 0; // initialize the character count to zero, to see how many times it appears
      if(s.getLength() > 0){
        if(s.getFirstChar() == c){ // checks the first letter for similar value
          charCount++; // increments charCount
        }
        if(s.getLastChar() == c){ // checks the last letter for similar value
          charCount++; // increments charCount
        }
        return (characterCount(s.getMiddleChars(), c) + charCount); // calls recursively with middleChars parameter, and the same c value.
      }
      return charCount; /* returns the int charCount. Showing how many times the character shows up in the string. */
    }

The goes is to use a custom class called NCString. This NCString only has a getLength(), getFirstChar(), getLastChar(), and getMiddleChars() methods. Using only those methods I was trying to get the amount of times that character 'c' is present in the string using RECURSION. If there is any help that someone could give me then I would greatly appreciate it. Thanks in advance.

 

Link to comment
https://linustechtips.com/topic/740155-java-programming-issue/
Share on other sites

Link to post
Share on other sites

In general it will be easier for people to help you (whether it's here, stackoverflow, reddit, etc.) if you provide 3 things:

1) what is your test data

2) what is the outcome you are getting

3) what is the outcome you expected

 

The only thing I can see based off of just this snippet, is that you will likely double count an occurrence of c when it is in the exact middle of an odd length string. 

 

for example, if you had an NCString, "abc", and you called characterCount(yourNCString, 'b') your first time through the function would result in a charCount of 0, since neither 'a' nor 'b' are what you are counting. The next time through your recursive function however, your only character will be 'b', since you trimmed 'a' and 'c' off of 'abc'. I can't see your implementation for getFirst/LastChar, but i'd be willing to bet money that you are hitting both of your if statements and incrementing charCount twice in this case, since 'b' is both your first and last character. 

 

If that's not the issue you're having, then we're probably going to need more details. 

 

hope that helps :)

Gaming build:

CPU: i7-7700k (5.0ghz, 1.312v)

GPU(s): Asus Strix 1080ti OC (~2063mhz)

Memory: 32GB (4x8) DDR4 G.Skill TridentZ RGB 3000mhz

Motherboard: Asus Prime z270-AR

PSU: Seasonic Prime Titanium 850W

Cooler: Custom water loop (420mm rad + 360mm rad)

Case: Be quiet! Dark base pro 900 (silver)
Primary storage: Samsung 960 evo m.2 SSD (500gb)

Secondary storage: Samsung 850 evo SSD (250gb)

 

Server build:

OS: Ubuntu server 16.04 LTS (though will probably upgrade to 17.04 for better ryzen support)

CPU: Ryzen R7 1700x

Memory: Ballistix Sport LT 16GB

Motherboard: Asrock B350 m4 pro

PSU: Corsair CX550M

Cooler: Cooler master hyper 212 evo

Storage: 2TB WD Red x1, 128gb OCZ SSD for OS

Case: HAF 932 adv

 

Link to comment
https://linustechtips.com/topic/740155-java-programming-issue/#findComment-9386172
Share on other sites

Link to post
Share on other sites

1 hour ago, reniat said:

In general it will be easier for people to help you (whether it's here, stackoverflow, reddit, etc.) if you provide 3 things:

1) what is your test data

2) what is the outcome you are getting

3) what is the outcome you expected

 

The only thing I can see based off of just this snippet, is that you will likely double count an occurrence of c when it is in the exact middle of an odd length string. 

 

for example, if you had an NCString, "abc", and you called characterCount(yourNCString, 'b') your first time through the function would result in a charCount of 0, since neither 'a' nor 'b' are what you are counting. The next time through your recursive function however, your only character will be 'b', since you trimmed 'a' and 'c' off of 'abc'. I can't see your implementation for getFirst/LastChar, but i'd be willing to bet money that you are hitting both of your if statements and incrementing charCount twice in this case, since 'b' is both your first and last character. 

 

If that's not the issue you're having, then we're probably going to need more details. 

 

hope that helps :)

Hello, sorry for the lack on information! And, as for your predictions, I would have assumed the same thing. HOWEVER, no matter what the input is, I get 0 as the count. the function is meant to get the correct count no matter what the input would be. I know that the NCString works because in the same class I tested for palindromes. One of my tests is "helloolleh" which is hello and hello backwards. I then ask how many times 'l' occurs, and then I will get zero. I have tested this multiple times with different data and produce the same result.

Link to comment
https://linustechtips.com/topic/740155-java-programming-issue/#findComment-9386704
Share on other sites

Link to post
Share on other sites

1 minute ago, DeadlyGrnSpirit said:

Can I get the source for NCString please?

import java.util.NoSuchElementException;

/**
 * A special form of a String with only a few allowable operations. Internally, an NCString is modeled as a String,
 * but it only exposes a few methods for us to use, which let us ask the length, first, last, and middle characters
 * of the string. We cannot ask if two NCStrings are equal directly.
 */
public class NCString {

    /** The internal String representation. */
    private final String string;

    /**
     * Constructs a new NCString with the given String.
     *
     * @param string The base String to use.
     */
    public NCString(final String string){
        if (string == null){
            throw new IllegalArgumentException("String cannot be null.");
        }
        this.string = string;
    }

    /**
     * Returns the number of characters in the NCString.
     *
     * @return The number of characters in this NCString.
     */
    public int getLength(){
        return this.string.length();
    }

    /**
     * Returns the first character of the NCString. The NCString is expected to be nonempty, or else
     * a NoSuchElementException will be thrown. Note that the first character may also be the last character if
     * the NCString only has length 1.
     *
     * @return The first character in this NCString, if it exists.
     */
    public char getFirstChar(){
        if (this.string.length() == 0){
            throw new NoSuchElementException("The NCString is empty!");
        }
        return this.string.charAt(0);
    }

    /**
     * Returns the last character of the NCString. The NCString is expected to be nonempty, or else
     * a NoSuchElementException will be thrown. Note that the last character may also be the first character if
     * the NCString only has length 1.
     *
     * @return The last character in this NCString, if it exists.
     */
    public char getLastChar(){
        if (this.string.length() == 0){
            throw new NoSuchElementException("The NCString is empty!");
        }
        return this.string.charAt(this.string.length()-1);
    }

    /**
     * Returns the characters in between the first and last characters of the NCString. If the NCString has length 2,
     * this will be the empty string. If the NCString is empty or has only one character, there is no middle and so
     * a NoSuchElementException will be thrown.
     *
     * @return The middle characters of this NCString as a new NCString.
     */
    public NCString getMiddleChars(){
        if (this.string.length() <= 1){
            throw new NoSuchElementException("The NCString has no middle.");
        }
        return new NCString(this.string.substring(1,this.string.length()-1));
    }

    /**
     * {@inheritDoc}
     */
    public int hashCode(){
        return this.string.hashCode();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String toString(){
        return "<NCString with value: \"" + this.string + "\">";
    }

    /**
     * @{inheritDoc}
     */
    @Override
    public boolean equals(final Object obj){
        throw new UnsupportedOperationException("You cannot directly compare NCString objects!");
    }

}

 

Link to comment
https://linustechtips.com/topic/740155-java-programming-issue/#findComment-9386911
Share on other sites

Link to post
Share on other sites

Run this code

 


public class Main {

	public static void main(String[] args) {
		NCString test = new NCString("test");
		
		System.out.println(characterCount(test, 't'));
	}
	
	public static int characterCount(final NCString s, char c){
	      int charCount = 0; // initialize the character count to zero, to see how many times it appears
	      if(s.getLength() > 0){
	        if(s.getFirstChar() == c){ // checks the first letter for similar value
	          charCount++; // increments charCount
	        }
	        if(s.getLastChar() == c){ // checks the last letter for similar value
	          charCount++; // increments charCount
	        }
	        return (characterCount(s.getMiddleChars(), c) + charCount); // calls recursively with middleChars parameter, and the same c value.
	      }
	      return charCount; /* returns the int charCount. Showing how many times the character shows up in the string. */
	    }

}

Using the same NCString class you posted. It output 2 for me, so if im understanding correctly the problem was it wasnt returning correctly yeah? Im not sure what I did but I think its working

Link to comment
https://linustechtips.com/topic/740155-java-programming-issue/#findComment-9386948
Share on other sites

Link to post
Share on other sites

1 minute ago, DeadlyGrnSpirit said:

Run this code

 


public class Main {

	public static void main(String[] args) {
		NCString test = new NCString("test");
		
		System.out.println(characterCount(test, 't'));
	}
	
	public static int characterCount(final NCString s, char c){
	      int charCount = 0; // initialize the character count to zero, to see how many times it appears
	      if(s.getLength() > 0){
	        if(s.getFirstChar() == c){ // checks the first letter for similar value
	          charCount++; // increments charCount
	        }
	        if(s.getLastChar() == c){ // checks the last letter for similar value
	          charCount++; // increments charCount
	        }
	        return (characterCount(s.getMiddleChars(), c) + charCount); // calls recursively with middleChars parameter, and the same c value.
	      }
	      return charCount; /* returns the int charCount. Showing how many times the character shows up in the string. */
	    }

}

Using the same NCString class you posted. It output 2 for me, so if im understanding correctly the problem was it wasnt returning correctly yeah? Im not sure what I did but I think its working

Could you give me a sample of the test code that you used to verify the output?

Link to comment
https://linustechtips.com/topic/740155-java-programming-issue/#findComment-9386950
Share on other sites

Link to post
Share on other sites

2 minutes ago, Undertaker225 said:

Could you give me a sample of the test code that you used to verify the output?

I did, make a new class called "Main" and paste what I posted. It outputs to the console the result.

 

EDIT: Do you want a logic check or?

Edited by DeadlyGrnSpirit
Link to comment
https://linustechtips.com/topic/740155-java-programming-issue/#findComment-9386953
Share on other sites

Link to post
Share on other sites

1 minute ago, DeadlyGrnSpirit said:

I did, make a new class called "Main" and paste what I posted. It outputs to the console the result.

Sorry! I read over that part thinking that was a copy of the code that I had sent you. It seems as if the problem existed with the code that I was using to test it for some reason. Thank you very much for the help as this was the issue!

Link to comment
https://linustechtips.com/topic/740155-java-programming-issue/#findComment-9386966
Share on other sites

Link to post
Share on other sites

2 minutes ago, Undertaker225 said:

Sorry! I read over that part thinking that was a copy of the code that I had sent you. It seems as if the problem existed with the code that I was using to test it for some reason. Thank you very much for the help as this was the issue!

Glad I could help man, it happens to us all xD

Link to comment
https://linustechtips.com/topic/740155-java-programming-issue/#findComment-9386972
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×