Hey guys, this is my assignment:
Ask the user for a single letter and a sentence, and print out the
number of times that letter shows up in the sentence.
Please tell me how to scan for a character. I tried this:
import java.util.Scanner;
public class Frequencies
{
public static final void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
System.out.println("Enter a sentence");
String x = scanner.next();
System.out.println("Enter a letter to look for");
String y = scan.next();
char z = y.charAt(0);
int chara = 0;
for(int i = 0; i<x.length(); i++){
if(z==y.charAt(i)){
chara = chara++;
}
}
System.out.println("There are " + chara + " " + z + "s in the sentence");
}
}
and got the error after Running (not compiling):
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.charAt(String.java:687)
at Frequencies.main(Frequencies.java:16)
I thought this meant that I was asking for the character in postition 1 of string y, but in my code I wrote position 0
when I tried inserting words in the character place (just to see what happened, not expecting functionallity, I got
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: [NUMBER OF CHARACTERS]
at java.lang.String.charAt(String.java:687)
at Frequencies.main(Frequencies.java:16)
Please help.
The assignment isn't due nor graded, this is just killing me lol.
Thanks in advance
Edited by: Sevan on Oct 18, 2008 4:40 PM