I am writing a program thats supposed to read a simple text file and output a list of all the letters in that .txt file, ordered with the most frequently used letter to the least frequently used letter.
I have finished coding a working Java program that asks for file name and outputs the text within the file. But I am unsure how to go about outputting a list of the letters. What I am not sure specifically is what methods(if any) within the reader class I could use that reads in each letter in the .txt file. Any help would be appreciated!
This is current code:
// Here I import the Bufered Reader and file reader Libraries
// The Buffered Reader library is similar to Scanner Library and
// is used here to read from a text file. File reader will allow
// the program to access windows file system, get the text file
// and allow the Buufered Reader to read it in.
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;
public class TextFileReaderApp
{
// I added "throws exception" in case there is an an error in the
// main method, throw an exception, so it can prevent further
// errors from occuring if java doesnt know the main methods going
// to throw an error.
public static void main(String[] args) throws Exception
{
// below I diplay a welcome messgae to the user
System.out.println();
System.out.println("Welcome to the Text File Reader application!");
System.out.println();
// Below I create an instance of the Scanner class to get
// input from the user.
Scanner userInput = new Scanner(System.in);
String selection = "y"; //this is the string variable that's used in
//the while loop to continue the program.
// Below I created a while loop that continues the program if the user
// keeps selecting y as their selecion
while (selection.equalsIgnoreCase("y"))
{
// this line of code is supposed to ask the user for text file name under
// the C:/ directory and must not be hidden in any foler.
System.out.print("Please enter the name of the .txt file: C/");
FileReader file = new FileReader("C:/" + userInput.next());
// file object is used as a parameter in buffered reader.
BufferedReader textReader = new BufferedReader(file);
// below I create and initialize an object of type string called text that will
// store whats inside of the text file.
String text = "";
// I use the readLine statement to read line after line of the text.
// Once it has read everything it will return null.
String lineText = textReader.readLine();
// code below is a test for me to see if the code above works and is able to read
// the text inside the file and output it.
while(lineText != null)
{
// this reads the text line for line and ads it to the text variable for output.
text = text + lineText + "\n";
lineText = textReader.readLine();
}
System.out.println(text);
}
// These 3 code lines ask the user if he/she would like to continue with the program.
System.out.println();
System.out.print("Continue using the Text File Reader? (y/n): ");
choice = user_input.next();
System.out.println();
}
}
If you need to count letters / characters you can do it just as well on lines / words etc. No need to involve the Reader here.
for (char c : someString.toCharArray ()) {
// handle the character
}
Should work once you have any String from your file.
This reads all characters from textReader until EOF is reached or an exception occurs.
try {
for(int i = textReader.read(); i != -1 /* EOF */; i = textReader.read()) {
char c = (char) i;
// do whatever you want with your char here
}
} catch(IOException)
textReader.close();
first of all you might want to use a StringBuilder instead of your String text because of alot better performance.
"text = text + lineText" will create another String object every time it is executed, StringBuilder works better in this case).
One way to achieve what you want is to read character for character of your textLine and use a switchcase block with all letters and add them to an array containing integers when they occur. Example:
int[] array = new int[26];
switch(character){
case "a":
array[0] += 1;
break;
case "b":
array[1] += 1;
break;
//....
}
and so on...
in the end you use a simple for loop and print the values of your array. Now you see how many times you have entered which character.
Related
I have a probem, and I didnt find any solution yet. Following Problem: I have to read a CSV File which has to look like this:
First Name,Second Name,Age,
Lucas,Miller,17,
Bob,Jefferson,55,
Andrew,Washington,31,
The assignment is to read this CSV File with JAVA and display it like this:
First Name: Lucas
Second Name: Miller
Age: 17
The Attribut Names are not always the same, so it also could be:
Street,Number,Postal Code,ID,
Schoolstreet,93,20000,364236492,
("," has to be replaced with ";")
Also the file Adress is not always the same.
I already have the view etc. I only need the MODEL.
Thanks for your help. :))
I already have a FileChooser class in Controller, which returns an URI.
If your CSV file(s) always contains a Header Line which indicates the Table Column Names then it's just a matter of catching this line and splitting it so as to place those column names into a String Array (or collection, or whatever). The length of this array determines the amount of data expected to be available for each record data line. Once you have the Column Names it's gets relatively easy from there.
How you acquire your CSV file path and it's format type is obviously up to you but here is a general concept how to carry out the task at hand:
public static void readCsvToConsole(String csvFilePath, String csvDelimiter) {
String line; // To hold each valid data line.
String[] columnNames = new String[0]; // To hold Header names.
int dataLineCount = 0; // Count the file lines.
StringBuilder sb = new StringBuilder(); // Used to build the output String.
String ls = System.lineSeparator(); // Use System Line Seperator for output.
// 'Try With Resources' to auto-close the reader
try (BufferedReader br = new BufferedReader(new FileReader(csvFilePath))) {
while ((line = br.readLine()) != null) {
// Skip Blank Lines (if any).
if (line.trim().equals("")) {
continue;
}
dataLineCount++;
// Deal with the Header Line. Line 1 in most CSV files is the Header Line.
if (dataLineCount == 1) {
/* The Regular Expression used in the String#split()
method handles any delimiter/spacing situation.*/
columnNames = line.split("\\s{0,}" + csvDelimiter + "\\s{0,}");
continue; // Don't process this line anymore. Continue loop.
}
// Split the file data line into its respective columnar slot.
String[] lineParts = line.split("\\s{0,}" + csvDelimiter + "\\s{0,}");
/* Iterate through the Column Names and buld a String
using the column names and its' respective data along
with a line break after each Column/Data line. */
for (int i = 0; i < columnNames.length; i++) {
sb.append(columnNames[i]).append(": ").append(lineParts[i]).append(ls);
}
// Display the data record in Console.
System.out.println(sb.toString());
/* Clear the StringBuilder object to prepare for
a new string creation. */
sb.delete(0, sb.capacity());
}
}
// Trap these Exceptions
catch (FileNotFoundException ex) {
System.err.println(ex.getMessage());
}
catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
With this method you can have 1 to thousands of columns, it doesn't matter (not that you would ever have thousands of data columns in any given record but hey....you never know... lol). And to use this method:
// Read CSV To Console Window.
readCsvToConsole("test.csv", ",");
Here is some code that I recently worked on for an interview that might help: https://github.com/KemarCodes/ms3_csv/blob/master/src/main/java/CSVProcess.java
If you always have 3 attributes, I would read the first line of the csv and set values in an object that has three fields: attribute1, attribute2, and attribute3. I would create another class to hold the three values and read all the lines after, creating a new instance each time and reading them in an array list. To print I would just print the values in the attribute class each time alongside each set of values.
I've been creating a game in Java for a while and I used to write all the in-game texts directly in my code like this:
String text001 = "You're in the castle.\n\nWhere do you go next?"
But recently I decided to write all the in-game texts in a text file and tried to let the program read them and put them into a String array since the amount of the texts has increased a lot and it made my code incredibly long. The reading went well except one thing. I've inserted line break codes in dialogues and although the code worked properly when I wrote it directly in my code, they are no longer recognized as line break code when I try to read them from a text file.
It is supposed to be displayed as:
You're in the castle.
Where do you go next?
But now it is displayed as:
You're in the castle.\n\nWhere do you go next?
The code doesn't recognize "\n" as line break code any more.
Here's the code :
import java.io.File;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
Scanner sc;
StringTokenizer token;
String line;
int lineNumber = 1;
String id[] = new String[100];
String text[] = new String[100];
try {
sc = new Scanner(new File("sample.txt"));
while ((line = sc.nextLine()) != null) {
token = new StringTokenizer(line, "|");
while (token.hasMoreTokens()) {
id[lineNumber] = token.nextToken();
text[lineNumber] = token.nextToken();
lineNumber++;
}
}
} catch (Exception e) {
}
System.out.println(text[1]);
String text001 = "You're in the castle.\n\nWhere do you go next?";
System.out.println(text001);
}
}
And this is the content of the text file:
castle|You're in the castle.\n\nWhere do you go next?
inn|You're in the inn. \n\nWhere do you go next?
I would be grateful if anyone tells me how to fix this. Thank you.
Just use
text[lineNumber] = token.nextToken().replace("\\n", "\n");
There is nothing inherently special about \n in a text file. It is just a \, followed by a \n.
It is only in Java (or other languages) which define that this sequence of characters - in a char or string literal - should be interpreted as a 0x0a (ASCII newline) character.
So, you can replace the character sequence with the one you want it to be interpreted as.
I'm trying to implement a Huffman algorithm that takes in characters from a .txt file. The txt file contains a paragraph of text. Right now when I run the program like so
java HuffmanCode large.txt
it produces output, but what it evaluated was the name of the file, "large.txt", rather than the text inside the file large.txt. How do I get it to read the contents instead?? Thanks for your help.
public static void main(String[] args) throws IOException {
String inputFileName = args[0];
FileReader reader = new FileReader(inputFileName);
Scanner in = new Scanner(reader);
int[] charFreqs = new int[256];
// read each character and record the frequencies
for (char c : inputFileName.toCharArray())
charFreqs[c]++;
// build tree
HuffmanTree tree = buildTree(charFreqs);
// print out results
System.out.println("SYMBOL\tWEIGHT\tHUFFMAN CODE");
printCodes(tree, new StringBuffer());
}
}
You were really close - you're just iterating over inputFileName.toCharArray(), which is giving you the characters in the file name. You need to read characters from your in variable (which will give you the file contents) instead, eg:
while (in.hasNextLine())
{
char[] line = in.nextLine().toCharArray();
for (char c : line)
charFreqs[c]++;
}
Note this will probably discard any newline characters in the file, so if you want to count them you'll probably have to do it manually. Or switch to reading raw char[]s from the FileReader you already have, which is probably a better approach than above (you want raw character data, not "text" data, which is what Scanner operates on).
I'm currently attempting to write a program that can scan a text document and replace a specified word / string / whatever with another phrase, specifically using the classes Scanner and Printwriter. Unfortunately, I'm having a little bit of trouble finding the correct methods to use and how exactly to implement them. Here's my code:
class Redaction {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
System.out
.println("Please enter the filename of the sensitive information");
String f = input.next();
System.out.println("Please input what text you want 'lost'");
String o = input.next();
System.out
.println("Please input what you want the new, improved filename to be called");
String n = input.next();
File sensitiveDocument = new File(f);
if (!sensitiveDocument.exists()) {
System.out.println("File does not exist.");
System.exit(0);
}
Scanner in = new Scanner(sensitiveDocument);
in.useDelimiter("[^A-Za-z]+");
PrintWriter out = new PrintWriter(n);
while (in.hasNext()) {
if (in.hasNext(o)) {
// ...
}
}
in.close();
out.close();
}
}
I'm pretty lost at this point. Any help would be much appreciated.
Start by reading PrintWriter and Scanner documentation, to decide which methods to use.
Pseodo code:
Get line by line (or word by word, depends on what you want to remove).
look for the string you want to remove
if the string contains the content to remove, remove it.
print the string to the file.
The simplest although not so efficient algorithm would be to read the contents of the file into a string variable. After which you could use a String Tokenizer to find and replace the word you don't want with the word you want and rewriting the contents of the variable back into the file.
I'm currently writing this program that I require to read info from a text file and to then compare the info read to a user input and output a message saying if it was a match or not.
Currently have this. The program is sucessfully reading the data specified but I can't seem to compare the strings correctly at the end and print a result.
Code is below any help would be greatly appreciated.
import java.util.Scanner; // Required for the scanner
import java.io.File; // Needed for File and IOException
import java.io.FileNotFoundException; //Required for exception throw
// add more imports as needed
/**
* A starter to the country data problem.
*
* #author phi
* #version starter
*/
public class Capitals
{
public static void main(String[] args) throws FileNotFoundException // Throws Clause Added
{
// ask the user for the search string
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter part of the country name: ");
String searchString = keyboard.next().toLowerCase();
// open the data file
File file = new File("CountryData.csv");
// create a scanner from the file
Scanner inputFile = new Scanner (file);
// set up the scanner to use "," as the delimiter
inputFile.useDelimiter("[\\r,]");
// While there is another line to read.
while(inputFile.hasNext())
{
// read the 3 parts of the line
String country = inputFile.next(); //Read country
String capital = inputFile.next(); //Read capital
String population = inputFile.next(); //Read Population
//Check if user input is a match and if true print out info.
if(searchString.equals(country))
{
System.out.println("Yay!");
}
else
{
System.out.println("Fail!");
}
}
// be polite and close the file
inputFile.close();
}
}
You should try reading the input from a textField in an user interface(visible window) where the user puts the country and getting that as raw input shortens the code.(Only if you have a visible window on screen)
I don't have that good experience with scanners, because they tend to crash my applications when I use them. But my code for the same test does only include a scanner for the file which does not crash my application and looks like following:
Scanner inputFile = new Scanner(new File(file));
inputFile.useDelimiter("[\\r,]");
while (inputFile.hasNext()) {
String unknown = inputFile.next();
if (search.equals(unknown)) {
System.out.println("Yay!");
}
}
inputFile.close();
I think the easiest way to compare string against a file is to add a visible window where the user types the country, and reading the input to a string with String str = textField.getText();
I am guessing that your comparison is failing due to case-sensitivity.
Should your string comparison not be CASE-INSENSITIVE?
There are a few possible issues here. First, you're converting the searchString to lower case. Are the data in the CSV also lower case? If not, try using equalsIgnoreCase instead. Also, it seems to me like you should be able to match parts of the country name. In that case, equals (or equalsIgnoreCase) would only work if the user inputs the complete country name. If you want to be able to match only a part, use contains instead.