Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having trouble using the java "if" statement

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

like image 235
Jarred Filmer Avatar asked Jan 24 '26 07:01

Jarred Filmer


2 Answers

Strings in Java are compared usually with equals not with ==.

like image 155
fyr Avatar answered Jan 26 '26 19:01

fyr


The String decision will not have reference-equality with the literal "r". You need to use String.equals method.

like image 39
Miserable Variable Avatar answered Jan 26 '26 19:01

Miserable Variable



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!