Note that there are some explanatory texts on larger screens.

plurals
  1. POPassing Generic Type into indexOf method JAVA
    primarykey
    data
    text
    <p>I want to use the <code>indexOf</code> method to find the number of words, and letters in a String. </p> <p>indexOf method can accept:</p> <pre><code>indexOf(String s) indexOf(Char c) indexOf(String s, index start) </code></pre> <p>So the method can accept <strong>Strings</strong> or <strong>Characters</strong> and can also accept <strong>starting point</strong></p> <p>I want to be able to pass either a String or a Character into this method so I have tried to use generics. The code below is main and 2 functions. As you can see I want to be able to have indexOf work with String or Character that I pass in. If I cast 's' in indexOf to a String, it works, but then crashes when it tries to run as Char. Thanks so much in advance! </p> <pre><code>public static void main(String[] args) { MyStringMethods2 msm = new MyStringMethods2(); msm.readString(); msm.printCounts("big", 'a'); } public &lt;T&gt; void printCounts(T s, T c) { System.out.println("***************************************"); System.out.println("Analyzing sentence = " + myStr); System.out.println("Number of '" + s + "' is " + countOccurrences(s)); System.out.println("Number of '" + c + "' is " + countOccurrences(c)); } public &lt;T&gt; int countOccurrences(T s) { // use indexOf and return the number of occurrences of the string or // char "s" int index = 0; int count = 0; do { index = myStr.indexOf(s, index); //FAILS Here if (index != -1) { index++; count++; } } while (index != -1); return count; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload