Path to string in java files - java

In my program I have a .txt file that has some config values in it.
I have my config.txt laid out like this:
Users:
Jeff: 14
Jimmy: 23
Jack: 532
I have code that consists of a scanner, a few variables, and a few printline commands.
I want the user of the program to enter a name, and if the name they enter exists in the config, to return the value, and if the name doesn't exist, add the name to a list and assign it a value.
I know how to create and read and write to files, but how do I write and read under the "Users:" key?
I've done a good bit of research but I haven't been able to figure it out.
EDIT:
I've been messing with some code, and I got this.
//Code used to get the username to read.
Scanner sc = new Scanner(System.in);
String user = new String();
String pass = new String();
//Username Detection
System.out.println("Please enter your username.");
user = sc.nextLine();
System.out.println("User name is: "+user);
try {
readSSDB(user);
} catch (FileNotFoundException e) {
// Do something with `e`
}
//Code used to check the file.
public static void readSSDB(String user) throws FileNotFoundException{
File SSDB = new File("SSDB.txt");
System.out.println("File Reader Loaded Successfully.");
Scanner read = new Scanner(SSDB);
String userRead = read.nextLine();
boolean userFound = false;
while(userFound == false){
if(read.nextLine().contains(user)){
System.out.println("Found user: "+userFound);
}else{
System.out.println("No user '"+user+"' found!");
read.nextLine();
}
}
}
EDIT 2: Realized I said while(userFound = false) instead of while(userFound == false).
Output I get is: "No user 'Jimmy' found! Found instead: 'Jimmy: 23'"
Shouldn't if(read.nextLine().contains(user)){ return true because read.nextLine() is "Jimmy: 23" and user is "Jimmy" so logically speaking "Jimmy: 23" does contain "Jimmy"?

You can read file using nextLine() and
if(scannedLine.contains(name)) {
//return data to the user
} else {
//add user to he config file
}
Have you tried something like this?

Related

Check if string exists in text file

I'm trying to write a method, which checks if a given string exists in a .txt file, but it seems like my if/else statement isn't working correctly.
public void ChcekIfPasswordExsists(String check) throws FileNotFoundException{
BufferedReader reader = new BufferedReader(new FileReader("Passwords.txt"));
Scanner fileScanner = new Scanner(reader);
while(fileScanner.hasNextLine()){
final String line = fileScanner.next();
if(line.contains(check)){
System.out.println("Password for " + check + " already exsits");
break;
}
else{
System.out.println(check + " is usable");
break;
}
}
}
This is where I'm calling the method:
System.out.println("Enter the name of the app or website,\nwhere password is going to be use:");
useCase = s.nextLine();
ChcekIfPasswordExsists(useCase);
I have looked at countless other posts with no effect. No matter what, it seems like the code skips the "if" statement and directly jumps to the "else" statement.
The logic of your while loop should be to iterate over all lines in the file until either you find a match or you hit the end of the file. Consider this version:
public void ChcekIfPasswordExsists(String check) throws FileNotFoundException {
BufferedReader reader = new BufferedReader(new FileReader("Passwords.txt"));
Scanner fileScanner = new Scanner(reader);
boolean flag = false;
while (fileScanner.hasNextLine()) {
final String line = fileScanner.next();
if (line.contains(check)) {
flag = true;
break;
}
}
if (flag) {
System.out.println("Password for " + check + " already exsits");
}
else {
System.out.println(check + " is usable");
}
}
Also, I might be inclined to change the method signature to return a boolean value (true/false). Based on that return value, you can display to the console the message you want.
Side note: If you are actually storing cleartext passwords in a text file, then stop doing that immediately. It is a security hole. Instead, setup a proper database and only store an irreversible hash of the passwords.

JAVA - Incorporating y/n Input to Print Array list to a file

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.

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();

Do while loop meeting one of 2 conditions

I'm trying to use a do while loop to find out whether the user wants to check a dog or a cat into a kennel system in Java. The idea is that they enter either "dog" or "cat" when prompted, and any of entry will result in an error and they will be prompted again to enter the file name.
If "cat" or "dog" has been entered then the equivalent file will be assigned to the program (dogs.txt or cats.txt) and then the system will run and load that data into the program.
Here are the current variables:
private String filename; // holds the name of the file
private Kennel kennel; // holds the kennel
private Scanner scan; // so we can read from keyboard
private String tempFileName;
private String dogsFile = "dogs.txt";
private String catsFile = "cats.txt";
and the method that is causing an issue:
private KennelDemo() {
scan = new Scanner(System.in);
boolean fileNotCorrect = false;
System.out.print("Which animal are you looking to check into the kennel?: " + "\n");
System.out.println("Dog");
System.out.println("Cat");
tempFileName = scan.next();
do {
tempFileName.equals("dog");
filename = dogsFile;
fileNotCorrect = true;
/*tempFileName.equals("cat");
filename = catsFile;
fileNotCorrect = true;*/
}
while(fileNotCorrect = false);
System.out.println("That is not a valid filename, please enter either 'dog' or 'cat' in lowercase.");
And here's what's printed when you run the code:
**********HELLO***********
Which animal are you looking to check into the kennel?:
Dog
Cat
cat
That is not a valid filename, please enter either 'dog' or 'cat' in lowercase.
Using file dogs.txt
It's assigning a file to the program regardless of what's entered and then continues to load the program.
I've tried using catch { but it's not working for some reason, can anybody offer any help?
Thanks!
That's not how do-while is working. You are not even checking.
Use this:
do {
System.out.print("Which animal are you looking to check into the kennel?: " + "\n");
System.out.println("Dog");
System.out.println("Cat");
tempFileName = scan.next();
if(tempFileName.equals("dog") || tempFileName.equals("cat"))
{
filename = tempFileName.equals("dog") ? dogsFile : catsFile;
fileNotCorrect = true;
}else{
System.out.println("That is not a valid filename, please enter either 'dog' or 'cat' in lowercase.");
}
}
while(!fileNotCorrect);

Foolproof user input program using scanner

This method is part of a bigger program which asks for specific user input and i need this method to prompt the user for input until its correct. here is what i have
public static String validName(Scanner input, Scanner histogram) {
String user = "";
String name = input.next();
boolean test = false;
while (histogram.hasNext()) {
user = histogram.next();
if (name.equalsIgnoreCase(user)) {
test = true;
break;
}
else {
test = false;
}
}
if (!test) {
System.out.println("Name not found");
}
return user;
}
Scanner histogram is reading a txt file. So far it works fine, but as it is it only goes through once.
What can i change or add to make it work properly?
Here is a quick fix. Create a temporary Scanner and set it equal to histogram before you run through histogram. If the user is found then validName() will return that user, if not then repeat this function by passing in input and the copy of histogram tmp. This will get the job done but is not the right way to go about this task.
Updated
Create a temporary string and add each user to the string followed by a space. If the check fails then recall the function with an anonymous Scanner constructed with the string of users.
public static String validName(Scanner input, Scanner histogram) {
String user = "";
String name = input.next();
String tmp = "";
boolean test = false;
while (histogram.hasNext()) {
user = histogram.next();
tmp += user + " ";
if (name.equalsIgnoreCase(user)) {
test = true;
break;
}
else {
test = false;
}
}
if (!test) {
System.out.println("Name not found");
user = validName(input, new Scanner(tmp));
}
return user;
}
It may not be a perfect solution, but here's how i would do it: first read the complete histogramm into a hash Table. This allows for very efficient input validation later on:
public static String validName(Scanner input, Scanner histogram) {
HashSet<String> validInputs = new HashSet<>();
// read in histogram
while (histogram.hasNext())
validInputs.add(histogram.next());
// ask for input and repeat if necessary
while (true) {
String userInput = input.next();
if (validInputs.contains(userInput))
return userInput;
System.out.println("invalid input");
}
}
i've not tested this solution but it should work.
Also the histogram is only ever read once. After that only the hash values of the different Strings are compared. Since 2 Strings with the same content should always have the same hash value this should work.
Also this solution does not require any recursion.
You can use the Scanner's findInLine(String pattern) method, try the following:
public static String validName(Scanner input, Scanner histogram) {
String user = "";
String name = input.next();
if(histogram.findInLine(name) != null){
System.out.println("This name exist");//Do what you have to do here
}
else{
System.out.println("Name not found");
user = validName(input, histogram);
}
return user;
}
Take a look at the Scanner Class methods for more information.

Categories

Resources