Page 1 of 1

Java code problem :(

Posted: Sun Nov 01, 2009 6:40 pm
by Tonka
Right, i need to get this code working so that i know how to program this as it's apart of a much larger program.

I wan't the variable to be String & display a box that asks user to enter an input. The program will read what the user has put such as shortcuts like:

M, for Monday
Tu, for Tuesday for example.

All i want this program to do is to recognise that it's put in M and then come up with a pop up box displaying "Monday" - if the user types M - else it will say Error.

This is my code so far for it using If statements, but i don't know why it will not compile correctly... Here is my code followed by the compiler error


__________________________________________________________
import javax.swing.JOptionPane;
public class DaysOfWeek
{
public static void main(String[] args)
{

input1 = JOptionPane.showInputDialog("Enter your input");
{
if (input1 == "M")

JOptionPane.showMessageDialog("Monday");
}
else
{
JOptionPane.showMessageDialog("Error");
}

}
}
________________________________________________________

Compiler Error=

*File location*: 'else' without 'if'
else
^
1 error
_____________________________________________

I don't know why it is erroring saying i do not have an 'if' when blaitantly i have and it doesen't seem to understand that i have an if but more logically i've misplaced something or done something wrong. Please help :)



help pls :) I want to learn why my code is wrong and how to overcome this problem so that i can be a better programmer (im a newbie at the moment)

Posted: Tue Nov 03, 2009 6:22 pm
by MudGuard

Code: Select all

{
if (input1 == "M")

JOptionPane.showMessageDialog("Monday");
} 
Here you have one block marked by { and }, containing an if-statement without an else statement. The if-branch contains exactly one statement (for more, it would need { } around the statements.

Next, you have

Code: Select all

else
{
JOptionPane.showMessageDialog("Error");
} 
which clearly is an else without an if.

It can't belong to the existing if, because the if is inside {}, while the else is outside.

Code: Select all

if (input1 == "M") 
Btw, the == operator in most cases does not what you probably want to do when used with strings - most times the equals method is more appropriate.