I'm trying to teach myself java by writing a simple weekly planner program and the if statment in my code is giving me grief, here is my code:
import java.util.Scanner;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class Week
{
public static void main(String[] args) throws IOException
{
Scanner inorout = new Scanner(System.in);
System.out.println("Do you want to read or write (r/w)");
String decision = inorout.nextLine();
System.out.println(decision);
if(decision == "r")
{
System.out.println("It has gone into the if");
Scanner namer = new Scanner(System.in);
System.out.println("What is the name of the week you want to read?");
String r = namer.nextLine();
Scanner s = new Scanner(new File(r + ".txt"));
System.out.println("What is Your Name?");
String name = s.nextLine();
System.out.println("Welcome " + name);
}
}
}
When I compile the program using Drjava and input "r" it doesn't run the if statment, and i'm at a loss as to whats wrong, help would be much appriciated
Strings in Java are compared usually with equals not with ==.
The String decision will not have reference-equality with the literal "r". You need to use String.equals method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With