Regular expression float number on a input text file - java

I need to do a payroll report. You have to type the file that has the text information. The Program checks if the file exist or not. Then you make a output file of the program. The programs prints the names, hours, and rates of workers in a text file. I program only runs the last set of numbers.
import java.text.NumberFormat;
import javax.swing.JTextArea;
import java.awt.Font;
import javax.swing.JOptionPane;
import java.util.Scanner;
import java.io.*;
public class Homework {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
String answer, filename;
filename = JOptionPane.showInputDialog("Enter the Input File Path:");
File input = new File(filename);
if (!input.exists()) {
JOptionPane.showMessageDialog(null, "The input file:\n" + filename + "\ndoes not exist!");
System.exit(0);
}
filename = JOptionPane.showInputDialog("Enter the Output File Path:");
File output = new File(filename);
if (output.exists()) {
answer = JOptionPane.showInputDialog("The output file alaready exist!\nDo you want to overwrite it?");
if (!answer.toLowerCase().equals("yes")) {
System.exit(0);
}
}
PrintWriter outFile = new PrintWriter(filename);
Scanner in = new Scanner(input);
double numberWords = 0, countNumber = 0;
double value;
String num, words, message;
String amtStr, line = "";
String alphaRegex = ".*[A-Za-z].*";
String numRegex = ".*[0-9].*";
while (in.hasNext()) {
words = in.next();
if (words.matches(alphaRegex)) {
numberWords++;
message = "The name is "+words+"\n"; //The Line is but leave +line+
JOptionPane.showMessageDialog (null, message);
} else if (words.matches(numRegex)) {
countNumber++;
num = in.next();
message = "The number is "+num+"\n"; //The Line is but leave +line+
JOptionPane.showMessageDialog (null, message);
}
}
}
}

It was not your regular expression that was causing the problem. It was the if statement in the while loop. When the word matches numRegex, than you asign in.next() to num, causing the scanner to skip the current word and chossing the next one, that in your case happens to be a num as well.
Replace the while loop with this and it will work (I have tested the code):
while (in.hasNext()) {
words = in.next();
if (words.matches(alphaRegex)) {
numberWords++;
message = "The name is "+words+"\n";
JOptionPane.showMessageDialog (null, message);
} else if (words.matches(numRegex)) {
countNumber++;
num = words; // instead of num = in.next()
message = "The number is "+num+"\n";
JOptionPane.showMessageDialog (null, message);
}
}

I'm assuming that you're looking for a regex to identify floating point numbers in text. If that's the case, here's one:
"(\\.\\d+)|(\\d+(\\.\\d+)?)"
This matches any lone decimal followed by one or more digits or any sequence of digits followed by an optional decimal with one or more digits following it. Note that this does not address leading zeros, if that's an issue.
This website is a fantastic resource for building and testing regular expressions:
http://www.regexr.com/

Related

Scanner issue! Code is skipping the first user input and printing twice instead of once ONLY on the first iteration

https://courses.cs.washington.edu/courses/cse142/15sp/homework/6/spec.pdf
EDIT* Input Files are here:(sorry i'm new to stack overflow, hopefully this works)
I've also tried console.next() but it gives different errors than console.nextLine() in the rePlaceholder method. **
tarzan.txt - https://pastebin.com/XDxnXYsM
output for tarzan should look like this: https://courses.cs.washington.edu/courses/cse142/17au/homework/madlibs/expected_output_1.txt
simple.txt https://pastebin.com/Djc2R0Vz
clothes.txt https://pastebin.com/SQB8Q7Y8
this code should print to an output file you name.
Hello, I have a question about scanners because I don't understand why the code
is skipping the user input on the first iteration but works fine on the rest.
I'm writing a code to create a madlib program and the link will provide the explanation to the program but pretty much you have these placeholders in a text file and when you see one, you prompt for user input to replace it with your own words. However, my program always go through TWO placeholders first and only ask the user input for one, completely skipping the first placeholder. What is wrong with my code??? Also, how do you fix this? Everything else is running perfectly fine, only that the first line is consuming two placeholders so I'm always off by one.
Welcome to the game of Mad Libs.
I will ask you to provide various words
and phrases to fill in a story.
The result will be written to an output file.
(C)reate mad-lib, (V)iew mad-lib, (Q)uit? c
Input file name: tarzan.txt
Output file name: test.txt
Please type an adjective: Please type a plural noun: DD DDDD <--- why is it like this
Please type a noun: DDDD
Please type an adjective: DD
Please type a place:
========================================================================
package MadLibs;
import java.util.*;
import java.io.*;
public class MadLibs2 {
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
intro();
boolean isTrue = true;
while(isTrue) {
System.out.print("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
String choice = console.next();
if (choice.equalsIgnoreCase("c")) {
create(console);
}
else if (choice.equalsIgnoreCase("v")) {
view(console);
}
else if (choice.equalsIgnoreCase("q")) {
System.exit(0);
}
}
}
public static void view(Scanner console) throws FileNotFoundException {
System.out.print("Input file name: ");
String viewFile = console.next();
File existingMadLib = new File(viewFile);
Scanner printText = new Scanner(existingMadLib);
while(printText.hasNextLine()) {
System.out.println(printText.nextLine());
}
}
public static void create(Scanner console) throws FileNotFoundException {
System.out.print("Input file name: ");
String inputFile = console.next();
File newMadLib = new File(inputFile);
while(!newMadLib.exists()) {
System.out.print("File not found. Try again: ");
inputFile = console.next();
newMadLib = new File(inputFile);
}
System.out.print("Output file name: ");
String outputFile = console.next();
System.out.println();
PrintStream output = new PrintStream(new File(outputFile));
Scanner input = new Scanner(newMadLib);
while(input.hasNextLine()) {
String line = input.nextLine();
outputLines(line, output, console);
}
}
public static void outputLines(String line, PrintStream output, Scanner console) throws FileNotFoundException{
String s = "";
Scanner lineScan = new Scanner(line);
while(lineScan.hasNext()){
s = lineScan.next();
if(s.startsWith("<") || s.endsWith(">")) {
s = rePlaceholder(console, lineScan, s);
}
output.print(s + " ");
}
output.println();
}
public static String rePlaceholder(Scanner console, Scanner input, String token) {
String placeholder = token;
placeholder = placeholder.replace("<", "").replace(">", "").replace("-", " ");
if (placeholder.startsWith("a") || placeholder.startsWith("e") || placeholder.startsWith("i")
|| placeholder.startsWith("o") || placeholder.startsWith("u")) {
System.out.print("Please type an " + placeholder + ": ");
} else {
System.out.print("Please type a " + placeholder + ": ");
}
String change = console.nextLine();
return change;
}
public static void intro() {
System.out.println("Welcome to the game of Mad Libs.");
System.out.println("I will ask you to provide various words");
System.out.println("and phrases to fill in a story.");
System.out.println("The result will be written to an output file.");
}
}
in your rePlaceholder, change this line:
String change = console.nextLine();
Into this
String change = console.next();
Your problem is that nextLine doesn't wait for your output, just reads what it has in the console, waiting for a new line.
This is from the documentation to be a bit more precise on the explanation:
Since this method continues to search through the input looking for a
line separator, it may buffer all of the input searching for the line
to skip if no line separators are present.
UPDATE
After reading the comment, the previous solution will not work for multiple words.
After reading the output file, you are using next().
You need to make another call to nextLine() to clean the buffer of any newlines.
System.out.print("Output file name: ");
String outputFile = console.next();
console.nextLine(); // dummy call
System.out.println();

How do I update a file using an ArrayList, Java

I am writing a method that will take in some command line arguments, validate them and if valid will edit an airport's code. The airport name and it's code are stored in a CSV file. An example is "Belfast,BHD". The command line arguments are entered as follows, java editAirport EA BEL Belfast, "EA" is the 2letter code that makes the project know that I want to Edit the code for an Airport, "BEL" is the new code, and Belfast is the name of the Airport.
When I have checked through the cla's and validated them I read through the file and store them in an ArrayList as, "Belfast,BEL". Then I want to update the text file by removing the lines from the text file and dumping in the arraylist, but I cannot figure out how to do it. Can someone show me a way using simple code (no advanced java stuff) how this is possible.
Here is my program
import javax.swing.*;
import java.io.*;
import java.util.*;
import java.text.*;
public class editAirport
{
public static void main(String [] args)throws IOException
{
String pattern = "[A-Z]{3}";
String line, line1, line2;
String[] parts;
String[] parts1;
boolean found1 = false, found2 = false;
File file = new File("Airports.txt"); // I created the file using the examples in the outline
Scanner in = new Scanner(file);
Scanner in1 = new Scanner(file);
Scanner in2 = new Scanner(file);
String x = args[0], y = args[1], z = args[2];
//-------------- Validation -------------------------------
if(args.length != 3) // if user enters more or less than 3 CLA's didplay message
JOptionPane.showMessageDialog(null, "Usage: java editAirport EA AirportCode(3 letters) AirportName");
else if(!(file.exists())) // if "Airports.txt" doesn't exist end program
JOptionPane.showMessageDialog(null, "Airports.txt does not exist");
else // if everything is hunky dory
{
if(!(x.equals("EA"))) //if user doesn't enter EA an message will be displayed
JOptionPane.showMessageDialog(null, "Usage: java editAirport EA AirportCode(3 letters) AirportName");
else if(!(y.matches(pattern))) // If the code doesn't match the pattern a message will be dislayed
JOptionPane.showMessageDialog(null, "Airport Code is invalid");
while(in.hasNext())
{
line = in.nextLine();
parts = line.split(",");
if(y.equalsIgnoreCase(parts[1]))
found1 = true; //checking if Airport code already is in use
if(z.equalsIgnoreCase(parts[0]))
found2 = true; // checking if Airport name is in the file
}
if(found1)
JOptionPane.showMessageDialog(null, "Airport Code already exists, Enter a different one.");
else if(found2 = false)
JOptionPane.showMessageDialog(null, "Airport Name not found, Enter it again.");
else
/*
Creating the ArrayList to store the name,code.
1st while adds the names and coses to arraylist,
checks if the name of the airport that is being edited is in the line,
then it adds the new code onto the name.
sorting the arraylist.
2nd for/while is printing the arraylist into the file
*/
ArrayList<String> airport = new ArrayList<String>();
while(in1.hasNext()) // 1st while
{
line1 = in1.nextLine();
if(line1.contains(z))
{
parts1 = line1.split(",");
parts1[1] = y;
airport.add(parts1[0] + "," + parts1[1]);
}
else
airport.add(line1);
}
Collections.sort(airport); // sorts arraylist
FileWriter aFileWriter = new FileWriter(file, true);
PrintWriter output = new PrintWriter(aFileWriter);
for(int i = 0; i < airport.size();)
{
while(in2.hasNext()) // 2nd while
{
line2 = in2.nextLine();
line2 = airport.get(i);
output.println(line2);
i++;
}
}
output.close();
aFileWriter.close();
}
}
}
}
The Airports.txt file is this
Aberdeen,ABZ
Belfast City,BHD
Dublin,DUB
New York,JFK
Shannon,SNN
Venice,VCE
I think your problem may lie in the two lines:
line2 = in2.nextLine();
line2 = airport.get(i);
this will overwrite the 'line2' in memory, but not in the file.

how to generate a .txt file from a list whose title is an abbreviation of a full name

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

Java not detecting file contents

I'm having difficulty figuring out why this isn't working. Java simply isn't executing the while loop, file apparently does not have a next line.
fileName = getFileName(keyboard);
file = new Scanner (new File (fileName));
pass = true;
String currentLine;
while (file.hasNextLine()) {
currentLine = file.nextLine();
System.out.println(reverse(currentLine));
}
Here is the file I am testing this with. I got it to work with the first few paragraphs but it seems to simply stop working...:
Jabberwocky
'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe;
All mimsy were the borogoves,
And the mome raths outgrabe.
"Beware the Jabberwock, my son!
The jaws that bite, the claws that catch!
Beware the Jubjub bird, and shun
The frumious Bandersnatch!"
He took his vorpal sword in hand:
Long time the manxome foe he soughtó
So rested he by the Tumtum tree,
And stood awhile in thought.
And as in uffish thought he stood,
The Jabberwock, with eyes of flame,
Came whiffling through the tulgey wood,
And burbled as it came!
One, two! One, two! and through and through
The vorpal blade went snicker-snack!
He left it dead, and with its head
He went galumphing back.
"And hast thou slain the Jabberwock?
Come to my arms, my beamish boy!
O frabjous day! Callooh! Callay!"
He chortled in his joy.
'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe;
All mimsy were the borogoves,
And the mome raths outgrabe.
——from Through the Looking-Glass, and What Alice Found There (1872).
/*
* Lab13a.java
*
* A program that prompts the user for an input file name and, if that file exists,
* displays each line of that file in reverse order.
* Used to practice simple File I/O and breaking code up into methods as well as a first
* step to implementing Lab13b.java - reversing the entire file and Lab13c.java writing
* output to a separate output file.
*
* #author Benjamin Meyer
*
*/
package osu.cse1223;
import java.io.*;
import java.util.*;
public class Lab13a {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String fileName = "";
Scanner file;
boolean pass = false;
while (!pass) {
try {
fileName = getFileName(keyboard);
file = new Scanner (new File (fileName));
pass = true;
String currentLine;
while (file.hasNextLine()) {
currentLine = file.nextLine();
System.out.println(reverse(currentLine));
}
}
catch (FileNotFoundException e) {
System.out.println("There was a problem reading from " + fileName);
System.out.println("Goodbye.");
return;
}
}
}
// Given a Scanner as input prompts the user to enter a file name. If given an
// empty line, respond with an error message until the user enters a non-empty line.
// Return the string to the calling program. Note that this method should NOT try
// to determine whether the file name is an actual file - it should just get a
// valid string from the user.
private static String getFileName(Scanner inScanner) {
boolean pass = true;
String fileName = "";
while (pass) {
System.out.print("Enter an input name: ");
fileName = inScanner.nextLine();
if (fileName.length()!=0) {
pass = false;
}
else {
System.out.println("You cannot enter an empty string.");
}
}
return fileName;
}
// Given a String as input return the reverse of that String to the calling program.
private static String reverse(String inString) {
if (inString.length()==0) {
return "";
}
String reversed = "" + inString.charAt(inString.length()-1);
for (int x = inString.length()-2; x>=0; x--) {
reversed = reversed + inString.charAt(x);
}
return reversed;
}
}
The issue might lie in your implementation of your functions getFilename() or reverse(). Since you have stated that you got it to work with a few of the paragraphs I doubt that your program is failing due to your file handling. It might be in the logic you are using to reverse the strings in the file that is causing the issue.

Txtfile search not working

Ok so i have inputted a number of records to a text file and i can both write to and read from this file, but i am now attempting to search through this textfile and have encountered a problem.
package assignmentnew;
// Import io so we can use file objects
import java.io.*;
import java.util.Scanner;
public class SearchProp {
public void Search() throws FileNotFoundException {
try {
String details, input, id, line;
int count;
Scanner user = new Scanner(System.in);
System.out.println();
System.out.println();
System.out.println("Please enter your housenumber: ");
input = user.next();
Scanner housenumber = new Scanner(new File("writeto.txt"));
while (housenumber.hasNext())
{
id = housenumber.next();
line = housenumber.nextLine();
if (input.equals(id))
{
System.out.println("House number is: " + id + "and" + line);
break;
}
if(!housenumber.hasNext()) {
System.out.println("no house with this number");
}
}
}
catch(IOException e)
{
System.out.print("File failure");
}
}
}
No matter what value i enter i am told that the house number is not present in the file, but obviously it is, any ideas?
Addendum:
File Structure in textfile.
27,Abbey View,Hexham,NE46 1EQ,4,150000,Terraced
34,Peth Head,Hexham,NE46 1DB,3,146000,Semi Detached
10,Downing Street,London,sw19,9,1000000,Terraced
The default delimiter for a scanner is white-space, and not ,.
You have to use housenumber.useDelimiter(","); and the code will work.
EDIT:
Set it before the while.
And that is what I get for example for 27.
Please enter your housenumber:
27
House number is: 27 and ,Abbey View,Hexham,NE46 1EQ,4,150000,Terraced

Categories

Resources