I am totally new to programming. I´m reading some tutorials on the internet, and also Barry Burds “Java for dummies” while trying to learn programming Java. I have tried all variations I could think of without success.
In one exercise I am supposed to make the following program to print a message in a “messageDialogBox” which should contain the numbers wrote in by the user of the program. Unfortunately I get thhe following error message when trying to compile: Can somebody please help me get the code to work? What is wrong with the code?
5 errors
Addition2.java:24: ')' expected
JOptionPane.showMessageDialog( null, firstnumber "+" secondnumber
^
Addition2.java:25: not a statement
+ sum, "Results", JOptionPane.PLAIN_MESSAGE );
^
Addition2.java:25: ';' expected
+ sum, "Results", JOptionPane.PLAIN_MESSAGE );
^
Addition2.java:25: not a statement
+ sum, "Results", JOptionPane.PLAIN_MESSAGE );
^
Addition2.java:25: ';' expected
+ sum, "Results", JOptionPane.PLAIN_MESSAGE );
The code is the following:
import javax.swing.JOptionPane;
public class Addition2
{
public static void main( String args[] )
{
String firstnumberstring;
String secondnumberstring;
int firstnumber;
int secondnumber;
int sum;
firstnumberstring = JOptionPane.showInputDialog(
"Write first number" );
secondnumberstring =
JOptionPane.showInputDialog( "Write second number" );
firstnumber = Integer.parseInt( firstnumberstring );
secondnumber = Integer.parseInt( secondnumberstring );
sum = firstnumber + secondnumber;
JOptionPane.showMessageDialog( null, firstnumber "+" secondnumber
+ sum, "Results", JOptionPane.PLAIN_MESSAGE );
}
}
You need to concatenate strings using the string cat operator: +
Btw; it’s considered a good thing to declare variables where they are assigned for the first time – and not sticking to the old c- requirement (with ancient roots) that all variables must be declared before the actual code.
It helps a little when trying to figure out where a variable is used.
It’s particulary good when a variable is used only in a specific scope; ( inside curly brackets)