Question

I'm trying to understand the Scanner function, but I can't seem to understand it.

I'm making a program to calculate the BMI (body mass index) and it's practically done, except that I can't make the calculation! Everything works fine except for when I click the "ok" button.

Had to take away my code so my collegues won't copy my code, like they've made in the past, will be posting again after friday.

Was it helpful?

Solution

first thing there is no poblem with Scanner things and its not required when we use GUI.

its useful only for console input/output.

so when you get text it will be in string format so parse it to double like

String val = txt1.getText();
double valueDouble = Double.parseDouble(val);

and handle the parse exception using try/catch

so replace the piece of code below

 Scanner dado1 = new Scanner(txt1.getText());
            System.out.println(dado1);
                if(dado1.hasNextDouble()){
                    tamanho = dado1.nextDouble();
                }
            Scanner dado2 = new Scanner(txt2.getText());
                if(dado2.hasNextDouble()){
                    peso = dado2.nextDouble();
                }

to

String t1 = txt1.getText();
if(!"".equals(t1))
tamanho = Double.parseDouble(t1);


String t2 = txt2.getText();
if(!"".equals(t2))
peso = Double.parseDouble(t2);

i tried to run your program but i got the exception saying -> container does not have parent attribute.

so what i did is i have added a parent container inside your ok button action listener

and it works well.

container to be added is

final JDesktopPane desk = new JDesktopPane();
                    setContentPane(desk);

to your

JOptionPane.showInternalMessageDialog(desk,"Seu IMC é:"+ (result/ peso));

but you have passed null as the first argement.

so it should become like below

   ok.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent evt){
            String t1 = txt1.getText();
            if(!"".equals(t1))
            tamanho = Double.parseDouble(t1);


            String t2 = txt2.getText();
            if(!"".equals(t2))
            peso = Double.parseDouble(t2);
              result = tamanho*tamanho;
            if (ok != null){
                System.out.println(result);
                System.out.println(peso);
                final JDesktopPane desk = new JDesktopPane();
                setContentPane(desk);
                JOptionPane.showInternalMessageDialog(desk,"Seu IMC é:"+ (result/ peso));
            }
        }
    });

OTHER TIPS

you may simply parse instead of Scanner:

tamanho = Double.parseDouble(txt1.getText());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top