Foolproof user input program using scanner - java

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.

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.

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?

How to use input to create an object

I have a CarModel class that has three fields: name, fuelEconomy, and gasTankSize.
class CarModel {
private String name;
private double fuelEconomy;
private double gasTankSize;
CarModel(String name, double fuelEconomy, double gasTankSize) {
this.name = name;
this.fuelEconomy = fuelEconomy;
this.gasTankSize = gasTankSize;
}
String getName() {
return name;
}
double getFuelEconomy() {
return fuelEconomy;
}
double getGasTankSize() {
return gasTankSize;
}
}
Given the input as a string of text separated by a new line:
MODEL Camry 6.5 58
MODEL Civic 7.5 52
FINISH
How can I create a new object every time the word MODEL is in the input, store the model in an array, use the following words as the data for those fields and end the program when FINISH is in the input?
Inside main method, try doing something like this (Using try with resources):
public static void main(String args[]){
String line;
List<CarModel> cars = new ArrayList<>();
try(Scanner sc = new Scanner(System.in)){
while(sc.hasNextLine()){
line = sc.nextLine();
String[] arr = line.split(" ");
if(arr[0].equalsIgnoreCase("Model")){
cars.add(new CarModel(arr[0], Double.parseDouble(arr[1]), Double.parseDouble(arr[2])));
}else if(arr[0].equalsIgnoreCase("Finish"){
break;
}
}
}catch(ArrayIndexOutOfBoundsException ex){
// do something here!
}catch(Exception ex){
// do something here as well!
}
}
I would use the String.split method. You pass a delimiter, in your case a space character, and then the method chops the string into pieces based on your provided delimeter. Getting the input into your program depends on where the input will be coming from, whether by file or terminal or some other source.
Once you've read a line of input, call String[] values = line.split(" ")
Again, how to read the input depends on where the input is coming from, which you haven't specified.

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.

Java: Checking for changes in a String with BufferedReader

If trying to get user input into a string, using the code:
String X = input("\nDon't just press Enter: ");
and if they did't enter anything, to ask them until they do.
I've tried to check if it's null with while(x==null) but it doesn't work. Any ideas on what I am doing wrong/need to do differently?
input() is:
static String input (String prompt)
{
String iput = null;
System.out.print(prompt);
try
{
BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
iput = is.readLine();
}
catch (IOException e)
{
System.out.println("IO Exception: " + e);
}
return iput;
//return iput.toLowerCase(); //Enable for lowercase
}
In order to ask a user for an input in Java, I would recommend using the Scanner (java.util.Scanner).
Scanner input = new Scanner(System.in);
You can then use
String userInput = input.nextLine();
to retrieve the user's input. Finally, for comparing strings you should use the string.equals() method:
public String getUserInput(){
Scanner input = new Scanner(System.in);
String userInput = input.nextLine();
if (!userInput.equals("")){
//call next method
} else {
getUserInput();
}
}
What this "getUserInput" method does is to take the user's input and check that it's not blank. If it isn't blank (the first pat of the "if"), then it will continue on to the next method. However, if it is blank (""), then it will simply call the "getUserInput()" method all over again.
There are many ways to do this, but this is probably just one of the simplest ones.

Categories

Resources