How to get a char data from JOptionPane?

0
char cadastrar;
cadastrar = JOptionPane.showInputDialog("cadastrar: A-aluno P-professor M-medico");
    
asked by anonymous 23.05.2018 / 22:28

1 answer

0

You can do this:

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 ...
}

Here's what it looks like:

However,ifyouaregivingalistwiththreeoptionsfortheusertochooseoneandarealreadyusingJOptionPaneforthis,itmakesmoresensetoasktheusertochoosethebuttonwiththeoptionthathewantsinsteadofaskingforhetypealetter:

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 ...
}

Here's what it looks like:

YoucannotgetachardirectlyfromJOptionPanebecausetheshowInputDialogmethodpromptstheusertotypealineoftext,sothereareseveralcharactersinsteadofone.TheshowOptionDialogmethodreturnsaintthatcorrespondstotheindexofthebuttonthatwaschosen.CLOSED_OPTIONcorrespondstothecasewheretheuserclicksonthe in the corner of the window that appears.

Furthermore, it is not a good idea to use char to represent a set of student, teacher, and physician values. This is something that goes totally against the principles of object-oriented programming that is what you are learning. This kind of thing would be better represented by some class or enum . However, without looking at the context in which you want to use it, you can not pinpoint what would be the best alternative.

    
23.05.2018 / 22:31