Java code problem :(

Using the Java SDK with TextPad

Moderators: AmigoJack, bbadmin, helios, Bob Hansen, MudGuard

Post Reply
Tonka
Posts: 2
Joined: Sun Nov 01, 2009 6:16 pm
Location: United Kingdom
Contact:

Java code problem :(

Post 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)
I am a firm believer that the amount of material possessions & currency you own has a direct effect on the amount of intercourse you will recieve
User avatar
MudGuard
Posts: 1295
Joined: Sun Mar 02, 2003 10:15 pm
Location: Munich, Germany
Contact:

Post 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.
Post Reply