HelpMe
HelpMe

Reputation: 61

How to output an int in a JOptionPane dialogue box?

I was wondering how you display a messagebox that shows an int. For example:

import java.util.*;
import javax.swing.JOptionPane;

public class ShowMessage {


    public static void main(String[] args) {
        int a = 4;

        JOptionPane.showMessageDialog(null, a  );

I get an error under the showMessageDialog.

Upvotes: 2

Views: 2803

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347204

If you have a look at the JavaDocs for JOptionPane#showMessageDialog, you will see that message parameter is a Object while int is a primitive

Prior to Java 5's autoboxing support you would have had to convert a to Integer, but

JOptionPane.showMessageDialog(null, a);

Should work. JOptionPane will use the object's (now a Integer) toString method to create a String representation for you, but personally I prefer to use

JOptionPane.showMessageDialog(null, Integer.toString(a));

as it's intentions are well spelled out without people needing to know how the underlying JOptionPane API works

Upvotes: 1

Related Questions