Hello,

I am making a authentication software, and this is the code for the Username panel.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Scanner;
import java.util.ArrayList;
import java.io.*;

public class Username {

    private static String username;
    private static char[] actualUsername;

    public Username () {
        final JFrame frame = new JFrame("Username");
        JLabel jlbusername = new JLabel("Enter the username: ");
        JTextField userfield = new JTextField(10);
        userfield.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JTextField input = (JTextField)e.getSource();
                String USERNAMEINPUT = input.getText();
                char[] charusername = USERNAMEINPUT.toCharArray();
                if (isUsernameCorrect(charusername)) {
                    JOptionPane.showMessageDialog(frame, "Success! You typed the right password.");
                    frame.setVisible(false);
                } else {
                    JOptionPane.showMessageDialog(frame, "Invalid password. Try again.",
                        "Error Message", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        JPanel jplContentPane = new JPanel(new BorderLayout());
        jplContentPane.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        jplContentPane.add(jlbusername, BorderLayout.WEST);
        jplContentPane.add(userfield, BorderLayout.CENTER);

        frame.setContentPane(jplContentPane);
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) { System.exit(0); }
        });
        frame.pack();
        frame.setVisible(true);
    }

    private static boolean isUsernameCorrect(char[] inputUsername) {
        String StringinputUsername = new String(inputUsername);
        String ActualUsernameString = "";
        try{

        Scanner usernameScan = new Scanner(new File("data/usernames.txt"));
        ArrayList <String> storedusernames = new ArrayList<String>();
        while (usernameScan.hasNext()){
        storedusernames.add(usernameScan.nextLine());
        }
        for (int i = 0; i < storedusernames.size() || !StringinputUsername.equals(ActualUsernameString);i++)
        {
        ActualUsernameString = usernameScan.nextLine();
        }
        }catch (FileNotFoundException e)
        {
            System.out.println("Data Not Found!");
        }
        actualUsername = ActualUsernameString.toCharArray();
        if (inputUsername.length != actualUsername.length)
            return false;           //Return false if lengths are unequal
        for (int i = 0;  i < inputUsername.length; i ++)
            if (inputUsername[i] != actualUsername[i])
                return false;
        return true;
    }



}

It reads from a file called usernames.txt :

//start
hello
test

//end

However, when I run it from another class with a main method, the frame shows and everything works, until I input the username into the textfield. The command prompt displays this:

Exception in thread "AWT-EventQueue-0" java.util.NoSuchElementException: No line
     found
            at java.util.Scanner.nextLine(Scanner.java:1585)
            at Username.isUsernameCorrect(Username.java:58)
            at Username.access$000(Username.java:8)
            at Username$1.actionPerformed(Username.java:23)
            at javax.swing.JTextField.fireActionPerformed(JTextField.java:508)
            at javax.swing.JTextField.postActionEvent(JTextField.java:721)
            at javax.swing.JTextField$NotifyAction.actionPerformed(JTextField.java:8
    36)
            at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1664)
            at javax.swing.JComponent.processKeyBinding(JComponent.java:2879)
            at javax.swing.JComponent.processKeyBindings(JComponent.java:2926)
            at javax.swing.JComponent.processKeyEvent(JComponent.java:2842)
            at java.awt.Component.processEvent(Component.java:6282)
            at java.awt.Container.processEvent(Container.java:2229)
            at java.awt.Component.dispatchEventImpl(Component.java:4861)
            at java.awt.Container.dispatchEventImpl(Container.java:2287)
            at java.awt.Component.dispatchEvent(Component.java:4687)
            at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.ja
    va:1895)
            at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboard
    FocusManager.java:762)
            at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeybo
    ardFocusManager.java:1027)
            at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeybo
    ardFocusManager.java:899)
            at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFoc
    usManager.java:727)
            at java.awt.Component.dispatchEventImpl(Component.java:4731)
            at java.awt.Container.dispatchEventImpl(Container.java:2287)
            at java.awt.Window.dispatchEventImpl(Window.java:2719)
            at java.awt.Component.dispatchEvent(Component.java:4687)
            at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:723)
            at java.awt.EventQueue.access$200(EventQueue.java:103)
            at java.awt.EventQueue$3.run(EventQueue.java:682)
            at java.awt.EventQueue$3.run(EventQueue.java:680)
            at java.security.AccessController.doPrivileged(Native Method)
            at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDo
    main.java:76)
            at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDo
    main.java:87)
            at java.awt.EventQueue$4.run(EventQueue.java:696)
            at java.awt.EventQueue$4.run(EventQueue.java:694)
            at java.security.AccessController.doPrivileged(Native Method)
            at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDo
    main.java:76)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:693)
            at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThre
    ad.java:244)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.
    java:163)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
    ad.java:151)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147)

            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139)

            at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)

Any ideas how to solve this? Thanks.

this is method description of next() in Scanner class :
String next()
Finds and returns the next complete token from this scanner and returns it as a string; a token is usually ended by whitespace such as a blank or line break. If not token exists, **NoSuchElementException ** is thrown.

i think the format of the datatable may be not in the proper way...
please check it once and reply the answer .. so that we will find another solution for your problem if this is not a solutionn.......
and can you tell me the data format of the users table which are storedi the text file?
regards
radha krihsna

You read the file into the arraylist the search (OK), then search the arraylist for the desired value, but when you do that search you use the code for file reading (nextLine) rather than an ArrayList method to eccess the next element in the arraylist.

Ok, I made a change to th isUsernameCorrect method and it works now:

private static boolean isUsernameCorrect(char[] inputUsername) {
        String StringinputUsername = new String(inputUsername);
        String ActualUsernameString = "";
        try{
        Scanner usernameScan = new Scanner(new File("data/usernames.txt"));
        ArrayList <String> storedusernames = new ArrayList<String>();
        while (usernameScan.hasNext()){
        storedusernames.add(usernameScan.nextLine());
        }
        int UsernameLength = storedusernames.size();
        for (int a = 0; a < UsernameLength; a++) {
        if (storedusernames.get(a).contains(StringinputUsername)) {
        return true;
    }
    else{
    }
        }

        }catch (FileNotFoundException e)
        {
            System.out.println("Data Not Found!");
        }

        return false;
    }

If I type "hello" or "test", it says "Success! ...." and if I do otherwise, it shows an error message. BUT... if I type a part of the stored usernames like "hel" or "tes", it still says "Success! ..." Can anyone help? Thanks!!

Never mind, I added a length check and it works perfectly now!! Thanks for all your help.

private static boolean isUsernameCorrect(char[] inputUsername) {
        String StringinputUsername = new String(inputUsername);
        String ActualUsernameString = "";
        try{
        Scanner usernameScan = new Scanner(new File("data/usernames.txt"));
        ArrayList <String> storedusernames = new ArrayList<String>();
        while (usernameScan.hasNext()){
        storedusernames.add(usernameScan.nextLine());
        }
        int UsernameLength = storedusernames.size();
        for (int a = 0; a < UsernameLength; a++) {
        if (storedusernames.get(a).contains(StringinputUsername) && storedusernames.get(a).length() == StringinputUsername.length()) {
        return true;
    }
    else{
    }
        }

            }catch (FileNotFoundException e)
        {
            System.out.println("Data Not Found!");
        }

        return false;
    }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.