Find line with text in a file [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
I wanted to find out in options.bldata if firstLaunch= was written, for this I wrote the following code:
File file = new File("options.bldata");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line == "firstLaunch=") {
System.out.println("123");
}
}
when it finds a line with firstLaunch= it should print 123, but I don't know why it doesn't print 123 even if firstLaunch= is in the file.

Operator == checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects.
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.equals("firstLaunch=")) {
System.out.println("123");
}
}
Here is an article for more information

There is two wrong thing in the code.
Never use double equals to compare strings. You need to use the equals() function from string to do so
you want to test if the string firstLaunch= is in the line, not that your line is equals to firstLaunch=. For this, you can use line.contains("firstLaunch=")

You should use equals() to compare strings. Or in your case, contains() because the line might have other stuff, not just what you want to find

Related

Why is my program not counting word hello when it reads from a text file in IntelliJ

I am new to java and coding in general and I was learning how to read from file. I have looked up at the process on how to add file into the src folder by just dragging it but my question persists on why my program is not counting a string "hello" when it reads the file successfully. According to what I think, it is the first element that shows us and I have used the IF statement to check out by storing it in a string element line. can someone explain this to me in a beginner friendly way.
public class Main {
public static void main(String[] args) throws FileNotFoundException {
File path = new File("C:\\Users\\fahad\\IdeaProjects\\testingFileIO\\src\com\\Fahad\\Readingfile.txt");
Scanner fileread = new Scanner(path);
String check = "hello";
int count=0;
boolean flag = false;
while(fileread.hasNextLine()){
String line = fileread.nextLine();
System.out.println(line);
if(line == check)
{
flag = true;
count++;
}
}
if(flag == true)
{
System.out.println("WE found it" + count);
}
else
{
Syste.out.println("No string was there");
}
}
}
output
hello world.
This is fahad Qazi
How are you doing ?
checking
1234567
No string was there
I am new to stackoverflow so sorry about this question but any help is appreciated
The majority of your code is alright. It can be better, but it's alright for a start.
As to where you're going wrong is the line:
if (line == check)
You're comparing the complete line if it equals to the string "hello". This returns false since the line in question is hello world.
A solution to this is to do a contains() operations. Below is an example of this
String myStr = "Hello world";
System.out.println(myStr.contains("Hello")); // true
System.out.println(myStr.contains("world")); // true
System.out.println(myStr.contains("hello")); // false due to case sensitivity
System.out.println(myStr.contains("Hi")); // false
So in your case you should check the following using contains:
if (line.contains(check)) // do the things you wanna do when the line contains 'hello'
To compare String values you don't have to use "==".
You have to compare with the equals method from String class.
For example:
String x="hello",y="world";
if(x.equals(y)){
}
Or you can use x.equalsIgnoreCase(y) if you want to compare two strings and ignore uppercase and lowercase.
Direct == operation on string will not work. You need to use contains(CharSequence s) method from String class in-order to check if the the required sequence of characters is present in the given string or not. You need to make use of this method in your code in order to achieve the required result.
Additionally, if you are using Java 8+, then solution can be simplified/re-written as:
long count = Files.lines(Paths.get(<your_file_path>))
.filter(line -> line.contains(check))
.count();

Palindrome java error [duplicate]

This question already has answers here:
Java .equals between String and StringBuilder
(12 answers)
Closed 6 years ago.
I have a problem in Java. I am making a program to check if a given text is Palindrome or not. I am 99% sure my code is correct yet I can't get a good result. Here is the code.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
System.out.print("Enter a line of text to check if palindrome: ");
String text = scan.nextLine();
String revText = text.replaceAll("[^A-Za-z]", "").toLowerCase().trim(); /*
* Using regex here... everything that is not
* (^) from A-Z (capital) to a-z replace with
* ("") in revText.
*/
sb.append(revText).reverse().toString();
System.out.println("Reversed: " + sb);
System.out.println("Normal: " + revText);
System.out.println(sb.equals(revText));
scan.close();
}
So for instance I enter:
Enter a line of text to check if palindrome: Anna2023
Reversed: anna
Normal: anna
false
Why false ? ;/
Try
System.out.println(revText.equals(sb.toString()));
sb is not equal to the string because it is not a String. It is a container for building a string. The reason printing sb shows the String is that System.out.println will call toString on whatever is given to it.
StringBuilder class does not override equals method from Object class.Hence it's equals method will check if object references are same and if those are same then only it will return true.In case of String class, it overrides equals method from object class and it checks if contents of two strings are equal.
In your code, you are calling equals method on StringBuilder object and as both references are different it is returning false.
Convert it to string and then call equals(),
System.out.println(sb.toString().equals(revText));
Java .equals between String and StringBuilder

while loop not working Java [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
When I create a variable and wrap the code in a while loop it never repeats. Here's a sample of code I tried it on.
String repeat = "y";
Scanner keyboard = new Scanner(System.in);
while (repeat == "y"){
String word1 = "this";
String word2 = "that";
String word3 = word1 + word2;
System.out.println(word3);
for(int x = 10; x<20; x = x+1){
word3 = word1 + word3;
System.out.println(word3);
}
repeat = keyboard.nextLine();
}
No matter what the input is in the end of the script, it just ends. Any help?
Change the line
while (repeat == "y")
to
while("y".equalsIngnoreCase(repeat))
and
keyboard.nextLine() ;
to
keyboard.next();
Reading How do I compare strings in Java? will be helpful.
When you compare a string using '=='. you are comparing the object reference. You are essentially asking if the two objects are the same, rather than comparing the string contents. Try using the String.compareTo(..) method.
Example:
while (repeat.compareTo("y") == 0) {
The problem probably comes from the facts you compare two objects with = but I guess what you want to do is compare Strings with the String method equals, so it would look like that:
while(repeat.equals("y")){
...
}
Never use == to compare strings.
Try this:-
while ("y".equalsIngnoreCase(repeat) )

Compilation error executing basic if else statements [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I had a similar code to this using numbers, and it worked perfectly. This however keeps underlining the word else and I don't know why. I am just playing around with java trying to understand a few principles.
I want to program to reply one of two statements depending on input. Also, where it says if (input1 == "Hello");, I wanted to put if (input1 == "Hello" || "hello"); to accept lowercase too, but that showed errors too.
Just to be clear, if i remove the else clause, my program runs and both statements are printed!
import java.util.Scanner;
public class Input
{
public static void main(String[] args)
{
System.out.println("Hello there!");
Scanner Scan = new Scanner (System.in);
String input1 = Scan.nextLine();
Scan.close();
if (input1 == "Hello");
{
System.out.println("How are you?");
}
else
System.out.println("How rude, you didn't even say Hello!");
break;
}
}
}
Never use == to compare strings.
use .equals instead.
if (input1.equals("Hello"))
or
if (input1.equalsIgnoreCase("Hello"))
Delete the semicolon at the end of
if (input1 == "Hello");
EDIT:- As seen in your comments regarding OR.
You can try this:-
if(input1.equalsIgnoreCase("hello") || input1.equalsIgnoreCase("hey") || input1.equalsIgnoreCase("hi"))
Remove the ; at the end of your if statement. And use .equals() to compare strings.
The semicolon causes the compile error, while the == will cause a logical error once it does run.
You probably don't want the semicolon on the line
if (input1 == "Hello");
You also probably do not actually want to compare using == (read the linked question about comparing strings).
Third, why is there a break statement in your else clause?
You're looking for equalsIgnoreCase(). This compares two Strings without any regard to case.
Remove the ; after your if statement condition and add a { after else. Also, it is good practice to to use the equals(Object) method when comparing objects because you might get unexpected results when using ==.

I Cannot Get If/Else Statement to Prove True with Scanner [duplicate]

This question already has answers here:
Can't get else if statement to work in Java
(5 answers)
Closed 10 years ago.
Help. I'm new to Java programming so I'll try to make the best of your terms.
I was wondering how to get this program to register as true. When I type in "password" as an input, it does not execute any code from the "if" body. I also pasted this code in another class and it still doesn't work, regardless.
I've worked on this program for about a half an hour, and debugging it for twice as long. Please look through the coding.
import java.util.Scanner;
public class whileloop {
public void whileloop1() {
//DEBUG THIS PROGRAM! "password" does not work for input
System.out.println("Please enter the password to continue: ");
Scanner password = new Scanner(System.in);
String passwordinput = password.nextLine();
System.out.println("This is your entered password: " + passwordinput);
if (passwordinput == "password") {
System.out.println("Startup sequence has been iniciated.");
System.out.println("System is working correctly.");
//Terminate all here ---
} else {
System.out.println("Wrong password! Terminating program. /END");
}
System.out.println("Supressing the program's scanner!");
password.close();
}
}
When comparing string content in Java you use the .equals() method.
The == operator checks for reference equality, meaning, testing if they are both references of the same object.
So, in your case:
if(passwordinput.equals("password"))
This has been said many times, but I'll say it again, when comparing Strings in java, if you want to know if they point to the same reference use the == operator. if you want to check if they are equal in value use .equals("somestringhere") In your case use passwordinput.equals("password")
Since, in Java the line:
String s; declares a reference to a String object, unlike C++, which may declare an object of String.
So, the line if (passwordinput == "password") compares the reference of "password" and reference of passwordinput, the result will be false.
So, use if(passwordinput.equals("password"), which compares the object referenced by passwordinput with "password"

Categories