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.
Related
I'm currently working on a program that is meant to store the inventory for a car dealership. I'm trying to find the correct way to print the data stored in an array list to a file when the user is prompted with a y/n option "Would you like to print the inventory to a file? (y/n)".
So far I have two separate methods. One which displays the data that I've input into the array, and one that prints the data to a file. I just need to figure out how to add the question & print to file aspect to the display method.
// method to save vehicle data to a file upon exiting the program
public static void printToFile(String filename) throws FileNotFoundException {
PrintWriter pw = new PrintWriter(filename);
String text = " Make | Model| Color| Year| Mileage\n";
for (Automobile a : carList) {
text += a.toCSV() + "\n"; // Separating car information with commas
}
pw.write(text);
pw.flush();
pw.close();
System.out.println("\n Car Inventory below has been printed to " + filename + " file. \n");
System.out.println(text);
}
// My method to display the data however I just need to find a way to incorporate the y/n question for printing to a file also
public static void displayCars() { // method to display all vehicles in the list
Scanner scnr = new Scanner(System.in);
System.out.println("--------------");
System.out.println("Car Inventory");
System.out.println("--------------");
for (Automobile a : carList) {
System.out.println(a + "\n");
// FIND OUT HOW TO ADD y/n INPUT FOR PRINTING TO FILE
}
}
Looking to combine add a y/n question into the Display method that will ask the user if they want to print the data to a file.
Assuming you want to iterate over each automobile in the list and ask the user for each whether or not they would like it added to the file, something like the following should work:
public static List<Automobile> displayCars() {
Scanner scnr = new Scanner(System.in);
List<Automobile> fileItems = new ArrayList<>();
System.out.println("--------------");
System.out.println("Car Inventory");
System.out.println("--------------");
for (Automobile a : carList) {
System.out.println(a + "\n");
System.out.println("Would you like to add this item to the file? (y/n)");
String input = scnr.next();
if (input.equals("y")) {
fileItems.add(a);
System.out.println("Added to file.");
}
}
return fileItems;
}
The method now returns the list of only the automobiles that should be added to the file.
Note: I have not compiled/tested so there may be some errors.
If this is a command line program, then you can use a Scanner to read input from the user. Something like the following would work:
// Creates a new Scanner that reads from standard in
Scanner userInput = new Scanner(System.in);
String yesNo = userInput.next(); // blocks the program until something is typed into the command line
if (yesNo.toLowerCase().equals("y")) {
// print to file
} else {
// continue doing something else
}
The .toLowerCase() isn't necessary, but I would recommend it to handle changes in case from user input.
See Scanner for more information.
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();
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!
I am trying to read information from a file to interpret it. I want to read every line input. I just recently learned about bufferedreader. However, the problem with my code is that it skips every other line.
For example, when I put in 8 lines of data, it only prints 4 of them. The even ones.
Here is the code:
import java.io.*;
import java.util.Scanner;
public class ExamAnalysis
{
public static void main(String[] args) throws FileNotFoundException, IOException
{
int numOfQ = 10;
System.out.println();
System.out.println("Welcome to Exam Analysis. Let’s begin ...");
System.out.println();
System.out.println();
System.out.println("Please type the correct answers to the exam questions,");
System.out.print("one right after the other: ");
Scanner scan = new Scanner(System.in);
String answers = scan.nextLine();
System.out.println("What is the name of the file containing each student's");
System.out.print("responses to the " + numOfQ + " questions? ");
String f = scan.nextLine();
System.out.println();
BufferedReader in = new BufferedReader(new FileReader(new File(f)));
int numOfStudent= 0;
while ( in.readLine() != null )
{
numOfStudent++;
System.out.println("Student #" + numOfStudent+ "\'s responses: " + in.readLine());
}
System.out.println("We have reached “end of file!”");
System.out.println();
System.out.println("Thank you for the data on " + numOfStudent+ " students. Here is the analysis:");
}
}
}
I know this may be a bit of a bad writing style. I am just really new to coding. So if there is any way you can help me fix the style of the code and methods, I would be really thrilled.
The point of the program is to compare answers with the correct answer.
Thus I also have another question:
How can I compare strings with the Buffered Reader?
Like how can I compare ABCCED with ABBBDE to see that the first two match but the rest don't.
Thank you
the problem with my code is that it skips every other line
Your EOF check thows a line away on each iteration
while ( in.readLine() != null ) // read (first) line and ignore it
{
numOfStudent++;
System.out.println("Student #" + numOfStudent+ "\'s responses: " +
in.readLine()); // read (second) next line and print it
}
to read all line do the following:
String line = null;
while ( null != (line = in.readLine())) // read line and save it, also check for EOF
{
numOfStudent++;
System.out.println("Student #" + numOfStudent+ "\'s responses: " +
line); // print it
}
To compare Strings you need to use the String#compareTo(String other) method. Two Strings are equal if the return value is 0.
You don't compare Strings with readLine(). You compare them with String.equals().
Your reading code skips every odd line for the reason mentioned in the duplicate.
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.