gpt4 book ai didi

Javaform : how to use a char in this case

转载 作者:行者123 更新时间:2023-11-30 02:52:22 24 4
gpt4 key购买 nike

我知道“如何从字符串转换为字符?”已被问过很多次,但我不知道为什么这对我的项目来说是一个问题,因为我不认为我正在尝试从字符转换为字符串。

这是我的代码:

private void BtnAddClientActionPerformed(java.awt.event.ActionEvent evt) {                                             

try {

ArrayList<Cliente> clientes = ClienteDataSer.LoadData();

Cliente C = new Cliente();
JOptionPane.showMessageDialog(null, "reading: dni");
C.setDni(Integer.parseInt(TxTDni.getText()));
JOptionPane.showMessageDialog(null, "reading: nombre");
C.setNombre(TxTNombre.getText());
JOptionPane.showMessageDialog(null, "reading: apellido");
C.setApellido(TxTApellido.getText());
JOptionPane.showMessageDialog(null, "reading: sexo");
C.setSexo(TxTSexo.getText()); //<--- error: "Incopatible types:String cannot be converted to char
JOptionPane.showMessageDialog(null, "reading: edad");
C.setEdad(Integer.parseInt(TxTEdad.getText()));
JOptionPane.showMessageDialog(null, "Se añade a la tabla clientes");
clientes.add(C);
JOptionPane.showMessageDialog(null, "Se guarda");
ClienteDataSer.saveData(clientes);
JOptionPane.showMessageDialog(null, "Se corre el metodo llenartablaclientes");
llenarTablaClientes();
JOptionPane.showMessageDialog(null, "Hecho");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Faltan campos por llenar");
}

}

(多个消息对话框只是调试语句,以查看程序在哪里失败。)

这里是 TxTSexo.getText() 类的摘录,来自:

    public char getSexo() {
return sexo;
}

public void setSexo(char sexo) {
if (this.sexo == 'M'|| this.sexo == 'm'|| this.sexo == 'f'|| this.sexo == 'F')
this.sexo = sexo;
}

我已经尝试转换为字符串,但它再次显示错误。

如果有人想阅读整个项目,这里是 link ,也许你还可以用它做其他事情。

最佳答案

相关类的 sexo 属性的类型为 charTxTSexo.getText() 返回一个String。它们不是同一件事,它们之间没有自动转换。您需要自己执行合适的转换,才能使用 TxTSexo.getText() 设置 sexo 属性的值。

如果您可以依靠 TxTSexo.getText() 始终返回包含一个字符或包含所需字符作为第一个字符的非 null 字符串,则您可以简单地使用C.setSexo(TxTSexo.getText().charAt(0))

如果您需要容纳 TxTSexo.getText()null 或为空或包含前导空格,那么您可能会这样做

char sexoChar;

try {
sexoChar = TxTSexo.getText().trim().charAt(0);
} catch (NullPointerException | IndexOutOfBoundsException e) {
sexoChar = ' ';
}

C.setSexo(sexoChar);

您可能想要执行进一步的验证或转换。

关于Javaform : how to use a char in this case,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38234240/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com