java - Letter Counter (with substring rather than the usual atChar() method) -
i have programming challenge , i'm bit stuck how work. challenge follows:
write programme asks user come in string, , asks user come in character. programme should count , display number of times specified character appears in string.
the code:
import java.util.scanner; public class f***around { public static void main(string[] args) { scanner keyb = new scanner(system.in); string word, character, test; int c = 0; system.out.println("enter word: "); word = keyb.nextline(); system.out.println("enter character: "); character = keyb.nextline(); for(int x = 1; x <= word.length(); x++) { test = word.substring(1, 2); if (test.equals(character)) { c += c; } } system.out.println(c); } }
it returns 0 @ end , can't figure out what's wrong.
2 changes needed:
use iteration variablex
loop through string. currently, hard coding substring compared, loop virtually useless. increment c
1 since increasing count every 1 time character found. so, code should become this:
for(int x = 0; x < word.length(); x++) { test = word.substring(x, x+1); if (test.equals(character)) { c += 1; } }
java
No comments:
Post a Comment