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.
Related
I need to do the following exercise:
a) Make a new text file
b) Put the user's input into that text file
c) we must save all user's input while user keeps typing but as soon as user pressing Enter in a new line (When an empty string is sent) the user must get out of the program.
For coding this issue I have write the following codes, but when
I try it by myself so I am stuck at while loop, cant get out when I sending empty string.
So could anyone help with a solution for this issue?
Thanks
I have tried some of the solutions I have found on youtube like making if statement inside the while loop or adding the code that takes the input of the user inside the loop's condition.
So I do not know what to do at the next stage.
I tried to see the console window via the Eclipse output.
import java.io.*;
import java.util.Scanner;
public class lesson {
public static void main(String[] args) throws IOException {
File file = new File("mytext.txt");
if (file.exists() == false) {
file.createNewFile();
}
PrintWriter pw = new PrintWriter(file);
System.out.println("Enter a text here: ");
String str;
while (true) {
Scanner input = new Scanner(System.in);
str = input.next();
pw.println();
if (str.equals(null)) {
break;
}
}
pw.close();
System.out.println("Done");
}
}
The user must get out of the loop when he/she sends an empty string. and the writing to the file must be finished.
First the code, then the explanation...
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Lesson {
public static void main(String[] args) {
File file = new File("mytext.txt");
try (Scanner input = new Scanner(System.in);
PrintWriter pw = new PrintWriter(file)) {
System.out.println("Enter a text here: ");
String str = input.nextLine();
while (str.length() > 0) {
pw.println(str);
pw.flush();
str = input.nextLine();
}
}
catch (IOException xIo) {
xIo.printStackTrace();
}
System.out.println("Done");
}
}
The above code requires at least Java 7 since it uses try-with-resources. Scanner should be closed, just like PrintWriter should be closed. The try-with-resources ensures that they are closed. Note that if file mytext.txt doesn't exist, creating a new PrintWriter will also create the file and if the file already exists, its contents will be removed and replaced with the text that you enter.
After that the prompt is displayed, i.e. Enter a text here, and the user enters a line of text. Method nextLine() will get all the text entered until the user presses Enter. I read your question again and the program should exit when the user presses Enter without typing any text. When the user does this, str is an empty string, i.e. it has zero length. That means I need to assign a value to str before the while loop, hence the first call to method nextLine() before the while loop.
Inside the while loop I write the value entered by the user to the file mytext.txt and then wait for the user to enter another line of text. If the user presses Enter without typing any text, str will have zero length and the while loop will exit.
Written and tested using JDK 12 on Windows 10 using Eclipse for Java Developers, version 2019-03.
To achieve this, we check is length of input is >0:
import java.io.*;
import java.util.Scanner;
public class lesson {
public static void main(String[] args) throws IOException {
File file = new File("mytext.txt");
if (file.exists() == false) {
file.createNewFile();
}
PrintWriter pw = new PrintWriter(file);
System.out.println("Enter a text here: ");
String str;
Scanner input = new Scanner(System.in);
while ((str = input.nextLine()).length() > 0) {
//str = input.next();
pw.println(str);
}
pw.close();
System.out.println("Done");
}
}
I am working on a simple program that takes input from user and then saves it with specific file name.
To be more precise:
public static Scanner in = new Scanner(System.in);
public static boolean quit = false;
public static String name;
public static FileWriter fw;
public static void main(String[] args) throws IOException {
System.out.print("File name: ");
name = in.nextLine();
fw = new FileWriter(name + ".txt", false);
System.out.println("Continue typing/type save to quit");
while(!quit) {
String word = in.nextLine();
if(word.equals("save")) {
fw.close();
quit = true;
}
else {
fw.write(word + "\n");
}
}
Program asks for file name.
User is typing words until he types "save" which saves the file
As you can see program ask user for file name at the beginning, before he starts to type. This is my problem. I want my program to ask the user for a file name at the end, after he typed all words. Unfortunately I cant do this because filewriter class creates the file when new object is created and name cannot be changed later.
I would like to know is there any solution to my problem or what kind of information should I look for.
You have two options:
Store all the user input in memory (in a List<String> for instance) and then write out the words after seeing the save keyword and getting the output filename from the user.
Open the output file as you are doing, but with a temporary name, and write the words as you read them. Upon seeing the save keyword, close the file, get the user's chosen filename, and then rename the temporary file to the user's choice.
Unless you need to process millions of words I'd go with option 1 for its simplicity.
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.
this is what I'm trying to accomplish:
To write a program code such that when the user is allowed to enter an employee name from the given list of employees, the program will search for
the employee’s payroll data and then generate a report in the form of a .txt file,
whose file name is the employee’s first initial of his / her first name, followed by
their complete last name.
For example, if a report is generated for David Davies, the report will be located in the text file bearing the name DDavies.txt.
I've generated the list and I know how to pick the records I'm looking for. My problem is in creating a text file based on the user selection.
i.e How do I create a file DDavies.txt based on a user entering "David Davies" as 1 string.
Since names have different lengths, that means each string length is potentially different so I can't pick out the characters by index alone (or I don't know how).
Since each full name is in 1 string, I was thinking of writing a code to pick the very first character, then the following string after the break(space) BUT since it's all in 1 string and the length isn't fixed, I don't know how to accomplish that.
And Filewriter doesn't help matters cos' I have to specify the .txt extension to create a text file so I don't know how to generate the text file dynamically (having a specified title) without entering the name myself.
I was thinking of breaking the string apart into a first and last name basis but that will change the code fundamentally cos what I'm trying to accomplish is part of a larger program.
Please pardon my long intro, this is my first time so I hope I'm being specific enough.
Below is the code. (Please note that the report doesn't need to be displayed to the user, I just need it to be generated in that firstInitial-LastName format)Thanks guys!
//Report.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.JOptionPane;
public class Report {
String firstLine = "", secondLine = "", thirdLine = "";
double hours = 0, wages = 0;
DecimalFormat twoDecimal = new DecimalFormat("0.00");
static ArrayList<String> emps = new ArrayList<String>();
public Report() throws Exception {
//code here the logic to create a report for the user
FileReader file = new FileReader("payroll.txt");
BufferedReader buffer = new BufferedReader(file);
String line;
File check = new File("Overtime.txt");
FileWriter file1;
if (check.exists())
file1 = new FileWriter("Overtime.txt", true);
else
file1 = new FileWriter("Overtime.txt");
int count = 0;
while ((line = buffer.readLine()) != null) {
firstLine = line;
secondLine = buffer.readLine();
thirdLine = buffer.readLine();
double grosspay;
emps.add(line);
}//end while
buffer.close();
file1.close();
String empList = "";
Collections.sort(emps);
for (String str : emps) {
empList += str + "\n";
}
//Employee Listing (names)
JOptionPane.showMessageDialog(null, "Name:\n" + empList, "Employee Listing",
JOptionPane.PLAIN_MESSAGE);
//Get input then of desired employee name to save employee data to a file
String userInput = "";
while (userInput == null || userInput.equals("")) {
userInput = JOptionPane.showInputDialog("To get a payroll report, enter a name from the list");
}
if (empList.toLowerCase().contains(userInput.toLowerCase())) {
/*Upon retrieval of a CORRECT employee name that exists from the employee list,
open payroll.txt file, grab the employee data from the name given
and write the emp's data to a file given the employee’s first initial of his / her first name,
followed by their complete last name. **THIS IS WHERE I NEED HELP!!** */
/**Examples of random names to choose from, we have David Davies, Hyacinth Ho, Betty Boop etc**/
// "Report Generated" Notification
JOptionPane.showMessageDialog(null, "Report Generated.", "Result", JOptionPane.PLAIN_MESSAGE);
}
//Error Message
else {
JOptionPane.showMessageDialog(null, "Error!! Name invalid or doesn't exist, please try again.");
}
System.exit(0);
} //END of Public Report ()
public static void main(String[] args) throws Exception {
new Report();
} //End of Main
} // End of Report Class
After checking the user input is not null and is correct. Try this:
String userInput;
....
String filename;
String[] split = userInput.split(" ");
//get the first names first character and gets the last name
filename = userInput.charAt(0)+split[split.length-1];
I was thinking of writing a code to pick the very first character, then the following string after the break(space) BUT since it's all in 1 string and the length isn't fixed, I don't know how to accomplish that.
You can use yourString.charAt(0) to pick first character of String.
To pick string after fist space you can just find index of that first space using yourString.indexOf(' ') and substring after it.
Example
String someString = "Foo Bar";
System.out.println(someString.charAt(0)
+ someString.substring(someString.indexOf(' ') + 1))
//+1 because we don't want to include space in substring
output: FBar
You can also add ".txt" to result.
Perhaps this is what you want:
String name = "Doctor Who";
String[] name_parts = name.split(" ");
String filename = name_parts[0].charAt(0) + name_parts[1] + ".txt");
//filename = DWho.txt
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.