How to take a char type die by Joptionpane?

Asked

Viewed 323 times

0

char cadastrar;
cadastrar = JOptionPane.showInputDialog("cadastrar: A-aluno P-professor M-medico");

1 answer

0

You can do it:

String resposta = JOptionPane.showInputDialog("cadastrar: A-aluno P-professor M-medico");
if (resposta == null) {
    // O usuário clicou no botão Cancelar ou no X do canto da tela.
} else if (resposta.length() != 1) {
    // Resposta inválida. Tratar esse caso aqui.
} else {
    char cadastrar = resposta.charAt(0);
    // Continuar com o código aqui ...
}

This is what appears:

JOptionPane.showInputDialog

However, if you are giving a list with three options for the user to choose one and are already using JOptionPane for this, it makes more sense to ask the user to choose the button with the option he wants instead of asking him to type a letter:

String[] opcoes = { "Aluno", "Professor", "Médico" };
int escolha = JOptionPane.showOptionDialog(
    null,
    "Escolha qual você quer cadastrar",
    "O que você quer cadastrar?",
    JOptionPane.DEFAULT_OPTION,
    JOptionPane.QUESTION_MESSAGE,
    null,
    opcoes,
    opcoes[0]);

if (escolha == JOptionPane.CLOSED_OPTION) {
    // Usuário clicou no X do canto da tela.
} else {
    char cadastrar = opcoes[escolha].charAt(0);
    // Continuar com o código aqui ...
}

This is what appears:

JOptionPane.showInputDialog

You can’t get one char directly from JOptionPane because the method showInputDialog asks the user to type a line of text, and therefore there are several characters instead of one. The method showOptionDialog returns a int which corresponds to the index of the button that was chosen. O CLOSED_OPTION corresponds to the case where the user clicks on X in the corner of the window that appears.

Plus, it’s not a good idea to use a char to represent a set with the values student, teacher and doctor. This is something that goes totally against the principles of object-oriented programming that is what you are learning. Such a thing would be best represented by some class or by a enum. However, without looking at the context in which you want to use it, you can’t tell for sure which would be the best alternative.

  • can’t take a given char by Jopotionpane ?

  • @Brennoamaral Reply edited.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.