1

When the user inputs pBreak, it should break the while loop. However, this isn't working and I'm confused on why. Could somebody please help me?

package main;

import java.io.*;
import java.util.*;

public class TextFiles {
    public static void main(String[] args) {
        try {
            BufferedWriter out = new BufferedWriter(new FileWriter("file.txt"));
            Scanner input = new Scanner(System.in);
            while (true) {
                String line = input.next();
                if (line == "pBreak") {
                    break;
                }
                out.write(line);
                out.newLine();
            }
                out.close();
        } catch (IOException e) {
            System.out.println("Error!");
        }
    }
}
Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
EpicBlargh
  • 1
  • 1
  • 5

4 Answers4

2

Use equals instead of ==. Consider, null-safe equals

 if ("pBreak".equals(line)) {
Masudul
  • 21,823
  • 5
  • 43
  • 58
0

This code will also work:

if (line.equals("pBreak")) {
    break;
}
Dennis Meng
  • 5,109
  • 14
  • 33
  • 36
Kishore
  • 300
  • 3
  • 14
0

== operator will compare the references of the two operands. As line variable is a different string object's reference ,it will not match to string literal constant reference pBreak while comparing.

if (line .equals("pBreak")) {
  break;
}

So equals() method has to be used to compare the String.enter code here

strivedi183
  • 4,749
  • 2
  • 31
  • 38
Om S patel
  • 31
  • 2
0

Change:

if (line == "pBreak") {

to

if (line.equals("pBreak")) {

== compares object references, .equals(String) compares String values.

Michael Yaworski
  • 13,410
  • 19
  • 69
  • 97