0

I have a problem with if-statement. There is a file with the line admin.admin. I break the line into points and store it in an array. The first element of the array is the login. The first element of the array is compared with the input value (inputLogin = "admin" in the code String inputLogin = textField[0].getText()). I have to get the true, but I'm actually getting a false

first java file

package classPackage;

import java.awt.*;

import javax.swing.*;

public class ClassAuthorization extends JFrame {

private static final int WIDTH_AUTH = 400;
private static final int HEIGHT_AUTH = 500;

private JLabel[] label = new JLabel[3];
public JTextField[] textField = new JTextField[1];
public JPasswordField[] passwordField = new JPasswordField[1];
protected JButton[] button = new JButton[2];

private String[] text = {"Авторизуйтесь", "Логин:", "Пароль:", "Вход", "Я - участник"};

private Integer[] coordXAuth = {110, 39, 25, 110, 110, 25, 25};
private Integer[] coordYAuth = {20, 120, 170, 125, 175, 225, 285};

private Integer[] widthAuth = {200, 100, 100, 220, 220, 305, 305};
private Integer[] heightAuth = {30, 30, 30, 27, 26, 40, 40};

private Integer[] sizeFont = {24, 22, 22, 18, 18, 18, 18};

public ClassAuthorization() {

    setSize(WIDTH_AUTH, HEIGHT_AUTH);
    setLocationRelativeTo(null);

    JPanel panel = new JPanel();
    getContentPane().setLayout(null);
    setPanel(panel, 10, 11, 400, 500);
    getContentPane().add(panel);

    for (int i = 0; i < 3; i++) {
        if (i < 1) {
            addLabel(i, panel);
            addTextField(i, panel);
            addPasswordField(i, panel);
            addButton(i, panel);
        }
        else if (i == 1) {
        addLabel(i, panel);
        addButton(i, panel);
        }
        else if (i > 1) {
            addLabel(i, panel);
        }
    }

}

private JPanel setPanel (JPanel panel, int x, int y, int width, int height) {   

    panel.setBounds(x, y, width, height);
    panel.setLayout(null);
    return panel;

}

private void addLabel(int i, JPanel panel) {

    label[i] = new JLabel();
    label[i].setText(text[i]);
    label[i].setBounds(coordXAuth[i], coordYAuth[i], widthAuth[i], heightAuth[i]);
    label[i].setFont(new Font("Segoe UI Light", Font.PLAIN, sizeFont[i]));
    panel.add(label[i]);

}

private void addTextField(int i, JPanel panel) {

    textField[i] = new JTextField();
    textField[i].setBounds(coordXAuth[i + 3], coordYAuth[i + 3], widthAuth[i + 3], heightAuth[i + 3]);
    textField[i].setFont(new Font("Segoe UI Light", Font.PLAIN, sizeFont[i + 3]));
    panel.add(textField[i]);
}

private void addPasswordField(int i, JPanel panel) {

    passwordField[i] = new JPasswordField();
    passwordField[i].setBounds(coordXAuth[i + 4], coordYAuth[i + 4], widthAuth[i + 4], heightAuth[i + 4]);
    panel.add(passwordField[i]);

}

private void addButton(int i, JPanel panel) {

    button[i] = new JButton();
    button[i].setText(text[i + 3]);
    button[i].setBounds(coordXAuth[i + 5], coordYAuth[i + 5], widthAuth[i + 5], heightAuth[i + 5]);
    button[i].setFont(new Font("Segoe UI Light", Font.PLAIN, sizeFont[i + 5]));
    panel.add(button[i]);
}

}

Second java file

package mainPackage;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;

import javax.swing.JButton;

import classPackage.ClassAuthorization;

public class Authorization extends ClassAuthorization {

private String path = "src/putFile/Account.txt";

public Authorization() {
    checkAccess(button[0]);
}

private void checkAccess(JButton button) {

    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            File file = new File(path);
            Scanner scanner;

            try {

                scanner = new Scanner(file);

                do {

                    String account = scanner.nextLine();
                    String[] parts = account.split("\\.");
                    String login = parts[0].trim();
                    String pass = parts[1];
                    char [] password = pass.toCharArray();
                    String inputLogin = textField[0].getText();
                    char[] inputPassword = passwordField[0].getPassword();
                    System.out.println(inputPassword);

                    if (inputLogin.equals(login) == true && Arrays.equals(password, inputPassword) == true) { // BAD

                         System.out.println("GOOD");

                        break; 
                    }
                    else {

                        System.out.println("BAD");
                    }
                } while (scanner.hasNextLine() == true);
            }
            catch (FileNotFoundException NotFoundFile) {
                NotFoundFile.printStackTrace();
            }
        }
    });
}


public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Authorization frame = new Authorization();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}


}

Account.txt

admin.admin
damirqasha
  • 81
  • 6
  • 1
    replace `toString().valueOf(` with `String.valueOf(` and try again? – Darshan Mehta Jun 05 '17 at 18:34
  • are you sure this is how you get the input: ***toString().valueOf(passwordField[0].getPassword());*** – ΦXocę 웃 Пepeúpa ツ Jun 05 '17 at 18:35
  • Apart from the 2 comments above, you shouldn't be trying to convert `JPasswordField`'s `getPassword()` char array to String. [Here](https://stackoverflow.com/a/9798093/2180785)'s a good explanation by Hovercraft. It's due to security reasons – Frakcool Jun 05 '17 at 18:39
  • @Frakcool, im use Arrays.equals for password - it is good idea, but i have problem with inputLogin.equals(login) – damirqasha Jun 05 '17 at 19:13
  • @DarshanMehta Did not work out :( – damirqasha Jun 05 '17 at 19:14
  • @ΦXocę웃Пepeúpaツ I get what I want, but do I do the right thing? – damirqasha Jun 05 '17 at 19:15
  • maybe some whitespaces in one of your strings? Did you try to trim() them? – Davis Molinari Jun 05 '17 at 19:19
  • I'm sorry, I didn't understand quite well what you said with `inputLogin.equals(login)` – Frakcool Jun 05 '17 at 19:25
  • @Frakcool, soory for my english. `inputLogin.equals(login)` give me false - need true – damirqasha Jun 05 '17 at 19:45
  • And what is `login`? Please post a proper [mcve] that demonstrates your issue. I mean, what `login` and what `inputLogin` contain? – Frakcool Jun 05 '17 at 19:46
  • @DavisMolinari im make string login to char[] and i get whitespace, but in the beginning im make login.trim(); I do not understand where this whitespace comes from – damirqasha Jun 05 '17 at 20:05
  • Show **how** you're doing the `trim()` – Frakcool Jun 05 '17 at 20:07
  • @Frakcool `String log = parts[0].trim(); char [] login = log.toCharArray();` and i get in char massive = [,a,d,m,i,n] whitespace in the beginning massive – damirqasha Jun 05 '17 at 20:27
  • Please [edit] your question and post a MCVE – Frakcool Jun 05 '17 at 20:57
  • @Frakcool im change Q – damirqasha Jun 05 '17 at 21:13
  • Did you read the link I posted about the MCVE? That's **NOT** a MCVE, re(read) the link and post a valid [mcve] that demonstrates the problem. It still doesn't show the `trim` part... – Frakcool Jun 05 '17 at 21:15
  • 1
    @Frakcool I do not understand why this is not the MCVE for you. For me it is brief and understandable. I do not understand why you can not understand that the login is not equal to the input login. I said that such a login, I said that such an input login. The trim method is not needed, because it does not help. Can be I give you a link to the repository? – damirqasha Jun 05 '17 at 21:26
  • I understand that both are not equal but you're not posting the relevant code so we can test it, and I don't have time to create a GUI from scratch to see the error you have. If you want my help post a MCVE, your code is a snippet and is far from being Complete, also it's not Verifiable because it's not complete. I won't see any repository, only a proper MCVE posted in this question as code-formatted text – Frakcool Jun 05 '17 at 21:30
  • @Frakcool I put out the necessary code to run – damirqasha Jun 05 '17 at 21:53
  • Please see my answer below – Frakcool Jun 06 '17 at 15:47

1 Answers1

2

Before I go into a real answer to your question, I must give some advices:

  1. Avoid extending JFrame, as JFrame is a rigid container, instead build your GUI towards JPanels and instantiate a JFrame, take the answers in: Extends JFrame vs. creating it inside the program as a reference

  2. Why create a whole array for these lines:

    public JTextField[] textField = new JTextField[1];
    public JPasswordField[] passwordField = new JPasswordField[1];
    

    if you're going to have a single element, an array is not needed.

  3. The following lines, make no sense to me, because there's no need to wrap the numbers as Integer when you could use the primitive int, this affects the performance of the program.

    private Integer[] coordXAuth = {110, 39, 25, 110, 110, 25, 25};
    private Integer[] coordYAuth = {20, 120, 170, 125, 175, 225, 285};
    
  4. getContentPane().setLayout(null); STOP using null-layout! Please read carefully how to use the different layout managers, you can combine them and create cool GUIs.

    Swing was designed to use them, because it has to deal with different OS, PLAFs, screen sizes and resolutions, pixel perfect GUIs are an illusion, here is an example of what happens when you use them.

    See: Why is it frowned upon to use a null layout in Swing?, What's wrong with the Null Layout in Java? and Null layout is evil for more information.

    Stop using setLayout(null) and setBounds(...), setLocation(...) methods right now!

  5. These lines:

    while (scanner.hasNextLine() == true);
    if (inputLogin.equals(login) == true && Arrays.equals(password, inputPassword) == true) { // BAD
    

    could have been written like this:

    while (scanner.hasNextLine()); //Removed == true
    if (inputLogin.equals(login) && Arrays.equals(password, inputPassword)) { //Removed == true
    

    because those methods already return a boolean, so, there's no need to compare a boolean with another one, which is the same as if (true == true), why not if (true)? It's easier to read and understand.

However I must congratulate you for placing your program on the EDT.


Now, after we've said the above recommendations, let's move on to the program... it works fine for me:

This is the console output when I ran it:

admin
GOOD

So, the problem is probably on your file, I recommend you to write it again maybe?

Here's an example that generates a similar output using:

  • A GridBagLayout for the outer pane.
  • A GridLayout for both user / password label and fields panes

Code:

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class LoginSample {
    private JFrame frame;
    private JLabel userLabel;
    private JLabel passLabel;
    private JTextField userField;
    private JPasswordField passField;
    private JButton button;
    private JButton button2;
    private File file;
    private JPanel pane;
    private JPanel contentPane;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new LoginSample().createAndShowGui();
        });
    }

    private void createAndShowGui() {
        GridBagConstraints gbc = new GridBagConstraints();

        frame = new JFrame(getClass().getSimpleName());
        contentPane = new JPanel();
        contentPane.setLayout(new GridBagLayout());

        userLabel = new JLabel("User: ");
        passLabel = new JLabel("Password: ");
        userField = new JTextField(10);
        passField = new JPasswordField(10);

        pane = new JPanel();
        pane.setLayout(new GridLayout(1, 2));
        pane.add(userLabel);
        pane.add(userField);

        gbc.fill = GridBagConstraints.BOTH;
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.gridx = 0;
        gbc.gridy = 0;

        contentPane.add(pane, gbc);

        gbc.gridx = 0;
        gbc.gridy = 1;
        pane = new JPanel();
        pane.setLayout(new GridLayout(1, 2));
        pane.add(passLabel);
        pane.add(passField);
        contentPane.add(pane, gbc);

        button = new JButton("Click me!");
        button2 = new JButton("Do not click me");

        file = new File("src/sof/users.txt");
        System.out.println(file.getAbsolutePath());

        button.addActionListener(listener);
        button2.addActionListener(listener);

        gbc.gridx = 0;
        gbc.gridy = 2;
        contentPane.add(button, gbc);

        gbc.gridy = 3;
        contentPane.add(button2, gbc);

        frame.add(contentPane);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    private ActionListener listener = e -> {
        if (e.getSource().equals(button)) {
            String s = "";
            Scanner sc = null;
            try {
                sc = new Scanner(file);
                while (sc.hasNext()) {
                    s = sc.nextLine();
                    System.out.println(s);
                }
            } catch (FileNotFoundException ex) {
                ex.printStackTrace();
            } finally {
                sc.close();
            }
            String[] parts = s.split("\\.");
            String user = parts[0].trim();
            String pass = parts[1].trim();
            System.out.println(user + " <<>> " + Arrays.toString(pass.toCharArray()));
            System.out.println(userField.getText() + " <<>> " + Arrays.toString(passField.getPassword()));
            System.out.println(user.equals(userField.getText()));
            System.out.println(Arrays.equals(pass.toCharArray(), passField.getPassword()));
        } else {
            System.out.println("Told you not to click me! You made me cry :'(");
        }
    };
}

As you can see, the code is short, it's complete because you can copy-paste it and see the output with a single modification (file path), it's verifiable (it shows the same output as below), that's what you're expected to do when you're requested to do a MCVE. Without posting the relevant code, well, I couldn't have written the first five suggestions :)

My output vs yours, both are really similar, just change the fonts and it should look like the one before...

enter image description here enter image description here

Frakcool
  • 10,915
  • 9
  • 50
  • 89