Java - Searching through a file without using a list - java

I'm trying to create a program that will let a user search through a file for a specific word, without creating an array and adding all the contents of the file to it (so it could be easily ported and used with different file sizes etc). Below is my code:
package test2;
import java.io.InputStream;
import java.util.Scanner;
import javax.swing.JOptionPane;
/**
*
* #author Kafaka157
*/
public class Prep2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
InputStream stream = Prep1.class.getResourceAsStream("words.txt");
Scanner scanner = new Scanner(stream);
while(scanner.hasNextLine()){
String word = JOptionPane.showInputDialog("Input word to look for: ");
if(word.equals(scanner.next().trim())){
JOptionPane.showMessageDialog(null, word + " found"); // found
break;
}else{
JOptionPane.showMessageDialog(null,word + " not found"); // not found
break;
}
}
}
}
The above is my code, I get no build errors or anything, however it won't return found on words which I know are in the file. It seems to default to else at every instance, any help / idea where I'm going wrong? Many thanks.

public static void main(String[] args) {
InputStream stream = Prep1.class.getResourceAsStream("words.txt");
Scanner scanner = new Scanner(stream);
boolean wordFound = false;//initially set it to false
String word = JOptionPane.showInputDialog("Input word to look for: ");
while(scanner.hasNextLine()){
if(word.equals(scanner.next().trim())){
//after the loop would be a better place to show below notification
//JOptionPane.showMessageDialog(null, word + " found"); // found
wordFound = true;//make the flag as true and break out of the loop
break;
}/*else{
JOptionPane.showMessageDialog(null,word + " not found"); // not found
break;
}*/
}
if(wordFound)
JOptionPane.showMessageDialog(null, word + " found"); // found
else
JOptionPane.showMessageDialog(null,word + " not found");
Few modifications needed and that should do. The comments provided above should serve the purpose. The main problem is that you are breaking out of the loop after checking the first word itself!

Related

In Java, using Scanner, Is there a way to find a specific String in a CSV file, use it as a column header and return all values under it?

I am trying to find the String "5464" in a csv document then have it return all of the values under that String (same number of Delimiters from the start of the line), until reaching the end of the list (no more values in the column). Any help would be sincerely appreciated.
import javax.swing.JOptionPane;
public class SearchNdestroyV2 {
private static Scanner x;
public static void main(String[] args) {
String filepath = "tutorial.txt";
String searchTerm = "5464"
readRecord(searchTerm,filepath);
}
public void readRecord(String searchTerm, String filepath)
{
boolean found = false;
String ID = ""; String ID2 = ""; String ID3 = "";
}
try
{
x = new Scanner(new File(filepath));
x.useDelimeter("[,\n]");
while(x.hasNext() && !found )
{
ID = x.next();
ID2 = x.nextLine();
ID3 = x.nextLine();
if(ID.equals(searchTerm))
{
found = true;
}
}
if (found)
{
JOptionPane.showMessageDialog(null,"ID: " + ID + "ID2: " + ID2 + "ID3: "+ID3);
}
}
else
{
JOptionPane.showMessageDialog(null, "Error:");
}
catch(Exception e)
{
}
{
}
I'm not exactly sure of what you mean. The way I read your question:
You want to locate a specific String ("5464") that is contained within a specific column within a comma (,) delimited CSV file. If this specific string (search term) is found then retrieve all other values contained within the same column for the rest of the CSV file records from the point of location. Here is how:
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class SearchNDestroyV2 {
private Scanner fileInput;
public static void main(String[] args) {
// Do this if you don't want to deal with statics
new SearchNDestroyV2().startApp(args);
}
private void startApp(String[] args) {
String filepath = "tutorial.txt";
String searchTerm = "5464";
readRecord(searchTerm, filepath);
}
public void readRecord(String searchTerm, String filepath) {
try {
fileInput = new Scanner(new File(filepath));
// Variable to hold each file line data read.
String line;
// Used to hold the column index value to
// where the found search term is located.
int foundColumn = -1;
// An ArrayList to hold the column values retrieved from file.
ArrayList<String> columnList = new ArrayList<>();
// Read file to the end...
while(fileInput.hasNextLine()) {
// Read in file - 1 trimmed line per iteration
line = fileInput.nextLine().trim();
//Skip blank lines (if any).
if (line.equals("")) {
continue;
}
// Split the curently read line into a String Array
// based on the comma (,) delimiter
String[] lineParts = line.split("\\s{0,},\\s{0,}"); // Split on any comma/space situation.
// Iterate through the lineParts array to see if any
// delimited portion equals the search term.
for (int i = 0; i < lineParts.length; i++) {
/* This IF statement will always accept the column data and
store it if the foundColumn variable equals i OR the current
column data being checked is equal to the search term.
Initially when declared, foundColumn equals -1* and will
never equal i unless the search term is indeed found. */
if (foundColumn == i || lineParts[i].equals(searchTerm)) {
// Found a match
foundColumn = i; // Hold the Coloumn index number of the found item.
columnList.add(lineParts[i]); // Add the found ite to the List.
break; // Get out of this loop. Don't need it anymore for this line.
}
}
}
if (foundColumn != -1) {
System.out.println("Items Found:" + System.lineSeparator() +
"============");
for (String str : columnList) {
System.out.println(str);
}
}
else {
JOptionPane.showMessageDialog(null, "Can't find the Search Term: " + searchTerm);
}
}
catch(Exception ex) {
System.out.println(ex.getMessage());
}
}
}
If however, what you want is to search through the CSV file and as soon as any particular column equals the Search Term ("5464") then simply store the CSV line (all its data columns) which contains that Search Term. Here is how:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class SearchNDestroyV2 {
/* A JFrame used as Parent for displaying JOptionPane dialogs.
Using 'null' can allow the dialog to open behind other open
applications (like the IDE). This ensures that it will be
displayed above all other applications at center screen. */
JFrame iFRAME = new JFrame();
{
iFRAME.setAlwaysOnTop(true);
iFRAME.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
iFRAME.setLocationRelativeTo(null);
}
public static void main(String[] args) {
// Do this if you don't want to deal with statics
new SearchNDestroyV2().startApp(args);
}
private void startApp(String[] args) {
String filepath = "tutorial.txt";
String searchTerm = "5464";
ArrayList<String> recordsFound = readRecord(searchTerm, filepath);
/* Display any records found where a particular column
matches the Search Term. */
if (!recordsFound.isEmpty()) {
System.out.println("Records Found:" + System.lineSeparator()
+ "==============");
for (String str : recordsFound) {
System.out.println(str);
}
}
else {
JOptionPane.showMessageDialog(iFRAME, "Can't find the Search Term: " + searchTerm);
iFRAME.dispose();
}
}
/**
* Returns an ArrayList (of String) of any comma delimited CSV file line
* records which contain any column matching the supplied Search Term.<br>
*
* #param searchTerm (String) The String to search for in all Record
* columns.<br>
*
* #param filepath (String) The CSV (or text) file that contains the data
* records.<br>
*
* #return ({#code ArrayList<String>}) An ArrayList of String Type which
* contains the file line records where any particular column
* matches the supplied Search Term.
*/
public ArrayList<String> readRecord(String searchTerm, String filepath) {
// An ArrayList to hold the line(s) retrieved from file
// that match the search term.
ArrayList<String> linesList = new ArrayList<>();
// Try With Resourses used here to auto-close the Scanner reader.
try (Scanner fileInput = new Scanner(new File(filepath))) {
// Variable to hold each file line data read.
String line;
// Read file to the end...
while (fileInput.hasNextLine()) {
// Read in file - 1 trimmed line per iteration
line = fileInput.nextLine().trim();
//Skip blank lines (if any).
if (line.equals("")) {
continue;
}
// Split the curently read line into a String Array
// based on the comma (,) delimiter
String[] lineParts = line.split("\\s{0,},\\s{0,}"); // Split on any comma/space situation.
// Iterate through the lineParts array to see if any
// delimited portion equals the search term.
for (int i = 0; i < lineParts.length; i++) {
if (lineParts[i].equals(searchTerm)) {
// Found a match
linesList.add(line); // Add the found line to the List.
break; // Get out of this loop. Don't need it anymore for this line.
}
}
}
}
catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
}
return linesList; // Return the ArrayList
}
}
Please try to note the differences between the two code examples. In particular how the file reader (Scanner object) is closed, etc.

Coding with Java Eclipse

I need to make a program where a user can input a name, and the program will search through the file line by line until it has a match, then return all the match. So this is what i Have, I got the file into the program, but cant seem to code the program to search the file for the user input. Any help?
Assignment: this what the code has to be able to do.
read in each row, parse out the name part, perform a match on names, if match return full name, else move to next row. Have message if you reach the end without a match.
import java.util.Scanner;
import java.io.*;
public class USpres {
public static void main(String[] args) throws FileNotFoundException {
File file = new File ("USPres.txt");
Scanner kb = new Scanner(System.in);
Scanner scanner = new Scanner(file);
System.out.println("Please enter the name you would like to search for: ");
String name = kb.nextLine();
while (scanner.hasNextLine())
{
if(scanner.nextLine() == kb)
{
System.out.println("I found " +name+ " in file " +file.getName());
}
break;
if(scanner.nextLine() == kb)
{
System.out.println("I found " +name+ " in file " +file.getName());
}
should become
if(scanner.nextLine().equalsIgnoreCase(name))
{
System.out.println("I found " +name+ " in file " +file.getName());
}
just like they said above in the comments. Also, .equals() is meant to compare two Objects, not two strings. Since they are both strings, you may have success with this method, but I would suggest always using .equalsIgnoreCase() when comparing Strings.

Regular expression float number on a input text file

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/

while loop won't read file, or print out line java

I have a with the hentAntall method in my code below. It's supposed to find the search word inside a txt file. I don't get any sort of error. It just won't print out any of the two possible lines.
This method has to access a constructor first to get the search word, and then it has to find that search word in the txt file and add to count. The constructor gets the search word from another class. Like this new lolz("searchword").hentAntall();
(I apologize for the stupid naming in this program, but it's just a copy of one of my programs, and I'm just trying to correct it without screwing up the original.)
import java.io.File;
import java.util.Scanner;
public class lolz {
private String sokeord=null;
private int antall = 0;
// Constructor
lolz(String searchword) throws Exception{
this.sokeord = searchword;
}
//toString method, to print in the same format.
#Override
public String toString(){
return "\nSokeordet er: " + sokeord+ "\n";
}
// Gets the ammount of the searchword
public int hentAntall() throws Exception{
File file = new File("Hvorfor.txt");
Scanner readfile = new Scanner(file);
while (readfile.hasNextLine()){
String nextline = readfile.nextLine();
if (nextline.equalsIgnoreCase(sokeord)) {
antall ++;
System.out.println("Antallet av:" + sokeord + "er " + antall);
}
else {System.out.println("Error no such search word in the given text");}
}
return antall;
}
// void methode to increase the count of a searcheword.
void oekAntall() {
antall++;
}
}
This is the other class that calls on this method, and also give information to the constructor.
public class Main {
public static void main(String[] args) throws Exception {
new lolz("fungerer").hentAntall();
}}
Also tried some of the suggestions and they did not work, I only get a the message Process finished with exit code 0.
Your Issue:
You are trying to compare a Scanner variable with a String Variable?!!!
Explanation:
you try to compare content of Scanner which is
java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match
valid=true][need input=false][source
closed=false][skipped=false][group separator=\,][decimal
separator=.][positive prefix=][negative prefix=\Q-\E][positive
suffix=][negative suffix=][NaN string=\Q�\E][infinity string=\Q∞\E]
with content of a String variable.
You do not read the each line with following
if (readfile.equals(sokeord)) {
You Should have
if (readfile.nextLine().equals(sokeord)) {
Instead of:
readfile.equals(sokeord)
Which is comparing an instance of type Scanner with a String (never going to be true). You need to read a line and compare that.
String line = readfile.nextLine();
if(line.equals(sokeord)){
Add a main method to your class:
public static void main(String[] args)
{
hentAntall();
}
You will have to make hentAntall() static or create an instance of lolz class and call it that way.
Also change:
while (readfile.hasNext()){
if (readfile.nextLine().contains(sokeord)) {
You need to actually read the input and then check if sokeord exists in the line or not.
Your hentAntall method should be like this:
public int hentAntall() throws Exception {
File file = new File("Hvorfor.txt");
Scanner readfile = new Scanner(file);
while (readfile.hasNextLine()) {
String word = readfile.next();
if (word.contains(sokeord)) {
antall++;
System.out.println("Antallet av:" + sokeord + "er " + antall);
} else {
System.out
.println("Error no such search word in the given text: ");
}
}
readfile.close();
return antall;
}
Don't forget to close the Scanner resource to avoid leaks.

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.

Categories

Resources