Reputation: 53
Just have a question. I have a practice lab assignment for my class and I am trying to get the number of occurrences of letter "a" from a user input. If I type: "apples apples apples" the output would print the user string as desired, but at the end instead of giving me a number 3, it gives 123... I want the output: "apples apples apples3" not "apples apples apples123" thanks in advance for help.
Here is my code:
import java.util.Scanner;
public class labnextLine {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String input;
int count = 0;
System.out.print("Enter a string:");
input = in.nextLine();
System.out.print(input);
for (int i = 0; i < input.length(); i++) {
if(input.charAt(i) == 'a') {
count = count + 1;
System.out.print(count);
}
}
}
}
Upvotes: 1
Views: 751
Reputation: 23
It appears that your System.out.print(count);
is in the for loop, thus leading the program to output the count every single iteration.
Below is the correct code.
You can see how we moved System.out.print(count);
outside, just below, the for loop.
import java.util.Scanner;
public class labnextLine {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String input;
int count = 0;
System.out.print("Enter a string:");
input = in.nextLine();
System.out.print(input);
for (int i = 0; i < input.length(); i++) {
if(input.charAt(i) == 'a') {
count = count + 1;
}
}
System.out.print(count);
}
}
Upvotes: 2
Reputation: 40034
You've been given several good answers. And the key point was moving the print statement out of the loop.
Here is another way of counting a particular letter.
[^a]
says match any character other than an a
.replaceAll(arg1, arg2)
- replace all occurrences of the matching expression in string arg1
with with string arg2
.
System.out.print("Enter a string:");
input = in.nextLine();
System.out.print(input);
// effectively remove all but the letter a from the string and get the
// resulting length.
int count = input.replaceAll("[^a]","").length();
System.out.println(count);
For apples apples apples
this prints
3
Upvotes: 1
Reputation: 593
For this you'll just want to print your count
outside of the loop, that'll give your desired output.
Another method you may want to try, if using Java 8:
long count = input.chars().filter(ch -> ch == 'a').count();
System.out.print(count);
Upvotes: 3
Reputation: 79015
Move System.out.print(count);
out of the loop as shown below:
for (int i = 0; i < input.length(); i++) {
if(input.charAt(i) == 'a') {
count = count + 1;
}
}
System.out.print(count);
Since you have put it inside the loop, it gets executed with each iteration of the loop. When you move it after the loop body, it will be invoked only once after the loop is finished.
Upvotes: 1