0
import java.util.Scanner;
public class main {

    public static void main(String[] args) {
    boolean a = true; 
        do {
                Scanner input = new Scanner(System.in);
                System.out.println("Press any on keyboard:");
                String keys = input.nextLine();
                System.out.println("You pressed:");
                System.out.println(keys);
                System.out.println("Your hash is:");
                String B = "#B";
                String hash = B+keys;
                System.out.println(hash);
                System.out.println("To end loop press f");
                //End Loop
                Scanner exit = new Scanner(System.in);
                String end = exit.nextLine();
                if (end=="f") {
                    a=false;
                    }
            }



            while(a);
    }           
}

I've been using python and I decided to start learning java since android studio requires it. I'm learning how to do loops again. I can't get this to work. I already looked this up I couldn't find it. How would I end this by pressing 'f'? My thought process was that once it was done going though the first lines of the do loop, it would go though the if statement changing the value of a ending the loop.

Juan Ramos
  • 179
  • 1
  • 10

3 Answers3

2

use break statement under if(){} body. also your == comparison will give false, use str1.equals(str2) for comparison.

Sajidkhan
  • 608
  • 7
  • 16
0

Your problem is you are comparing strings with ==.You have to use equals to write correct if statement.

if (end.equals("f")){...}
Y.Kakdas
  • 833
  • 7
  • 17
  • if you want to duplicate the answer for which it is marked as 'duplicate of', you should at the very least state why they should use equals instead of ==. both myString.equals(otherString) and myString == otherString are 'correct statements', btw. – Stultuske Apr 01 '19 at 06:33
  • I answered this question just after it is posted,so it was not marked as duplicate when I post it. – Y.Kakdas Apr 01 '19 at 07:39
0

You could use the below code to check

if (end.equals("f")) { // end == "f" , it check the reference.
     a = false;
}
Ramesh Subramanian
  • 944
  • 1
  • 12
  • 28