拒绝在Java Swing中数组对象的重复属性条目。

huangapple go评论65阅读模式
英文:

Reject duplicate attribute entry of an array of objects in java swing

问题

我尝试创建一个用于注册用户的程序,所以我创建了一个用户数组,其属性包括:Usuario(用户ID)、nombre(姓名)和contrase&#241;a(密码)。每当我创建一个新用户时,程序必须确保用户ID之前尚未注册过,如果已经注册过,程序必须拒绝用户注册,直到我输入一个不同的UserID。每个创建的对象(每个带有其属性的用户)都保存在数组的相应位置,所以我创建了一个具有以下功能的方法(int contador将计算我注册用户的次数,数组最多有10个,因此contador<10):

public void registrarUsuario(int contador){
    int f = contador;
    usuario = t3.getText();
    nombre = t4.getText();
    contrase&#241;a = t5.getText();

    for(int i=0; i<users.length; i++){
        if(users[i].getUsuario() == usuario){
            JOptionPane.showMessageDialog(null, "El nombre de usuario ya ha sido utilizado");
        }
    }

    if(this.t6.getText().equals(this.t5.getText())){  
        Usuario user = new Usuario(usuario, nombre, contrase&#241;a);
        users[contador] = user;
        JOptionPane.showMessageDialog(null, "El usuario se ha registrado con exito!");   

        this.t3.setText("");
        this.t4.setText("");
        this.t5.setText("");
        this.t6.setText("");

    } else {
        JOptionPane.showMessageDialog(null, "ERROR: las contrase&#241;as no coididen");
        this.t5.setText("");
        this.t6.setText("");
    }
}

但是当我运行程序时,出现以下错误:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at proyecto1.Proyecto1.registrarUsuario(Proyecto1.java:143)

(请参见上面的第143行)

注意:我已经将您提供的代码进行了简单的翻译,但您提供的代码中存在一些 HTML 编码的内容(如&#241;表示的是特定字符)。如果需要完整的翻译,请提供正确格式的内容。

英文:

I try to make a program to register users, so I created an array of users with the attributes: Usuario (User ID), nombre (name) and contrase&#241;a (password), and everytime I create a new user the program has to ensure that the User ID hasn't registered before, if it's already registered the program must reject the user register until I put a different UserID, every Object created(every user with it's attributes) is saved in it's respective position of the array, so I create a method with these functions (int contador will count the times I register a User, the array has a maximum of 10 so contador<10):

public  void registrarUsuario(int contador){
         int f = contador;
        usuario = t3.getText();
        nombre = t4.getText();
        contrase&#241;a = t5.getText();

            for(int i=0; i&lt;users.length; i++){
\line 43 with error if(users[i].getUsuario() == usuario){
                    JOptionPane.showMessageDialog(null, &quot;El nombre de usuario ya ha sido utilizado&quot;);

                }
            }



                
        if(this.t6.getText().equals(this.t5.getText())){  
           Usuario user = new Usuario(usuario, nombre, contrase&#241;a);
           users[contador] = user;
            
        JOptionPane.showMessageDialog(null, &quot;El usuario se ha registrado con exito!&quot;);   
        
            this.t3.setText(&quot;&quot;);
            this.t4.setText(&quot;&quot;);
            this.t5.setText(&quot;&quot;);
            this.t6.setText(&quot;&quot;);
            
        }else{
            
        JOptionPane.showMessageDialog(null, &quot;ERROR: las contrase&#241;as no coididen&quot;);
            this.t5.setText(&quot;&quot;);
            this.t6.setText(&quot;&quot;);
            
        }
      
    }

but when I run the program I get this error:

Exception in thread &quot;AWT-EventQueue-0&quot; java.lang.NullPointerException
	at proyecto1.Proyecto1.registrarUsuario(Proyecto1.java:143) 

( see above to line 143)

答案1

得分: 0

在这行代码中:

for(int i=0; i&lt;users.length; i++){

你从未定义数组users - 要么是因为你忘记了this标识符,要么就是忘记定义它。

英文:

On this line of code:

for(int i=0; i&lt;users.length; i++){

You never defined the array users - either because you forgot the this identifier, or simply forgot to define it.

答案2

得分: 0

我理解你想要实现的内容,但由于你没有发送所有的类,我没有完全理解你的方法。我会将我是如何解决这个问题的发送给你,如果你想的话,你可以重新发送所有的类和代码,以便我可以全面了解 拒绝在Java Swing中数组对象的重复属性条目。

我的代码:(当然,你可以编辑它,使其与用户交互,在这里我只显示了一般思路)

    // 用户类
package userArray;

public class User {
	
	private int id;
	private String name;
	private String password; // Java中有特殊的密码类,但在这个问题中不会使用它们

	public User(int id, String name, String password) {
		super();
		this.id = id;
		this.name = name;
		this.password = password;
	}
	// 获取器和设置器 + toString()
}

// UsersList 类

package userArray;

import java.util.*;

public class UsersList {
	
	ArrayList<User> users = new ArrayList<User>();
	
	// 原始函数
	public User createUser(int id, String name, String password) throws Exception {
		for(User u : this.users) {
			if(id == u.getId())
				throw new Exception("用户已存在...");
		}
		User u = new User(id, name, password);
		this.users.add(u);
		return u;
	}
	
	// 将原始函数包装在每次执行时的 try/catch 中的函数
	public User registerUser(int id, String name, String password) {
		try {
			return createUser(id, name, password);
		} catch (Exception e) {
			System.out.println("ID " + id + " 对应用户 " + name + " 已存在...");
			return null;
		}
	}

	public UsersList() {
		super();
		this.users = users;
	}
	// + toString()
}

// 主类

package userArray;

public class Main {

	public static void main(String[] args) {
		
		UsersList list = new UsersList();
		
		list.registerUser(1, "Kevin", "Kevin123");
		list.registerUser(2, "Sarah", "Sarah123");
		list.registerUser(1, "Steven", "Steven123");
		list.registerUser(3, "Stephany", "Stephany123");
		list.registerUser(3, "Alex", "Alex123");
		
		System.out.println("列表是:");
		System.out.println(list.toString());

	}
}

执行结果:

ID 1 对应用户 Steven 已存在...
ID 3 对应用户 Alex 已存在...
列表是:
UsersList [users=[User [id=1, name=Kevin, password=Kevin123], User [id=2, name=Sarah, password=Sarah123], User [id=3, name=Stephany, password=Stephany123]]]

英文:

I got what you're trying to achieve but I didn't fully understand your method because you didn't send all the classes, so i'll send you how i solved it and if you want you can resend us all your classes and code to have a full view 拒绝在Java Swing中数组对象的重复属性条目。

My code: (of course you can edit it to be interactive with the user, here i'm showing the general idea only)

    //User class
package userArray;
public class User {
private int id;
private String name;
private String password;//there is special classes for password in java, not going to use them in this problem
public User(int id, String name, String password) {
super();
this.id = id;
this.name = name;
this.password = password;
}
//getters and setters + toString()
//UsersList class
package userArray;
import java.util.*;
public class UsersList {
ArrayList&lt;User&gt; users = new ArrayList&lt;User&gt;();
//The original function
public User createUser(int id, String name, String password) throws Exception {
for(User u : this.users) {
if(id == u.getId())
throw new Exception(&quot;User already exists...&quot;);
}
User u = new User(id,name,password);
this.users.add(u);
return u;
}
//The function used to wrap the original function in try/catch each time executed
public User registerUser(int id, String name, String password) {
try {
return createUser(id,name,password);
} catch (Exception e) {
System.out.println(&quot;ID &quot;+ id +&quot; for user &quot;+name+&quot; is for an existing user...&quot;);
return null;
}
}
public UsersList() {
super();
this.users = users;
}
// + toString()
//Main class
package userArray;
public class Main {
public static void main(String[] args) {
UsersList list = new UsersList();
list.registerUser(1, &quot;Kevin&quot;, &quot;Kevin123&quot;);
list.registerUser(2, &quot;Sarah&quot;, &quot;Sarah123&quot;);
list.registerUser(1, &quot;Steven&quot;, &quot;Steven123&quot;);
list.registerUser(3, &quot;Stephany&quot;, &quot;Stephany123&quot;);
list.registerUser(3, &quot;Alex&quot;, &quot;Alex123&quot;);
System.out.println(&quot;The list is: &quot;);
System.out.println(list.toString());
}
}

The execution result:

ID 1 for user Steven is for an existing user... <br>
ID 3 for user Alex is for an existing user... <br>
The list is: <br>
UsersList [users=[User [id=1, name=Kevin, password=Kevin123], User [id=2, name=Sarah, password=Sarah123], User [id=3, name=Stephany, password=Stephany123]]]

huangapple
  • 本文由 发表于 2020年9月12日 03:02:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/63852890.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定