I have a txt file of names and genders that I imported for this java program. The scanners are supposed take a user input (name and gender) and compare it line by line to find it within the text file and then print the line at which the name was found. However, only some names work and not others. I think it may be because the program only reads every other line but im not sure if thats the problem, or how to fix it.
Link to the name file: http://courses.cs.washington.edu/courses/cse142/16au/homework/names.txt
public static void fileSearch() throws FileNotFoundException {
System.out.println("What name are you looking for?");
Scanner scan = new Scanner(System.in);
String name = scan.nextLine();
String gender = scan.nextLine();
File file = new File("names.txt");
Scanner fileScan = new Scanner(file);
while (fileScan.hasNextLine()) {
String line = fileScan.nextLine();
Scanner lineScan = new Scanner(line);
String nameText = lineScan.next();
String genderText = lineScan.next();
if (name.equalsIgnoreCase(nameText) && gender.equalsIgnoreCase(genderText)) {
System.out.println(line);
}
}
}
}
Related
So I have a file with a list of users in the format like this:
michael:atbWfKL4etk4U:500:500:Michael Ferris:/home/michael:/bin/bash
abigail:&i4KZ5wmac566:501:501:Abigail Smith:/home/abigail:/bin/tcsh
What I need to do is just extract the passwords from the file which in this case are:
"atbWfKL4etk4U" and "&i4KZ5wmac566" and to store them into an array.
This is what I have so far:
public static void main(String[] args) throws IOException{
// Create a scanner for keyboard input
Scanner scan = new Scanner(System.in);
// Prompt user to select a file to open
System.out.print("Enter the path of the file: ");
String filename = scan.nextLine();
// Open the file
File file = new File(filename);
Scanner inputFile = new Scanner(file);
// Create Array to store each user password in
String[] passwords = {};
// Close the file
scan.close();
inputFile.close();
}
public static void main(String[] args) throws IOException{
// Create a scanner for keyboard input
Scanner scan = new Scanner(System.in);
// Prompt user to select a file to open
System.out.print("Enter the path of the file: ");
String filename = scan.nextLine();
// Open the file
File file = new File(filename);
Scanner inputFile = new Scanner(file);
List<String> passwords = new ArrayList<>();
while (sc.hasNextLine()) {
String line = sc.nextLine();
String password = line.split(":")[1];
passwords.add(password);
}
// Close the file
scan.close();
inputFile.close();
}
If instead you rather store username and password (assuming the first token is the user name), create a Map instead of a List.
Map<String, String> passwordMap = new HashMap<>();
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] tokens = line.split(":");
passwordMap.put(tokens[0], tokens[1]);
}
You could read the file line by line using a Scanner object.
Then, you use another Scanner object to read the password. Here's an example:
String input = "michael:atbWfKL4etk4U:500:500:Michael Ferris:/home/michael:/bin/bash";
Scanner s = new Scanner(input).useDelimiter(":");
s.next(); //skipping username
String password = s.next();
This looks like a typical CSV type file format and because there is an unknown number of Users in the file and the fact that arrays can not dynamically grow it's a good idea to utilize an ArrayList which can grow dynamically and then convert that list to a String array, for example:
The following method assumes there is No Header Line within the data file:
public static String[] getPasswordsFromFile(String filePath) {
List<String> passwordsList = new ArrayList<>();
File file = new File(filePath);
try (Scanner reader = new Scanner(file)) {
String line = "";
while (reader.hasNextLine()) {
line = reader.nextLine().trim();
// Skip blank lines (if any).
if (line.isEmpty()) {
continue;
}
/* Split out the password from the file data line:
The Regular Expression (RegEx) below splits each
encountered file line based on the Colon(:) delimiter
but also handles any possible whitespaces before
or after that delimiter: */
String linePassword = line.split("\\s*\\:\\s*")[1];
// If there is no password there then apply "N/A":
if (linePassword.isEmpty()) {
linePassword = "N/A";
}
// Add the password to the List
passwordsList.add(linePassword);
}
}
catch (FileNotFoundException ex) {
// Handle the exception (if any) the way you like...
System.err.println(ex.getMessage());
}
// Convert the List<String> to String[] Array and return:
return passwordsList.toArray(new String[passwordsList.size()]);
}
How you might use a method like this:
// Create a scanner object for keyboard input
Scanner userInput = new Scanner(System.in);
// Prompt user to select a file to open with validation:
String fileName = "";
// -----------------------------------
while (fileName.isEmpty()) {
System.out.print("Enter the path of the file (c to cancel): --> ");
fileName = userInput.nextLine();
if (fileName.equalsIgnoreCase("c")) {
System.out.println("Process Canceled! Quiting.");
System.exit(0);
}
if (!new File(fileName).exists()) {
System.out.println("Invalid Entry! Try again...\n");
fileName = "";
}
}
// -----------------------------------
/* OR - you could have........
// -----------------------------------
javax.swing.JFileChooser fc = new javax.swing.JFileChooser(new File("").getAbsolutePath());
fc.showDialog(new JDialog(), "get Passwords");
if (fc.getSelectedFile() != null) {
fileName = fc.getSelectedFile().getAbsolutePath();
}
else {
System.out.println("Process Canceled! Quiting.");
System.exit(0);
}
// -----------------------------------
*/
// Get the Passwords from file:
String[] passwords = getPasswordsFromFile("UserData.txt");
// Display the Passwords retrieved:
System.out.println();
System.out.println("Passwords from file:");
System.out.println("====================");
for (String str : passwords) {
System.out.println(str);
}
If you were to run this code against a file which contains the data you provided within your post,your console window will diplay:
Enter the path of the file (c to cancel): --> userData.txt
Passwords from file:
====================
atbWfKL4etk4U
&i4KZ5wmac566
Even though the file Movie_db.txt isn't empty, I get the following exception:
the text file consists of this:
hank horror 20.0 18 1
public void syncDB(List<Movie> movieList) throws IOException {
Scanner scanner = new Scanner("Movie_db.txt");
BufferedReader reader = null;
try {
String line = null;
String title;
String genre;
double movieDuration;
int ageRestriction;
int id;
while (scanner.hasNext()) {
title = scanner.next();
genre = scanner.next();
movieDuration = scanner.nextDouble();
ageRestriction = scanner.nextInt();
id = scanner.nextInt();
movieList.add(new Movie(title, genre, movieDuration, ageRestriction, id));
}
} catch (Exception e) {
System.out.println("List is empty");
}
}
Considering your path is correct, there is a problem in your code. I'd change this line
Scanner scan = new Scanner("Movie_db.txt");
with this one
Scanner scan = new Scanner(Paths.get("Movie_db.txt"));
The reason is that in your snippet the Scanner only reads the string "Movie_db.txt" and in the second snippet it recognizes as the path to file.
Read Scanner documentation for more info
genre = scan.next(); line is throwing exception because nothing is left to read from file now, which causes catch block to execute.
You are providing a string to Scanner which is a valid input for scanner. Hence, it never reads the file.
Scanner scan = new Scanner(new File("full_path_to_container_dir/Movie_db.txt"));
Please have a look at this blog on how to read from a file using scanner - https://www.java67.com/2012/11/how-to-read-file-in-java-using-scanner-example.html.
This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
I'm trying to print out "YES" for each line in a file (dna.txt) that starts with "ATG" and ends with "TAA", "TAG", or "TGA", and "NO" when this isn't the case. It should stop after the lines in the file are done, but I've created some kind of loop in my code where nothing is printed to the output file (hi.txt) but "NO"...endlessly. I know it should have some "YES"ses too, but my problem is clearly larger than just not reading the tokens of the file correctly.
My code:
public static void Results(Scanner console) throws
FileNotFoundException {
System.out.print("Input file name? ");
Scanner input = new Scanner(new File("dna.txt"));
System.out.print("Output file name: ");
File outputFile = new File("hi.txt");
System.out.println();
PrintStream outputRead = new PrintStream(outputFile);
String isProtein = "NO";
while (input.hasNextLine()) {
String line = input.nextLine().toUpperCase();
Scanner lineScan = new Scanner(line);
while (lineScan.hasNext()) {
if (line.startsWith("ATG")) {
if (line.endsWith("TAA") || line.endsWith("TAG") ||
line.endsWith("TGA")) {
isProtein = "YES";
}
}
}
outputRead.println(isProtein);
}
System.out.println(isProtein);
}
Text file (though it should work with any text file, and it isn't):
protein?
ATGCCACTATGGTAG
protein?
ATgCCAACATGgATGCCcGATAtGGATTgA
protein?
CCATt-AATgATCa-CAGTt
protein?
ATgAG-ATC-CgtgatGTGgg-aT-CCTa-CT-CATTaa
protein?
AtgC-CaacaTGGATGCCCTAAG-ATAtgGATTagtgA
protein?
atgataattagttttaatatcaga-ctgtaa
Do you have any idea where this loop is forming? If so, please just give me hints as to how I should fix this.
Thanks!
Just Modified few lines,
Changes
1.) Commented Scanner lineScan = new Scanner(line);
2.) Need to reset value for isProtein, in loop, for next iteration.
o/p is printed in text file hi.txt. BTW i have used text file for R/W operations so commented out scanner part.
Code
public static void Results() throws FileNotFoundException {
//System.out.print("Input file name? ");
Scanner input = new Scanner(new File("dna.txt"));
//System.out.print("Output file name: ");
File outputFile = new File("hi.txt");
//System.out.println();
PrintStream outputRead = new PrintStream(outputFile);
String isProtein = "NO";
while (input.hasNextLine()) {
String line = input.nextLine().toUpperCase();
//Scanner lineScan = new Scanner(line);
//while (lineScan.hasNext()) {
if (line.startsWith("ATG")) {
if (line.endsWith("TAA") || line.endsWith("TAG") || line.endsWith("TGA")) {
isProtein = "YES";
}
}else{
isProtein = "NO";
}
//}
outputRead.println(isProtein);
isProtein = "NO";
}
//System.out.println(isProtein);
}
Output
NO
YES
NO
YES
NO
NO
NO
YES
NO
YES
NO
YES
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 have a .txt file, which looks like this(just example):
sfafsaf102030
asdasa203040
asdaffa304050
sadasd405060
I am trying to get whole line which contains a specific(given by me) number, for example i have number "203040" and i want to receive "asdasa203040".
I tried something like this:
File file = new File("file.txt");
Scanner sc = new Scanner(file);
String pattern = "(.*)(\\d+)";
Pattern p = Pattern.compile(pattern);
System.out.println(sc.findInLine(pattern));
but it only gives me line with any number and not the one i specified. How to change it?
Thanks.
You don't need to use regex for this. You could just check for the line containing the number you enter:
File file = new File("file.txt");
Scanner sc = new Scanner(file);
Scanner input = new Scanner(System.in);
System.out.println(/*prompt user for input here*/);
String number = input.next();
String line;
while (sc.hasNextLine()) {
line = sc.nextLine();
if (line.contains(number)) {
System.out.println(line);
break;
} else if (!sc.hasNextLine()) {
System.out.println("Line not found.");
}
}