This is a workout program which asks the user for his name and creates a file where all his data is stored. Inside that file, there are 3 literals: fullName, age and experience.
The feature which is not working is printing out all the information inside the file, when the user enters his username.
So, if I had an account called Bob, and I entered Bob in the console, I should get my fullName, my Age and my experience. (which had already been stored in the file before).
This is my method for reading data from the file and printing it out. I ran it several times with the debugger but it only reads the title of the file and not the information inside it. The result is "Could not find file". How do I fix this? Thanks.
public void getInfo(String nameIn) {
Scanner keyboard = new Scanner(System.in);
Scanner x;
out.println("\nWhat's your account's name?");
nameIn = keyboard.nextLine();
//It reads the title of the file, not the data inside it.
try {
x = new Scanner(nameIn);
if (x.hasNext()) {
String a = x.next();
String b = x.next();
String c = x.next();
out.println("Account data for user: " + nameIn);
out.printf("Name: %s \tAge: %s \tExperience: %s", a, b, c);
}
} catch (Exception e) {
out.println("Could not find file.");
}
Here's the rest of the code in that class.
public class createMember {
public String name;
private String fullName;
private String age;
private String experience;
private Formatter x;
public createMember(String name) {
this.name = name;
}
public void setMembership() {
try {
x = new Formatter(name);
out.println("File with name \"" + name + "\" has been created!");
} catch (Exception e) {
out.println("Could not create username.");
}
}
public void setInfo() {
Scanner keyboard = new Scanner(System.in);
out.println("Enter your Full Name");
fullName = keyboard.nextLine();
out.println("Enter your Age");
age = keyboard.nextLine();
out.println("Enter your lifting experience");
experience = keyboard.nextLine();
x.format("Name: %s \tAge: %s \tExperience: %s", fullName, age, experience);
}
public void getInfo(String nameIn) {
Scanner keyboard = new Scanner(System.in);
Scanner x;
System.out.println("\nWhat's your account's name?");
nameIn = keyboard.nextLine();
//It reads the title of the file, not the data inside it.
try {
File file = new File("nameOfYourFile.txt");
x = new Scanner(file);
while (x.hasNextLine())) {
String line = x.nextLine();
if (line.contains(nameIn)){ // or you can use startsWith()
// depending how your text is formatted
String[] tokens = line.split(" ");
String a = tokens[0].trim();
String b = tokens[1].trim();
String c = tokens[2].trim();
System.out.println("Account data for user: " + nameIn);
System.out.printf("Name: %s \tAge: %s \tExperience: %s", a, b, c);
}
}
} catch (FileNotFoundException e) {
System.out.println("Could not find file.");
}
You have to pass an InputStream to your scanner, not the name of the file.
final String pathToFile = "/my/dir/" + nameIn;
x = new Scanner(new FileInputStream(new File(pathToFile)));
Even though I must say I have never seen this approach to read a file line by line. I usually do this using a BufferedLineReader.
Checking hasNext() once and invoking next() thrice is not a good design. Any of the next() calls after the first might fail if no more tokens are available.
So, one possibility is that you're running out of tokens after the first x.next() call.
Another possibility is that the given pathname nameIn does not correspond to any file on the file system.
Also, you should be catching exception using more specific types instead of Exception. If you had done that, you would have known which of the new Scanner(file) or x.next() threw exception.
Related
I have 3 different classes. I have to get user input by using BufferedReader but by using toString method. Below is the codes in my User2 (one of the classes).
How to call everything that user have input in the toString, at main function ? if i have to use object, how?
//in User2 class
#Override
public String toString() {
try {
//getting input using BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter customer name: ");
this.name = br.readLine();
System.out.print("Enter customer address: ");
this.address = br.readLine();
System.out.print("Enter customer contact no: ");
this.hp = br.readLine();
} catch (IOException e) {
return "";
}
return "" ;
}
I only know to print out everything in to string by using
System.out.println(u2.toString());
Thanks in advance.
You shouldn't be defining an Object when you call it's toString() method, especially when you are using Scanner to read data from System.in. Rather, when you read data you should use the data to instantiate the Object. I haven't seen the layout of your classes, but I have a feeling you don't fully understand what Objects are.
The following Class defines a User; The user has a name, address and hp. You create a new User Object once you have this information as, in this situation, it doesn't make sense to have an Object that doesn't represent a known User.
The toString() method has been overriden such that it produces a String that is representative of what the Object describes - You should adjust this to how you want the Object to be representative when the Object to converted to a String. Read more about the toString method and it's purpose.
The static User userFromInput() method does what you want. As it is static, you may invoke it on the Class, meaning you don't have to instantiate an Object. This method takes input from the user (name, address and hp), instantiates a new User object and returns it.
public class User {
private String name;
private String address;
private String hp;
public User (String name, String address, String hp) {
this.name = name;
this.address = address;
this.hp = hp;
}
#Override
public String toString() {
return name + " : " + address + " : " + hp;
}
public static User userFromInput() {
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
System.out.print("Enter customer name: ");
String name = br.readLine();
System.out.print("Enter customer address: ");
String address = br.readLine();
System.out.print("Enter customer contact no: ");
String hp = br.readLine();
return new User(name, address, hp);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Hence, you should call for the user to input data and then print the Object to console using the following to lines:
User user1 = User.userFromInput();
System.out.println(user1.toString());
My objective is to create a method in which a user inputs their first name and last name, and with this information a .txt file will be created and named using the first initial of the first name and the last name. For example if user enter Marcus Simmon, the text file created should be named "MSimmon.txt" and how would I be able to return this file name. Thank you in advance. This is my code so far...
public static String GetUserInfo() {
// complete with your code of the method GetUserInfo
Scanner input = new Scanner(System.in);
System.out.println("Please enter your first name: ");
char initial = input.next().charAt(0);
System.out.println("Please enter your last name: ");
String lastName = input.nextLine();
try{
FileWriter x = new FileWriter(initial + lastName + ".txt");
}
catch(IOException e){
System.out.println("ERROR");
}
}
I'm creating a menu based console application using Java. I have a class that allows the user to sign up by inputting their information. This information is written to a file that is appended each time a new user is entered.
I would like to have a login function, but I'm having trouble figuring out how to read the file and only match the user input to the first two columns ID;Password.
Once they match the user input, I'll be able to continue to the next menu.
My text file looks like this:
ID;Password;FirstName;LastName;Email
admin;1234;adminFirst;adminLast;adminMail#admin.com
Here's my Login class as well. I created an array for user input, just in case that would be useful:
public class Log_In extends Main_Menu {
public void logging_in(){
Scanner in = new Scanner(System.in);
System.out.println("Please enter your login information!");
String [] log_in_array = new String[2];
String ID, password;
System.out.print("ID: ");
ID = in.next();
System.out.print("Password: ");
password = in.next();
//Stores the ID and PASSWORD to the array. Now we will compare the array to the txt file to find a match
//Must match FIELD_ONE;FIELD_TWO
log_in_array [0] = ID;
log_in_array [1] = password;
in.close();
}
}
you can write helper method to read your text file and compare id and password provided by user, like following.
// The name of the file to open.
static String fileName = "myTextFliel.txt";
public static boolean myHelper(String id, String password) {
// This will reference one line at a time
String line = null;
boolean retVal= false;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader =
new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
//create a token based on
String [] token=line.split(";");
// because you know first and second word of each line in
// given file is id and password
if (token[0].equals(id) && token[1].equals(password)){
retVal=true;
return retVal;
}
}
// Always close files.
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
return retVal;
}
public void logging_in(){
Scanner in = new Scanner(System.in);
System.out.println("Please enter your login information!");
String [] log_in_array = new String[2];
String ID, password;
System.out.print("ID: ");
ID = in.next();
System.out.print("Password: ");
password = in.next();
//Stores the ID and PASSWORD to the array. Now we will compare the array to the txt file to find a match
//Must match FIELD_ONE;FIELD_TWO
log_in_array [0] = ID;
log_in_array [1] = password;
// Here you can call your helper method.
boolean foundMe =myHelper(log_in_array [0],log_in_array [1])
if (foundMe==true){
//do whatever u want to do
}
in.close();
}
With little bit of more work you can ignore header line.
If the structure of the file is something like this
username pass data data
username pass data data
username pass data data... and so on
you can read the file into an ArrayList, but skip everything that isn't a user name or pass like so
ArrayList<String> userinfo = new ArrayList();
while (input.hasNext()){ //input is a Scanner object that is your file
userinfo.add(input.next());//username
userinfo.add(input.next());//pass
input.next();//skip
input.next();//skip
}
every username and password will be in pairs like this within the
ArrayList
(username, pass, username, pass, username, pass,...)
Then to see if a username and password matches
int index = userinfo.indexOf(ID);
if (userinfo.get(index+1).equals(password))//the password comes right after the username in the list
return true;
I'm assuming this is for practice, you would typically use a database of some sort for user name and passwords
I am working on student registration system. I have a text file with studentname, studentnumber and the student's grade stored in every line such as:
name1,1234,7
name2,2345,8
name3,3456,3
name4,4567,10
name5,5678,6
How can I search a name and then return the whole sentence? It does not get any matches when looking for the name.
my current code look like this:
public static void retrieveUserInfo()
{
System.out.println("Please enter username"); //Enter the username you want to look for
String inputUsername = userInput.nextLine();
final Scanner scanner = new Scanner("file.txt");
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if(lineFromFile.contains(inputUsername)) {
// a match!
System.out.println("I found " +inputUsername+ " in file " ); // this should return the whole line, so the name, student number and grade
break;
}
else System.out.println("Nothing here");
}
The problem is with Scanner(String) constructor as it:
public Scanner(java.lang.String source)
Constructs a new Scanner that produces values scanned from the
specified string.
Parameters: source - A string to scan
it does not know anything about files, just about strings. So, the only line that this Scanner instance can give you (via nextLine() call) is file.txt.
Simple test would be:
Scanner scanner = new Scanner("any test string");
assertEquals("any test string", scanner.nextLine());
You should use other constructor of Scanner class such as:
Scanner(InputStream)
Scanner(File)
Scanner(Path)
You already have the variable that holds the whole line. Just print it like this:
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if(lineFromFile.contains(inputUsername)) {
// a match!
System.out.println("I found " +lineFromFile+ " in file " );
break;
}
else System.out.println("Nothing here");
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm trying to create a java program that recieves a .txt file and plays the game, then prints it all into a new file (named by the user). I've reached the point where all the words have been chosen but am getting a NoSuchElementException message after that. I have a pretty basic knowledge of java and absolutely no clue how to proceed. Anyone have suggestions?
import java.io.*;
import java.util.*;
public class MadLibs {
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
intro();
//in order to create the output file first prompts user to decide
//whether they want to create a mad-lib, view their mad-lib or quit
//if 'c' is selected then while loop is exited
String action = "c";
String fileName = "fileName";
while (action.equals("c")) {
System.out.print("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
action = console.nextLine();
action = action.toLowerCase();
File file = new File(fileName);
System.out.print("Input file name: ");
while (!file.exists()) {
fileName = console.nextLine();
file = new File(fileName);
if (!file.exists()) {
System.out.print("File not found. Try again: ");
}
}
//asks for a file to read from for the mad-lib game
//and creates file (named by user) to input the information
System.out.print("Output file name: ");
String outputName = console.nextLine();
System.out.println();
File outputFile = new File(outputName);
PrintStream output = new PrintStream(outputFile);
Scanner tokens = new Scanner(file);
while (tokens.hasNext()) {
String token = tokens.next();
//calls the returned placeHolder
String placeHolder = placeHolder(console, tokens, token);
String newWord = madLib(console, token, placeHolder);
//copies each token and pastes into new output file
}
}
while (action.equals("v")) {
System.out.print("Input file name: ");
fileName = console.nextLine();
File outputFile = new File(fileName);
if (!outputFile.exists()) {
System.out.print("File not found. Try again: ");
fileName = console.nextLine();
} else {
PrintStream output = new PrintStream(outputFile);
output = System.out;
}
}
while (action.equals("q")) {
}
}
public static String madLib(Scanner console, String token, String
placeHolder) throws FileNotFoundException{
String word = placeHolder.replace("<", "").replace(">", ": ").replace("-",
" ");
String startsWith = String.valueOf(word.charAt(0));
if (startsWith.equalsIgnoreCase("a") || startsWith.equalsIgnoreCase("e")
||
startsWith.equalsIgnoreCase("i") || startsWith.equalsIgnoreCase("o")
||
startsWith.equalsIgnoreCase("u")) {
String article = "an ";
System.out.print("Please type " + article + word);
String newWord = console.next();
return newWord;
} else {
String article = "a ";
System.out.print("Please type " + article + word);
String newWord = console.next();
return newWord;
}
}
public static String placeHolder(Scanner console, Scanner tokens, String
token) throws FileNotFoundException {
while(!(token.startsWith("<") && token.endsWith(">"))) {
//not a placeholder!
//continue reading file
token = tokens.next();
}
//outside of this while loop = found a placeholder!!
String placeHolder = token;
//returns placeholder to main
return placeHolder;
}
//method prints out the introduction to the game
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.");
System.out.println();
}
}
Also am currently using a file called simple.txt with the text:
I wannabe a <job> when I grow up.
Just like my dad.
Life is <adjective> like that!
This is the full error message:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at MadLibs.placeHolder(MadLibs.java:96)
at MadLibs.main(MadLibs.java:46)
I ran your code and got a NoSuchElementException instead of a NoSuchFileException. To circumvent this exception you need to check if there are any more tokens while in the method placeHolder. Otherwise, after entering every placeholder you would still search for the next placeholder token although there is no next().
Change your code to:
while(tokens.hasNext() && !(token.startsWith("<") && token.endsWith(">"))) {
//not a placeholder!
//continue reading file
System.out.println(token);
token = tokens.next();
}