java - The number occurrence of a character is to be counted in a given line string. Can anyone point out where the error is? The code compiles correctly -
the idea count number of occurrence of given character user inputs in line of string imputed user. idea use recursion in java rather sort of loop. code compiles correctly , runs correctly. result not give correct answer (does not count asked character correctly in given line of string.) can point out?
import java.util.scanner; public class numberofletters { public static int lettercounter(string line, string x) { if(line.isempty()) { return 0; } else { if(line.charat(0) == 'x') { return 1 + lettercounter(line.substring(1), x); } else { return 0 + lettercounter(line.substring(1), x); } } } public static void main(string[] args) { scanner keyboard = new scanner(system.in); system.out.println("enter line of string >_ "); string inputline = keyboard.nextline(); system.out.println("enter character count >_ "); string charac = keyboard.nextline(); int count = lettercounter(inputline, charac); system.out.println("the number of '"+ charac + "' in input '"+ inputline + "' "+ count); keyboard.close(); } }
you're testing 'x' instead of variable:
if(line.charat(0) == 'x')
you need:
if(line.charat(0) == x)
also pass x in char instead of string.
Comments
Post a Comment