counting character occurrence in input file - java

My program prompts the user to enter a specific letter and filename and then prints out the number of occurrences of the parameter letter in the input file.
Code I wrote:
public class CharCount {
public static void main(String[] args) {
Scanner inp= new Scanner(System.in);
String str;
char ch;
int count=0;
System.out.println("Enter a letter: ");
str=inp.nextLine();
while(str.length()>0)
{
ch=str.charAt(0);
int i=0;
while (i < str.length() && str.charAt(i) == ch)
{
count++;
i++;
}
str = str.substring(count);
System.out.println(ch + " appears " + count + " in" );
}
}
}
I get this output
Enter a letter:
e appears 1 in
But I should be getting this output
Enter a letter: Enter a filename: e appears 58 times in input.txt
Any help/advice would be great :)

With Java 8, you can rely on streams to do the work for you.
String sampleText = "Lorem ipsum";
Character letter = 'e';
long count = sampleText.chars().filter(c -> c == letter).count();
System.out.println(count);

Let's give a start help:
// Ask letter:
System.out.println("Enter a letter: ");
String str = inp.nextLine();
while (str.isEmpty()) {
System.out.println("Enter a letter:");
str = inp.nextLine();
}
char letter = str.charAt(0);
// Ask file name:
System.out.println("Enter file name:");
String fileName = inp.nextLine();
while (fileName.isEmpty()) {
System.out.println("Enter file name:");
fileName = tnp.nextLine();
}
// Process file:
//Scanner textInp = new Scanner(new File(fileName)); // Either old style
Scanner textInp = new Scanner(Paths.get(fileName)); // Or new style
while (textInp.hasNextLine()) {
String line = textInp.nextLine();
...
}

You could use regex.
Imports:
import java.util.regex.*;
Ex Usage:
String input = "abcaa a";
String letter = "a";
Pattern p = Pattern.compile(letter, Pattern.CASE_INSENSITIVE + Pattern.MULTILINE);
Matcher m = p.matcher(input);
int i = 0;
while(m.find()){
i++;
}
System.out.println(i); // 4 = # of occurrences of "a".

Related

How to resolve the following program with a for loop into producing an appropriate output?

The following Java program is supposed to manipulate a string input by the user in such a way that the user will decide which character needs to be replaced with another and just the last character from the string should be replaced. Example if the user enters the string "OYOVESTER" and decides to replace "O" with "L", the program should output the following result: "OYLVESTER" (notice that only the last "O" was replaced with "L")
NOTE: YOU CANNOT USE BREAK COMMAND TO STOP THE LOOP. IT IS PROHIBITED.
import java.util.Scanner;
public class StringFun {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
String inString = keyboard.nextLine();
String outString = "";
//Replace Last
System.out.println("Enter the character to replace");
char oldCharF = keyboard.next().charAt(0);
System.out.println("Enter the new character");
char newCharF = keyboard.next().charAt(0);
int count = 0; // variable that tracks number of letter occurrences
for(int index = inString.length() - 1;index >= 0;index--) {
if(inString.charAt(index) == oldCharF && count < 1){
outString = newCharF + outString;
outString = outString + inString.substring(0,index);
count++;
}
if (count < 1) {
outString = outString + inString.charAt(index);
}
}
System.out.print("The new sentence is: "+outString);
}
}
I keep getting the following output which is incorrect:
Enter the string to be manipulated
OYOVESTER
Enter the character to replace
O
Enter the new character
L
The new sentence is: LRETSEVOY
There are many simpler ways to achieve your requirement but I hope you have to demonstrate this with loops (without breaks)
Then you can use some thing like this :
boolean skip = false;
for (int index = inString.length() - 1; index >= 0; index--) {
if (!skip && inString.charAt(index) == oldCharF) {
outString = newCharF + outString;
skip = true;
}
else {
outString = inString.charAt(index) + outString;
}
}
PS : Using String concatenation inside loops is not recommended since
every String concatenation copies the whole String, usually it is preferable to
replace it with explicit calls to StringBuilder.append() or StringBuffer.append()
No break command seems like a weird condition. You could just a boolean value, and other methods, to break the loop when you need. Why not do something like this?
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
String word = keyboard.nextLine();
//Replace Last
System.out.println("Enter the character to replace");
char oldCharF = keyboard.next().charAt(0);
System.out.println("Enter the new character");
char newCharF = keyboard.next().charAt(0);
int index = word.lastIndexOf(oldCharF);
if(index > 1){
word = word.substring(0,index) + newCharF + word.substring(index+1);
}
System.out.println("The new sentence is: " + word);
}

to print all the words in a string which starts and ends with same letter in java

*
import java.util.*;
class Word{
void main(){
char ch='\u0000',firstc,lastc;
int c=0,lw; String w="",s1="";
Scanner in = new Scanner(System.in);
System.out.println("Enter a String");
String n = in.nextLine();n=n+"";
for (int i=0;i<n.length();i++){
ch = n.charAt(i);
if(ch!=' '){
w=w+ch;
}else{
firstc = w.charAt(0);
lastc = w.charAt(w.length()-1);
if(firstc==(lastc))
s1=s1+w;
System.out.println(""+s1);
}
}
w=" ";
}
}
*
Now the output comes for one string like if I give MADAM HAVE A MODEM as input it only gives me MADAM as output.
You have to split your "in" string by spaces " ".
After that, if both characters at the start and at the end.
Notice String.charAt() method will get characters from position 0 (start) to the string lenght - 1.
Scanner in = new Scanner(System.in);
System.out.println("Enter a String");
String n = in.nextLine();
String[] parts = n.split(" ");
for(String part : parts) {
if(part.charAt(0)==part.charAt(part.length()-1)) {
System.out.println(part);
}
}
Your code is overly complicated. It would be much simpler to either split the string on space or just read one word at a time:
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
// Get next word
String s = in.next();
if (Character.toLowerCase(s.charAt(0)) == Character.toLowerCase(s.charAt(s.length() - 1))) {
System.out.println(s);
}
}
But back to your code, I see these issues.
It will always skip the last word
You reset w outside of the for and it should be w = "";
Your indentation is really bad
Your code fixed (well, at least working):
char firstc, lastc;
String w = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a String");
String n = in.nextLine();
for (int i = 0; i < n.length(); i++) {
ch = n.charAt(i);
if (ch != ' '){
w = w + ch;
}
if (ch == ' ' || i == n.length()-1) {
firstc = w.charAt(0);
lastc = w.charAt(w.length()-1);
if (firstc == lastc) {
System.out.println(w);
}
w="";
}
}

java program to count the number of words that starts with capital letters

I want to write a program that count the number of words that starts with capital letters. It only count no. Of capital letter not word try this line
"Hi hOw are yOu"
According to my code output will be 3
But their is only 1 word that starts with capital letter that is 'Hi'...so how can I solve these problem..Please help me with this.
import java.util.*;
class Cap
{
public static void main(String m[])
{
Scanner in=new Scanner(System.in);
String s=new String();
System.out.println("Enter a line:");
s=in.nextLine();
char c;
int ct=0;
for(int i=0;i<s.length();i++)
{
c=s.charAt(i);
if(c>=65 && c<=90)
{
ct++;
}
}
System.out.println("total number of words start with capital letters are :"+ct);
}
}
You should better use scanner.next();, which returns the token up to white space in other way a word.Now, you can check the first character of String returned by next() is in uppercase or not.
For statement This is StackOverflow you will have three tokens, This, is and StackOverflow and you can use String.charAt(0) on this String.
Moreover, you can simply use Character.isUpperCase method to check whether character is in upper case or not.
import java.util.*;
public class program_6
{
public static void main(String[] args)
{
String s1;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the string... ");
s1 = scan.nextLine();
int count=0,i=0,n;
n = s1.length();
System.out.println("Size of the string is... " + n );
if ( null == s1 || s1.isEmpty())
{
System.out.println("Text empty");
}
else
{
if( Character.isUpperCase(s1.charAt(0) ))
{
count++;
}
for (i=1 ; i<n ; i++)
{
if ( Character.isWhitespace(s1.charAt(i-1)) && Character.isUpperCase(s1.charAt(i) ) )
{
count++;
}
}
}
System.out.println("Number of the word wich starts with capital latter... " + count );
}
}
Currently you are counting all the capital letters that are entered.
What you want to do is split the line on space and check only for the first letter if it is capital.
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
String s;
System.out.println("Enter a line:");
s=in.nextLine();
int ct=0;
for(String str: s.split(" ")) {
if(str.charAt(0)>=65 && str.charAt(0)<=90)
{
ct++;
}
}
System.out.println("total number of words start with capital letters are :"+ct);
}
You are comparing each character.Instead you can add a space at the begining of the string and check each character after space if it is in uppercase.
Scanner in = new Scanner(System. in );
String s = new String();
System.out.println("Enter a line:");
s = " " + in .nextLine().trim();
char c;
int ct = 0;
for (int i = 1; i < s.length(); i++) {
c = s.charAt(i);
if (c >= 65 && c <= 90 && s.charAt(i - 1) == 32) {
ct++;
}
}
System.out.println("total number of words start with capital letters are :" + ct);
DEMO
or better use scanner.next() as said by TAsk
Try this:
Scanner in = new Scanner(System.in);
String s = new String();
System.out.println("Enter a line:");
s = in.nextLine();
char c;
int ct = 0;
for (int i = 0; i < s.length(); i++) {
c = s.charAt(i);
if (Character.isUpperCase(c)
&& (i == 0 || Character.isWhitespace(s.charAt(i - 1)))) {
ct++;
}
}
System.out
.println("total number of words start with capital letters are :"
+ ct);
First of all we check on the first position whether it is starts with capital letter or not and it is only for the string which starts with capital letter... If yes then the count will be incremented. Next condition( Which is used for string which start with blank space or any other string) will check that left position must have blank space to start new word and the character must be capital to increment the count variable...
import java.util.*;
public class program_6
{
public static void main(String[] args)
{
String s1;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the string... ");
s1 = scan.nextLine();
int count=0,i=0,n;
n = s1.length();
System.out.println("Size of the string is... " + n );
if ( null == s1 || s1.isEmpty())
{
System.out.println("Text empty");
}
else
{
if( Character.isUpperCase(s1.charAt(0) ))
{
count++;
}
for (i=1 ; i<n ; i++)
{
if ( Character.isWhitespace(s1.charAt(i-1)) && Character.isUpperCase(s1.charAt(i) ) )
{
count++;
}
}
}
System.out.println("Number of the word wich starts with capital letter... " + count );
}
}

Replacing a char value in a string (Java)

In my assignment I need to get this output:
Enter a word: house
What letter do you want to replace?: e
With what letter do you wish to replace it? w
The new word is housw.
_____________________________________________.
I got the program to work with this code, but now I need to set while loops. Here is my current code.
String word = "";
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a word: " + word);
word = keyboard.nextLine();
String readChar = null;
System.out.print("What letter do you want to replace?: ");
readChar = keyboard.next();
String changeChar;
System.out.print("With what letter do you wish to replace it? ");
changeChar = keyboard.next();
keyboard.close();
System.out.println(word.replaceAll(readChar, changeChar));
System.out.println();
I need to now make my program output this:
Enter a word: house
What letter do you want to replace?: a
There is no a in house.
What letter do you want to replace?: b
There is no a in house.
What letter do you want to replace?: e
With what letter do you wish to replace it? w
The new word is housw.
How would my while loop look to portray this output?
After you read the word and the character you want to replace (plus the character you want to replace it with) you can use replace method from the String class.
Here is an example usage (adapt the variable names to your code)
word = word.replace(letterToReplace, replacementLetter);
So for example
String word = "aba";
word = word.replace('a', 'c');
System.out.println(word); // Prints out 'cbc'
Also here is an obligatory link to the JavaDoc for the replace method:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace%28char,%20char%29
Okay this is one possible way to implement the edited second part of the question:
public static void main(String[] args) {
String word = "";
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a word: " + word);
word = keyboard.nextLine();
boolean done = false;
do{
String readChar = null;
System.out.print("What letter do you want to replace?: ");
readChar = keyboard.next();
if(word.contains(readChar)){
String changeChar;
System.out.print("With what letter do you wish to replace it? ");
changeChar = keyboard.next();
done = true;
keyboard.close();
System.out.println(word.replace(readChar, changeChar));
}
}
while(!done);
}
I hope you don't mind hard interpretation,Below is the example you can follow the same.
String a = "HelloBrother How are you!";
String r = a.replace("HelloBrother","Brother");
print.i(r);
If you want to replace all of the letters, you can do it like this (working code):
public static void main(String[] args) {
String word = "";
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a word: " + word);
word = keyboard.nextLine();
String readChar = null;
System.out.print("What letter do you want to replace?: ");
readChar = keyboard.next();
String changeChar;
System.out.print("With what letter do you wish to replace it? ");
changeChar = keyboard.next();
keyboard.close();
System.out.println(word.replace(readChar, changeChar));
}
This illustrates what you need to do.
import java.util.Scanner;
public class WordScrambler{
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a word: ");
String word = keyboard.nextLine();
System.out.print("What letter do you want to replace?: ");
char letter = keyboard.next().charAt(0);
StringBuffer out = new StringBuffer(word);
System.out.print("With what letter do you wish to replace it? ");
char changeChar = keyboard.next().charAt(0);
for (int i=0; i<word.length(); ++i)
if(word.charAt(i) == changeChar)
out.setCharAt(i, changeChar);
System.out.println("The new word is "+out);
}
}

Concatenate User Input JAVA

This is what I have so far. I want the program to print out the words the user inputs as a sentence. But
I don't know how I get that to happen with the code I have written so far.
ex: if you entered
Hello
World
done
The program should say: "Hello World"
import java.util.Scanner;
public class Chapter3ProblemsSet {
public static void main(String [] args) {
String word = "";
final String SENTINEL = "done";
double count = 0;
String userInput = "";
Scanner in = new Scanner (System.in);
System.out.println("Please enter words: ");
System.out.println("Enter done to finish.");
word = in.next();
do {
word = in.next();
count++;
System.out.print(" "+word);
}
while (!word.equals(SENTINEL));
System.out.println(" "+word);
}
}
What you need it to store it in a variable which is declared outside the loop.
StringBuilder sentence=new StringBuilder();
do {
word = in.nextLine();
count++;
System.out.print(" "+word);
sentence.append(" "+word);
}
while (!word.equals(SENTINEL));
Then for printing use
System.out.println(sentence.toString());
You will need to create an additional string to "collect" all of the words that the user enters. The problem with your original is that you replace 'word' with the word entered. This should do the trick:
import java.util.Scanner;
public class Chapter3ProblemsSet {
public static void main(String [] args) {
String word = "";
String sentence = "";
final String SENTINEL = "done";
double count = 0;
String userInput = "";
Scanner in = new Scanner (System.in);
System.out.println("Please enter words: ");
System.out.println("Enter done to finish.");
word = in.next();
do {
word = in.next();
count++;
sentence += " " + word;
System.out.print(" "+word);
}
while (!word.equals(SENTINEL));
System.out.println(" "+sentence);
}
}
You can read it by pieces and put them together using a StringBuffer - http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html
StringBuffer sb = new StringBuffer();
do {
sb.append( in.next() );
count++;
}
while (!word.equals(SENTINEL));

Categories

Resources