简体   繁体   English

通过扫描仪验证输入数据

[英]Validation of input data via Scanner

I have a problem with if-statement. 我对if陈述有疑问。 There is a file with the line admin.admin . 有一个带有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() ). 将数组的第一个元素与输入值进行比较(代码String inputLogin = textField[0].getText()中的inputLogin =“ admin”)。 I have to get the true, but I'm actually getting a false 我必须得到真实,但实际上我得到了错误

first java file 第一个Java文件

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 第二个Java文件

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 Account.txt

admin.admin

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 JPanel s and instantiate a JFrame , take the answers in: Extends JFrame vs. creating it inside the program as a reference 避免扩展JFrame ,因为JFrame是一个刚性容器,而是朝JPanel GUI并实例化一个JFrame ,请回答以下问题: 扩展JFrame与在程序内部创建它作为参考

  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. 以下几行对我来说毫无意义,因为当您可以使用原始int ,无需将数字包装为Integer ,这会影响程序的性能。

     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 ! 停止使用null-layout Please read carefully how to use the different layout managers , you can combine them and create cool GUIs. 请仔细阅读如何使用不同的布局管理器 ,您可以将它们组合并创建很酷的GUI。

    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. Swing被设计为使用它们,因为它必须处理不同的OS,PLAF,屏幕尺寸和分辨率,像素完美的GUI只是一种幻想, 这里有一个使用它们时发生情况的示例。

    See: Why is it frowned upon to use a null layout in Swing? 请参阅: 为什么在Swing中使用null布局却不受欢迎? , What's wrong with the Null Layout in Java? Java中的Null布局怎么了? and Null layout is evil for more information. 空布局对于获取更多信息不利

    Stop using setLayout(null) and setBounds(...) , setLocation(...) methods right now! 立即停止使用setLayout(null)setBounds(...)setLocation(...)方法!

  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) ? 因为这些方法已经返回了布尔值,所以,不需要将布尔值与另一个布尔值进行比较,这与if (true == true)相同,但if (true == true)不是if (true)呢? It's easier to read and understand. 它更容易阅读和理解。

However I must congratulate you for placing your program on the EDT. 但是,我必须祝贺您将程序放置在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. 外窗格的GridBagLayout
  • A GridLayout for both user / password label and fields panes 用户/密码标签和字段窗格的GridLayout

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. 如您所见,该代码很短,它是完整的,因为您可以复制粘贴该代码,并且只需一个修改即可查看输出(文件路径),它是可验证的(它显示与下面相同的输出),这就是您所期望的要求您执行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... 我的输出与您的输出确实非常相似,只是更改了字体,它应该看起来像以前的字体...

在此处输入图片说明 在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM