Do while loop meeting one of 2 conditions - java

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

Related

Path to string in java files

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?

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.

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.

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.

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