Java: How to Count a Character in a String - java

I have to count the number of times that a character appears in a string.
I know this question has been asked previously. However, the solutions that I've seen use commands/techniques that I haven't yet covered in class.
Here is my code:
import java.util.Scanner;
/*
This program counts the number of occourances of a char in a string.
*/
public class LetterCounter
{
public static void main(String[] args)
{
int i, length, count=0;
String input;
char letter1, letter2;
// Create a Scanner object for keyboard input.
Scanner stdin = new Scanner(System.in);
// Get a string from user
System.out.print("Enter a string: ");
input = stdin.nextLine();
// Get a character from user
System.out.print("Enter a character: ");
letter1 = stdin.next().charAt(0);
//Determine the length of the string
length = input.length();
//Count the number of times the user selected character appears in the string
for (i = 0; i <= length; i++)
{
letter2 = input.charAt(i);
if (letter1 == letter2)
{
count++;
}
}
System.out.printf("Occurrences of a %s in %s is %d", letter1, input, count);
}
}
Here is the output from jgrasp:
----jGRASP exec: java LetterCounter
Enter a string: hello world
Enter a character: l
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 11
at java.lang.String.charAt(String.java:658)
at LetterCounter.main(LetterCounter.java:37)
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
I don't understand the errors. Any and all help is appreciated.

Looks like you're just iterating for too long:
for (int i = 0; i <= length; i++) {
...
}
should be
for (int i = 0; i < length; i++) {
...
}
I noticed that you wrote this line of code:
if (letter1 == letter2)
{
count++
}
I'd avoid using count++, you may end up getting mixed with ++count sometime. Sticking with the following is always good
if (letter1 == letter2) {
count + =1;
}

Error is occurring in the below line of code -
for (i = 0; i <= length; i++)
Here Iteration is longer than input length [exceeds the range].
The revised code will be -
for (i = 0; i < length; i++)
Need anything more? Shoot me a comment please.
Hopefully, it will work fine.

Related

Char array updating

I have been working on my hangman program for far to long and cannot figure out why it is not replacing the characters entered with the asterisks.
There are a lot of details I have not added so please do not sit here and judge that. I need someone to tell my why the character the user enters is not replacing the asterisks and If you know what I could do to fix it please tell me.
I'm struggling. I have edited my program to show you where I know the logic error is coming from however I do not know what the error is.
String hiddenWord = wordList[rand];
char[] asterisks = new char[MAXCHAR];
hideWord(hiddenWord);
System.out.println(Arrays.toString(hideWord(hiddenWord)));
numGuess( hiddenWord,asterisks);
public static char[] hideWord(String hiddenWord)
{
int wordLength = hiddenWord.length();
//int length = wordLength * 2;
char[] asterisks = new char[wordLength];
for(int i=0; i < wordLength; i++)
{
asterisks[i] = '*';
}
return asterisks;
}
public static void numGuess(String hiddenWord,char[] asterisks)
{
Scanner keyboard = new Scanner(System.in);
hideWord(hiddenWord);
int remAttempts = MAXGUESS;
int i = 0;
while(i < (hiddenWord.length()-1))
{
System.out.println("Enter a letter or 9 to quit");
char guess = keyboard.next().charAt(i);
if(asterisks[i] == (hiddenWord.charAt(i)))
{
//attemtps == hiddenWord.charAt(i);
System.out.println("Nice job!");
remAttempts--;
}
i++;
}
}
Look at this code (I changed the formatting a bit):
while (i < hiddenWord.length() - 1) {
System.out.println("Enter a letter or 9 to quit");
char guess = keyboard.next().charAt(i);
//...
i++;
}
You're asking for a letter, but you really request a String with at least the size + 1 that equals i: keyboard.next().charAt(i);. Therefore, if you write just a letter, then you'll get an Exception at the second iteration of that loop.
I guess what you meant was: keyboard.next().charAt(0);. This will return the first character of the given String.
If this doesn't solve the problem, then provide the whole Stacktrace and mark the line in your code, where the Exception occurs.

How do I get my value to print every time the loop increments in Java (For Loop)

I need to create a code that prints a pyramid like structure, given the user integer input which will be printed last. (I have attached an image of a final product below). I am new to programming, have been enjoying it, but am stuck in this problem.
My code can currently produce the user input 4 times. So I feel like I am close, just a little bit of tweaking will get the job done
I need my code to print out every single time that the loop increments instead of just displaying the user input a certain amount of times. I converted the integer to a string so that I can show the value x amount of times, but I feel that this is what is throwing me off. If I can somehow get the string to display the values at every incrementation then I will be golden. PLEASE HELP! Below is my code
import java.util.Scanner; //import scanner
public class NumberStack { // class
static Scanner myScanner; //declare scanner
public static void main(String[] args){ //add main method
myScanner= new Scanner (System.in); //scanner input declaration
int input= 0;
while (true) {
System.out.print("Enter an integer between 0 and 9 inclusive: ");
if (!myScanner.hasNextInt()) {
System.out.println("You have not entered an integer");
}
input= myScanner.nextInt();
if ( (input>=0) && (input<=9) ) {
String smln= Integer.toString(input);
String out="";
for (int p=0; p<input; p++) {
for (int j=0; j<input; j++) {
for (int i=0; i<((input*2)-1);i++) {
out += smln;
}
System.out.println(""+out);
out="";
smln= Integer.toString(input);
}
}
} //end of if statement
else {
System.out.println("You have not entered an integer within range");
}
} //end of while loop
} //end of main method
} //end of class
when you are facing problems like this one, you should try to look for a pattern...check this out
int input = 4;
for(int i = 1; i <= input; i++)
{
int times = i;
int length = 2 * i - 1;
String str = "";
for(int j = 0; j < length; j++)
{
str += i;
}
for(int k = 0; k < times; k++)
{
System.out.println(str);
}
}
Since your method is currently printing the data fro a particular number properly eg for input 4 it is printing
4444
4444
4444
4444
I would suggest that extract ur code for display into a separate function. And call that function using the number from a loop.
for(int i=1; i<=num;i++)
function_f1(i);
This should do the trick for you and since you are starting off with coding , it will also give you ideas on using methods.

out of bounds error with word count

I'm trying to write my own Java word count program. I know there may already be a method for this, but I'd like to get it work. I'm getting an out of bounds error at line 14. I'm trying to use an input word to count how many times it appears in an input string. So I'm looping up to stringlength - wordlength, but that's where the problem is.
Here is the code:
import java.util.Scanner;
public class wordcount {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print( "Enter word : " );
String word = s.nextLine();
Scanner t = new Scanner(System.in);
System.out.print("Enter string: ");
String string = t.nextLine();
int count = 0;
for (int i = 0; i < string.length()-word.length(); i = i+1){
String substring = string.substring(i,i+word.length());
if (match(substring, word)==true){
count += 1;
}
}
System.out.println("There are "+count+ " repetitions of the word "+word);
}
public static boolean match(String string1, String string2){
for (int i=0; i<string1.length(); i+=1){
if (string1.charAt(i)!=string2.charAt(i)){
return false;
}
}
return true;
}
}
First of all, two Scanners are not necessary, you can do many inputs with the same Scanner object.
Also, this if condition
if (match(substring, word) == true)
can be rewritten like
if (math(substring, word))
I would also recommend you to use i++ to increase the loop variable. Is not strictly necessary but is "almost" a convention. You can read more about that here.
Now, about theIndexOutOfBoundsException, I've tested the code and I don't find any input samples to get it.
Besides, there is an issue, you are missing one iteration in the for:
for (int i = 0; i < string.length() - word.length() + 1; i++) { // Add '+ 1'
String substring = string.substring(i, i + word.length());
// System.out.println(substring);
if (match(substring, word)) {
count++;
}
}
You can test it by putting a print statement inside the loop, to print each substring.
I'm not getting an out of bounds error, can you tell me what values you were using for word and string?
I have identified a bug with your program. If word is equal to string, it still returns count 0. I suggest adding one more iteration and using regionMatches instead. RegionMatches makes your match method obsolete and will return false if word.length() + i is equal or greater than string.length(), avoiding out of bounds issues.
As you can see I also moved the calculations to a seperate method, this will make your code more readable and testable.
And as Christian pointed out; you indeed do only need one Scanner object. I've adapted the code below to reflect it.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter word : ");
String word = sc.nextLine();
System.out.print("Enter string: ");
String string = sc.nextLine();
int count = calculateWordCount(word, string);
System.out.println("There are " + count + " repetitions of the word " + word);
}
private static int calculateWordCount(String word, String string) {
int count = 0;
for (int i = 0; i < string.length() - word.length() + 1; i++) {
if (word.regionMatches(0, string, i, word.length())) {
count++;
}
}
return count;
}

writes several line to standard out put in reverse order

I want to write a program in java that takes all the lines input to standard input and writes them to standard output in reverse order.
this is may code but it has an error and I can't understand where is the problem
(In this program at first I ask for the number of lines and then save it in 'n'.)
any help?
thanks in advance
package getLine;
import java.util.Scanner;
public class S {
public static void main(String[] args)
{
Scanner s= new Scanner(System.in);
System.out.println("how many lines do you want to enter");
int n= s.nextInt();
String [] str;
str= new String[n];
for(int i=0;i<n;i++)
str[i]=s.nextLine();
for(int i=n;i>=0;i--)
System.out.println(str[i]);
}
}
Why don't you use a Stack<String> to buffer the lines? Then simply pop every line and output it.
Following is the code with output:
import java.util.Scanner;
public class S {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("how many lines do you want to enter");
int n = s.nextInt();
System.out.println("I want to enter " + n + " lines ");
n = n + 1;
String[] str;
str = new String[n];
int count = 0;
for (int i = 0; i < n; i++) {
str[i] = s.nextLine();
System.out.println(str[i]);
count++;
}
if (count == n) {
System.out.println("Reversed output");
for (int i = n - 1; i >= 0; i--) {
System.out.println(str[i]);
}
}
}
Output:
how many lines do you want to enter
2
I want to enter 2 lines
1
1
2
2
Reversed output
2
1
for(int i=n-1;i>=0;i--)
System.out.println(str[i]);
Do you get ArrayIndexOutOfBoundsException? The error lies here:
for(int i=n;i>=0;i--)
System.out.println(str[i]);
In the first step of that loop you attempt to print str[n], which doesn't exist.
Your array consists of n elements numbered from 0 to n-1.
The proper code is:
for(int i = n - 1; i >= 0; i--)
System.out.println(str[i]);
You need to start from n-1 because the maximum index accessible in an array is array.length-1.
for(int i=n-1;i>=0;i--){
Also you need to make this change:-
int n= Integer.parseInt(s.nextLine());
s.nextInt() reads the next integer all right, but the enter you hit after that, is consumed as the first element of your array. To avoid that, you can do as I mentioned above.
You don't have to do much to handle this, just replace your line in a code by the following code-
int n = s.nextInt()+1;

JAVA - reading character with SCANNER

Here is the problem that I'm working on.
We have to ask the user to enter a string, and then enter a character (any character would be fine). And then count the number of times that character appears in the scanner.
I cannot figure out how to add character to scanner. We haven't done arrays yet so I don't wanna go there but this is what I have done so far:
import java.util.Scanner;
public class Counter {
public static void main (String args[]){
String a;
char b;
int count;
int i;
Scanner s = new Scanner (System.in);
System.out.println("Enter a string");
a = s.nextLine();
System.out.println("Enter a character");
b = s.next().charAt(0);
count = 0;
for (i = 0; i <= a.length(); i++){
if (b == s.next().charAt(b)){
count += 1;
System.out.println(" Number of times the character appears in the string is " + count);
else if{
System.out.println("The character appears 0 times in this string");
}
}
}
I know this is incorrect but I cannot figure this out right now.
Any help would be highly appreciated.
To verify your inputs [String, char] use a while loop for getting the character from the user. Basically you will check whether user enters a string of length 1 for character input.
Here is the compiling and running version of your code:
import java.util.Scanner;
public class Counter
{
public static void main ( String args[] )
{
String a = "", b = "";
Scanner s = new Scanner( System.in );
System.out.println( "Enter a string: " );
a = s.nextLine();
while ( b.length() != 1 )
{
System.out.println( "Enter a single character: " );
b = s.next();
}
int counter = 0;
for ( int i = 0; i < a.length(); i++ )
{
if ( b.equals(a.charAt( i ) +"") )
counter++;
}
System.out.println( "Number of occurrences: " + counter );
}
}
First, the for loop condition should be changed to :
for (i = 0; i < a.length(); i++)
The index starts from 0, but when you count length you start from 1. Therefore you don't need '='.
Second, in the for loop, you only need to do one thing: compare each character of a with b:
if (b == a.charAt(i))
count += 1;
Here, compared with the other solution, char is cheaper than String to be compared.
Third, after the for loop, output depends on count:
if (count > 0)
System.out.println(" Number of times the character appears in the string is "
+ count);
else // must be count == 0
System.out.println("The character appears 0 times in this string");

Categories

Resources