Akshit Joshi
Akshit Joshi

Reputation: 23

How to find a String in a .txt file and then read the data after it

There are two files, one is userData.txt and the other one is gameData.txt. In my program, I give two options to the user. Login and Register. If the user clicks on the Register option, then I ask for the ID and password they'd like to keep and store them in userData.txt. Then I run a command which generates a random string which will be stored with the user's credentials in userData.txt as well as in the gameData.txt. After the unique token is written in gameData.txt, I will assign 0 coins as default. This is how it will look like:

Akshit, Joshi, 687fd7d1-b2a9-4e4a-bc35-a64ae8a25f5b (in userData.txt)

687fd7d1-b2a9-4e4a-bc35-a64ae8a25f5b, 0 (in gameData.txt)

Now, if a user clicks on Login option, then the program verifies the data from userData.txt. It also reads the unique token after the credentials and then stores it into a variable named uniUserID.

Now comes the part where I am stuck. I compare this uniUserID to the data in the gameData.txt file. The Scanner reads the gameData.txt line by line and compares the uniUserID with it. What I want is, if it finds the ID then it should read the coins after it (which is 0) and store it into a variable named coins. But it throws me an error that goes like, "NoSuchElementException"

Here is the code:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.Scanner;
import java.util.UUID;


public class Verification
{
    static File credentials = new File ("C:\\Users\\user\\IdeaProjects\\Economic Bot\\out\\userData.txt"); //Clarifying filepath
    static String uniUserID = " ";
    static File gameData = new File ("C:\\Users\\user\\IdeaProjects\\Economic Bot\\out\\gameData.txt");

    public boolean Verify (String ID,String Pass)
    {
        String tempName = " ";           //the data read from the .txt file would be stored in these temporary variables
        String tempPass = " ";
        boolean found = false;//declaring some boolean variables so that the do while and if else statements work smoothly
        boolean verified = false;

        try //Try and catch block is initialized in case the file is not found
        {
            do
            {
                Scanner s2 = new Scanner(credentials); //Reading the .txt file
                s2.useDelimiter("[,\n]");// The file reader will stop once it encounters any of the following delimiters
                while (s2.hasNext() && !found)
                {
                    tempName = s2.next();                     //assigning the data read from the file to these variables
                    tempPass = s2.next();
                    uniUserID= s2.next();
                    if (tempName.trim().equals(ID) && tempPass.trim().equals(Pass))//comparing the data read from the file and the data entered by the user
                    {
                        verified = true;
                        found = true;
                    }
                }
            }
            while (found = false);
        }
        catch (Exception ex)
        {
            System.out.println("Error");
        }

        return verified;
    }
    public void Write (String newUser, String newPass) {
        String uniID = " ";
        try {// try catch is used in case the file is not found
            uniID = UUID.randomUUID().toString();
            FileWriter writer = new FileWriter(credentials, true);// initializing the FileWriter, to make sure that it doesn't overwrite true is used so that it appends
            BufferedWriter buffwrite = new BufferedWriter(writer);                    // creating buffered writer object
            buffwrite.write("\n");                          // Writing the new user's credentials into the .txt file
            buffwrite.write(newUser);
            buffwrite.write(",");
            buffwrite.write(newPass);
            buffwrite.write(",");
            buffwrite.write(uniID);
            buffwrite.close();
        } catch (Exception ex) {
            System.out.println("Error");
        }
        try
        {
            FileWriter writer2 = new FileWriter(gameData, true);
            BufferedWriter buffwrite2 = new BufferedWriter(writer2);
            buffwrite2.write("\n");
            buffwrite2.write(uniID);
            buffwrite2.write(",");
            buffwrite2.write("0");
            buffwrite2.close();
        }
        catch(Exception ex)
        {
            System.out.println("Error");
        }
    }

    public static void Game(String uniqueID) throws FileNotFoundException
    {
        Scanner s3 = new Scanner (gameData);
        String waste = " ";
        String coins = " ";
        while (s3.hasNextLine())
        {
            String fileLine = s3.nextLine();
            if(fileLine.contains(uniUserID))
            {
                s3.useDelimiter(("[\n]"));
                s3.skip(uniUserID);
                coins = s3.next();
                
            }
        }
        System.out.println(coins);
    }
    public static void main(String[] args) throws FileNotFoundException {
        Verification obj = new Verification();
        Scanner s1 = new Scanner(System.in);                                                   //Creating scanner object
        boolean end = false;                                    //declaring the variable that will end the do while loop
        do                          //do while loop is used so that the user gets taken to the main menu again and again
        {
            System.out.println("Welcome to the economic bot!");
            System.out.println("Select one option to proceed");
            System.out.println("1. Login");
            System.out.println("2. Register");
            int choice = s1.nextInt(); //accepting user's choice

            switch (choice) {
                case 1:
                    System.out.println("Enter your username:");
                    String userID = s1.next();                                                //taking user credentials
                    System.out.println("Enter your password");
                    String userPass = s1.next();

                    boolean validated = obj.Verify(userID,userPass);

                    if (validated == true) { //if the login details are correct
                        System.out.println("Login Successful!");
                        System.out.println("Redirecting...");
                        System.out.println();
                        end = true;
                        Game(uniUserID);
                    }
                    else { //if the details entered are wrong
                        System.out.println("Login failed! Possibly due to wrong user credentials.");
                        System.out.println("Please try again!");
                    }
                    break;

                case 2:
                    System.out.println("Enter the username you'd like to keep:");
                    String regUserID = s1.next(); //accepting user details
                    System.out.println("Enter the password:");
                    String regUserPass = s1.next();

                    obj.Write(regUserID,regUserPass);
                    break;

                default:
                    System.out.println("Invalid Option chosen.");              // In case the user enters a wrong choice
            }
        }
        while (!end); // condition for the initial do loop
    }
}

Upvotes: 2

Views: 94

Answers (2)

Paul Kocian
Paul Kocian

Reputation: 529

Change the Game() method to this:

{
        Scanner s3 = new Scanner (gameData);
        String waste = " ";
        String coins = " ";
        while (s3.hasNextLine())
        {
            String fileLine = s3.nextLine();
            if(fileLine.contains(uniUserID))
            {
                coins = fileLine.split(",")[1];
                break;
            }
        }
        System.out.println(coins);
    }

Simply split the line in 2 parts using a divider (,) and get the second part where are contained the coins

To add more coins, use a BufferedWriter:

BufferedWriter writer = new BufferedWriter(new FileWriter(gameData));
writer.write(uniId+","+newCoins);
writer.close();

Important: remove true from the FileWriter object because you are overwriting and not appending

Upvotes: 2

Prog_G
Prog_G

Reputation: 1615

Try the below code :

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.Scanner;
import java.util.UUID;


public class Verification {
    static File credentials = new File("C:\\Users\\user\\IdeaProjects\\Economic Bot\\out\\userData.txt"); //Clarifying filepath
    static String uniUserID = " ";
    static File gameData = new File("C:\\Users\\user\\IdeaProjects\\Economic Bot\\out\\gameData.txt");

    public boolean Verify(String ID, String Pass) {
        String tempName = " ";           //the data read from the .txt file would be stored in these temporary variables
        String tempPass = " ";
        boolean found = false;//declaring some boolean variables so that the do while and if else statements work smoothly
        boolean verified = false;

        try //Try and catch block is initialized in case the file is not found
        {
            do {
                Scanner s2 = new Scanner(credentials); //Reading the .txt file
                s2.useDelimiter("[,\n]");// The file reader will stop once it encounters any of the following delimiters
                while (s2.hasNext() && !found) {
                    tempName = s2.next();                     //assigning the data read from the file to these variables
                    tempPass = s2.next();
                    uniUserID = s2.next();
                    if (tempName.trim().equals(ID) && tempPass.trim().equals(Pass))//comparing the data read from the file and the data entered by the user
                    {
                        verified = true;
                        found = true;
                    }
                }
            }
            while (found = false);
        } catch (Exception ex) {
            System.out.println("Error");
        }

        return verified;
    }

    public void Write(String newUser, String newPass) {
        String uniID = " ";
        try {// try catch is used in case the file is not found
            uniID = UUID.randomUUID().toString();
            FileWriter writer = new FileWriter(credentials, true);// initializing the FileWriter, to make sure that it doesn't overwrite true is used so that it appends
            BufferedWriter buffwrite = new BufferedWriter(writer);                    // creating buffered writer object
            buffwrite.write("\n");                          // Writing the new user's credentials into the .txt file
            buffwrite.write(newUser);
            buffwrite.write(",");
            buffwrite.write(newPass);
            buffwrite.write(",");
            buffwrite.write(uniID);
            buffwrite.close();
        } catch (Exception ex) {
            System.out.println("Error");
        }
        try {
            FileWriter writer2 = new FileWriter(gameData, true);
            BufferedWriter buffwrite2 = new BufferedWriter(writer2);
            buffwrite2.write("\n");
            buffwrite2.write(uniID);
            buffwrite2.write(",");
            buffwrite2.write("0");
            buffwrite2.close();
        } catch (Exception ex) {
            System.out.println("Error");
        }
    }

    public static void Game(String uniqueID) throws FileNotFoundException {
        Scanner s3 = new Scanner(gameData);
        String waste = " ";
        String coins = " ";
        while (s3.hasNextLine()) {
            String fileLine = s3.nextLine();
            if (fileLine.contains(uniUserID)) {
                /*s3.useDelimiter(("[\n]"));
                s3.skip(uniUserID);
                coins = s3.next();*/
                coins = fileLine.split(",")[1];
                break;
            }
        }
        System.out.println(coins);
    }

    public static void main(String[] args) throws FileNotFoundException {
        Verification obj = new Verification();
        Scanner s1 = new Scanner(System.in);                                                   //Creating scanner object
        boolean end = false;                                    //declaring the variable that will end the do while loop
        do                          //do while loop is used so that the user gets taken to the main menu again and again
        {
            System.out.println("Welcome to the economic bot!");
            System.out.println("Select one option to proceed");
            System.out.println("1. Login");
            System.out.println("2. Register");
            int choice = s1.nextInt(); //accepting user's choice

            switch (choice) {
                case 1:
                    System.out.println("Enter your username:");
                    String userID = s1.next();                                                //taking user credentials
                    System.out.println("Enter your password");
                    String userPass = s1.next();

                    boolean validated = obj.Verify(userID, userPass);

                    if (validated == true) { //if the login details are correct
                        System.out.println("Login Successful!");
                        System.out.println("Redirecting...");
                        System.out.println();
                        end = true;
                        Game(uniUserID);
                    } else { //if the details entered are wrong
                        System.out.println("Login failed! Possibly due to wrong user credentials.");
                        System.out.println("Please try again!");
                    }
                    break;

                case 2:
                    System.out.println("Enter the username you'd like to keep:");
                    String regUserID = s1.next(); //accepting user details
                    System.out.println("Enter the password:");
                    String regUserPass = s1.next();

                    obj.Write(regUserID, regUserPass);
                    break;

                default:
                    System.out.println("Invalid Option chosen.");              // In case the user enters a wrong choice
            }
        }
        while (!end); // condition for the initial do loop
    }
}

Suggestions:

  1. Try adding a new line (\n) character at the end of every line not at the beginning because it is adding a blank line at the start of the files.
  2. Break the loop if the id matching is found.

Upvotes: 2

Related Questions