Counting a specific character in a file with Scanner - java

I'm trying to write a program that prompts the user to enter a character, and count the number of instances said character appears in a given file. And display the number of times the character appears.
I'm really at a loss, and I'm sorry I don't have much code yet, just don't know where to go from here.
import java.util.Scanner;
import java.io.*;
public class CharCount {
public static void main(String[] args) throws IOException {
int count = 0;
char character;
File file = new File("Characters.txt");
Scanner inputFile = new Scanner(file);
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a single character");
character = keyboard.nextLine().charAt(0);
}
}

You need the below code to read from the file and check it with the character you've entered. count will contain the occurrences of the specified character.
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) !=null) {
for(int i=0; i<line.length();i++){
if(line.charAt(i) == character){
count++;
}
}
}
} catch (FileNotFoundException e) {
// File not found
} catch (IOException e) {
// Couldn't read the file
}

Related

Read from File ASCII art Replace, Write to File

Trying to read text from ASCII art text file (it contains a series of blank spaces and '*' characters). Then, I want to be able to change the asterisks to whatever character the user wishes.
I also want to select a random file. All three files exist. I can store them as a list, if needed.
When executed, this code prompts user for substitution text but then just returns the file read location (including the random number 1-3).
import java.util.Scanner;
import java.util.Random;
import java.io.*;
public class AsciiArt
{
public static void main(String[]args) throws IOException
{
System.out.println("ASCII Art\n");
Scanner kbd = new Scanner(System.in);
Random randomGen = new Random();
int verSub = randomGen.nextInt(3)+1;
String fullSub = "/user/****/data/****"+verSub+".dat";
File inputFile = new File(fullSub);
System.out.print("Enter substitution text? ");
String subText = kbd.next();
Scanner input = new Scanner(fullSub);
PrintWriter outputFile = new PrintWriter("newFile.txt")
String line;
while(input.hasNext()){
line = input.nextLine();
int i, subIdx = 0;
for (i = 0; i < line.length(); i++){
if(line.charAt(i) == '*'){
outputFile.print(subText.charAt(subIdx));
++subIdx;
}
if(subIdx == subText.length()){
subIdx = 0;
}
else{
outputFile.print(line.charAt(i));
}
}
}
input.close();
outputFile.close();
System.out.println();
}
}

Printing each word from a paragraph of words in Java while skipping some using Scanner class

I am writing a program to take in a file and output a file.
The input file contains like:
1 cat dog rabbit
3 cat dog rabbit rabbit rabbit
2 yellow red blue white black
0 three two one
and the output file would be:
dog rabbit rabbit rabbit blue white black three two one
(the program takes in the integer at the beginning of each line and then skip the number of words in each line and then save the rest words and output them to a file)
Initially, I have
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.File;
import java.io.PrintWriter;
public class Scanner2{
public static void main(String args[]) {
String c = "";
try{
File file = new File(args[0]);
Scanner scanner = new Scanner(file);
PrintWriter writer = new PrintWriter(args[1]);
// as long as the scanner reads that the file has a next line
while (scanner.hasNextLine()) {
// read the next line of string as string s
String s = scanner.nextLine();
// split each word from the string s as an array called "words"
String[] words = s.split(" ");
// for loop executed length of "words" times
for(int x = 0; x < words.length; x++) {
// declare int, "count"
int count;
// parse the first element (the number) from "words" to be an integer, "count"
count = Integer.parseInt(words[0]);
// if the loop is executed more than "count" number of times
if (x > count){
// add respective element to string, "c"
c += words[x];
c += " ";
}
}
}
// close the scanner
scanner.close();
// output string "c" to the output file
writer.println(c);
// close the writer
writer.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
and these codes work perfectly.
However, now I want to switch from using the split method to another second scanner class to read each sentence to each word.
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.File;
import java.io.PrintWriter;
public class ScannerDemo{
public static void main(String args[]) {
String c = "";
try{
File file = new File(args[0]);
Scanner scanner = new Scanner(file);
PrintWriter writer = new PrintWriter(args[1]);
// as long as the scanner reads that the file has a next line
while (scanner.hasNextLine()) {
// read the first line of string in scanner s2
Scanner s2 = new Scanner(scanner.nextLine());
// read the first word of first line from s2 as string "counts"
String counts = s2.next();
// parse the string "counts" as int, "count"
int count = Integer.parseInt(counts);
// as long as s2 has the next element
while (s2.hasNext()){
// for loop executed "count" number of times to skip the words
for (int x = 0; x < count; x ++){
String b = s2.next();
}
// else add the next words to string, "c"
c += s2.next();
c += " ";
}
}
// close the scanner
scanner.close();
// output string "c" to the output file
writer.println(c);
// close the writer
writer.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
However, it gives out error message
Exception in thread "main" java.util.NoSuchElementException
I felt this error message is due to the second scanner class not closed properly. However, I did not figure out how to solve it after I added
s2.close();
in the for loop.
Any help is appreciated. Thank you but I am really new to Java,
There is a bug in the nested while and for loops that causes the s2.next() in the for loop to go of the end of the line. Try as follows
// parse the string "counts" as int, "count"
int count = Integer.parseInt(counts);
// for loop executed "count" number of times to skip the words
for (int x = 0; x < count && s2.hasNext(); x++){
String b = s2.next();
}
// as long as s2 has the next element add the next words to string
while (s2.hasNext()) {
c += s2.next();
c += " ";
}
Also, it is recommended to use try with resources instead of closing yourself. Simplified example :
try (Scanner scanner = new Scanner(file);
PrintWriter writer = new PrintWriter(args[1]);) {
scanner.next();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
This way the scanner and writer will be closed automatically even if an exception is thrown.
For example you can use a StringTokenizer instead of a second Scanner:
while(scanner.hasNextLine())
{
StringTokenizer tokenizer = new StringTokenizer(scanner.nextLine());
int count = Integer.parseInt(tokenizer.nextToken());
while(tokenizer.hasMoreTokens())
{
String b = tokenizer.nextToken() + " ";
if(count <= 0)
{
c += b;
}
count--;
}
}
scanner.close();
I think your problem with the second scanner was the inner loop and the scanner position - you want to advance it the number of words it has and only add some to your output string.

I need help reading a user-specified text file into an ArrayList of Strings using Java?

I am advised to use a while loop the Scanner method hasNextLine() and
in the while loop body, call the Scanner method nextLine(), and add the returned String to the ArrayList of Strings. I am new to Java so please keep that in mind. I'm not exactly sure if this is right, but this is what I have gotten so far:
Scanner input = new Scanner(new File(""));
while(input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
With this code you can:
prompt a user for a file name.
read the file line by line using the Scanner class.
add each line to an ArrayList of Strings.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ScannerReadFile {
public static void main(String[] args) {
// Location of file to read
Scanner x = new Scanner(System.in);
System.out.println("Enter a filename: ");
String fileName = x.nextLine();
File file = new File(fileName);
ArrayList<String> lines = new ArrayList<String>();
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lines.add(line);
System.out.println(line);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

Add a paragraph in File

I would like to write a paragraph using file.
This is my code(my effort).
import java.io.*;
import java.util.Scanner;
public class Test {
public static void main (String [] args)
{
Scanner input = new Scanner(System.in);
try {
BufferedWriter out = new BufferedWriter(new FileWriter("C:/Users/Akram/Documents/akram.txt")) ;
System.out.println("Write the Text in the File ");
String str = input.nextLine();
out.write(str);
out.close();
System.out.println("File created successfuly");
} catch (IOException e) {
e.printStackTrace();
}
}
}
With this code I can add just one word but I want to add a lot of word (paragraph).
I would use a while loop around Scanner#hasNextLine(). I would also recommend a PrintWriter. So, all together, that would look something like,
Scanner input = new Scanner(System.in);
PrintWriter out = null;
try {
out = new PrintWriter(new FileWriter(
"C:/Users/Akram/Documents/akram.txt"));
System.out.println("Write the Text in the File ");
while (input.hasNextLine()) {
String str = input.nextLine();
out.println(str);
}
System.out.println("File created successfuly");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
In order to write a paragraph, Decide a terminating character or string,Write your code so that it takes the input till that character or string is given in the input, Do some operation to remove the character in the file,
The code which I used is given below,Terminating Character is +
I haven't kept try and catch statements to reduce complexity in understanding
pw = new PrintWriter(new FileWriter("E://files//myfile.txt"));
System.out.println("Write the Text in the File,End the text with + ");
do
{
Scanner sc =new Scanner(System.in);
String S=sc.nextLine();
if(S.endsWith("+"))
{
S= S.replace("+"," ");
flag=1;
pw.println(S);
}
else
pw.println(S);
}while(flag!=1);
Cheers

Java simple counting words in a file

I am creating a simple program that counts the number of words, lines and total characters (not including whitespace) in a paper. It is a very simple program. My file compiles but when I run it I get this error:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1347)
at WordCount.wordCounter(WordCount.java:30)
at WordCount.main(WordCount.java:16)
Does anyone know why this is happening?
import java.util.*;
import java.io.*;
public class WordCount {
//throws the exception
public static void main(String[] args) throws FileNotFoundException {
//calls on each counter method and prints each one
System.out.println("Number of Words: " + wordCounter());
System.out.println("Number of Lines: " + lineCounter());
System.out.println("Number of Characters: " + charCounter());
}
//static method that counts words in the text file
public static int wordCounter() throws FileNotFoundException {
//inputs the text file
Scanner input = new Scanner(new File("words.txt"));
int countWords = 0;
//while there are more lines
while (input.hasNextLine()) {
//goes to each next word
String word = input.next();
//counts each word
countWords++;
}
return countWords;
}
//static method that counts lines in the text file
public static int lineCounter() throws FileNotFoundException {
//inputs the text file
Scanner input2 = new Scanner(new File("words.txt"));
int countLines = 0;
//while there are more lines
while (input2.hasNextLine()) {
//casts each line as a string
String line = input2.nextLine();
//counts each line
countLines++;
}
return countLines;
}
//static method that counts characters in the text file
public static int charCounter() throws FileNotFoundException {
//inputs the text file
Scanner input3 = new Scanner(new File("words.txt"));
int countChar = 0;
int character = 0;
//while there are more lines
while(input3.hasNextLine()) {
//casts each line as a string
String line = input3.nextLine();
//goes through each character of the line
for(int i=0; i < line.length(); i++){
character = line.charAt(i);
//if character is not a space (gets rid of whitespace)
if (character != 32){
//counts each character
countChar++;
}
}
}
return countChar;
}
}
I can't really say the exact reason for the problem without looking at the file (Maybe even not then).
while (input.hasNextLine()) {
//goes to each next word
String word = input.next();
//counts each word
countWords++;
}
Is your problem. If you are using the input.hasNextLine() in the while conditional statement use input.nextLine(). Since you are using input.next() you should use input.hasNext() in the while loops conditional statement.
public static int wordCounter() throws FileNotFoundException
{
Scanner input = new Scanner(new File("words.txt"));
int countWords = 0;
while (input.hasNextLine()) {
if(input.hasNext()) {
String word = input.next();
countWords++;
}
}
return countWords;
}
I have just added an if condition within the while loop. Just make sure to check there are token to be parsed. I have changed only in this place. Just make sure to change wherever needed.
This link will give good info. in regard to that.
Hope it was helpful. :)

Categories