Palindrome java error [duplicate] - java

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

Related

Find line with text in a file [duplicate]

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

Why does my program skip over the replace method? [duplicate]

This question already has answers here:
Why does String.replace not work? [duplicate]
(3 answers)
Closed 4 years ago.
Whenever I run the java code below it compiles but the line that include the replace method seems to be skipped, such so that the inputted string and the output (newMessage) are the same. Why? variable C and variable D are chars...
import java.util.Scanner;
public class javaencrypt
{
public static void main(String[] args)
{
// define and instantiate Scanner object
Scanner input = new Scanner(System.in);
//prompt user to enter a string
System.out.println("Please enter a string: ");
String message = input.nextLine();
String newMessage = message;
char c=' '; // the character at even locations
char d=' '; // new character
// go throughout the entire string, and replace characters at even positions by the character shifted by 5.
// access the even characters with a for loop starting at 0, step 2, and ending at length()-1
// for( initial value; maximum value; step)
for(int k=0; k<message.length(); k=k+2)
{
c=message.charAt(k);
d=(char)(c+5);
/*
there will always be characters available, because keyboard is mapped on ASCII which is in the beginning of UNICODE
*/
newMessage.replace(c,d);
}
System.out.println("Message replacement is: " + newMessage);
}
}
In Java, Strings are immutable.
An immutable class is simply a class whose instances cannot be modified. All information in an instance is initialized when the instance is created and the information can not be modified.
When you call newMessage.replace(c, d); this does not update newMessage, but rather creates a new String with all chars c replaced with d instead. If you want newMessage to change to include the replacing of c to d, then you need to reassign the variable. This would look like newMessage = newMessage.replace(c, d);

Length method in java , when used on input string does not produce the expected result [duplicate]

This question already has answers here:
Scanner doesn't read whole sentence - difference between next() and nextLine() of scanner class
(24 answers)
Closed 5 years ago.
My initial code that does not produce the desired result:
import java.util.Scanner;
class Strings {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your word: ");
String word1 = sc.next();
System.out.println(word1.length());
sc.close();
}
}
Output:
tk#localhost:~$ java Strings
Enter your word:
avada kedavra
5
Which is not the length of my string.
But when I try this(without the user input) :
class Strings {
public static void main(String[] args) {
String str = new String("avada kedavra");
System.out.println(str.length());
}
}
Output :
tk#localhost:~$ java Strings
13
It works!
So , why doesn't it work when I take input from the user? What am I missing?
By default, sc.next() finds and returns the next complete token. By default, a token is a word, something separated with spaces or newline (\p{javaWhitespace}+).
So in your first example, word1 = "avada", with length 5.
Use sc.nextLine() to get the complete line.
In short: RTFM
A bit longer for the click-lazy: Scanner returns the "next token" when calling next Tokens are calculated by taking a pattern, which is "all whitespaces" by default. So your call of next returns the next word and not the complete line as you intended.
Set a fitting pattern when instantiating Scanner or call nextLine instead.

How to reversing user input String? [duplicate]

This question already has answers here:
Reverse a string in Java
(36 answers)
Closed 6 years ago.
I am trying to reverse user input string my code below is working so that it just output as same as input value..
For example "Hello" will come out "Hello" while result should be "olleH"
This is my code that is in the main as a method call:
System.out.println("Enter a word or phrase you want to be reversed: ");
String s1 = sc.next();
System.out.println("The reversed message is: " + printReverse(s1));
And this is the code that is in my method for the reversal:
public static String printReverse(String str1){
return str1;
}
I know my method is just returning the same message, I did that intentionally as a place holder so that the code would run.
I need to know the most simplest way of doing the reversal, as all examples
I have seen use super complex ways of doing this.
Any help is appreciated.
You can use a StringBuilder, and call reverse on it.
public static String printReverse(String str1) {
return new StringBuilder(str1).reverse().toString();
}

How to use indexOf? Please help a beginner out

So I want to know what indexOf() does. As I want to use it in my program it find out how many vowels are in a word that the user inputs.
public static boolean methodCheck(char a){
return "AEIOUaeiou".indexOf(a) != -1;
}
But that doesnt seem to work at all hahah. as I have no idea what indexOf() actually does. anyway here is my program so far(sorry if its bad I'm really new). I left 5 questions too that would help me a lot! please and thank you for your help :D
import java.util.Scanner;
public class vowelCounter {
private static String input = methodInput(); //1. is there any other way to make a global Scanner?
public static void main(String[] args){
System.out.println("Enter word");
System.out.println(input);
System.out.println("This word has" + methodCheck('a')); //2. what should i put in my parameters?
}
public static boolean methodCheck(char a){
return "AEIOUaeiou".indexOf(a) != -1; //3. what does this line do?
}
public static String methodInput(){
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
return input;
//4. the output is 'hastrue' why is that?
//5. how can i make this program better?
}
}
If you don't know what a method does, then the solution is to go look at what it does. For example, the java documentation will tell you that
public int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character
In either case, if no such character occurs in this string, then -1 is returned.
How you're using it is not necessarily wrong, considering how the method returns -1 if the character wasn't found. But if you want to check how many vowels there are in a word that the user enters, it wouldn't be right to check whether the word they entered is in the string of vowels.
All the standard Java libraries, classes and methods have Javadoc that describes what they do.
All you need to do is look up the Javadoc and they describe it.
In this case the Javadoc is at: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(int)
Your first step with any question like this should always be the documentation, then if that doesn't work try doing a web search looking for examples. For example 5 seconds on google putting in "java indexOf example" found me:
http://www.tutorialspoint.com/java/java_string_indexof.htm
Then if that doesn't work you can try asking the question here.
When you have the word boolean before the name of a method, that means that the method will return either the value true or the value false. And it's this true or false value that your program is printing out, on the same line as "This word has".
This particular method will return true if the character you pass to it is a vowel, or false otherwise. The method indexOf tells you which character of a String is the first one that is equal to the value that you pass in to the method. It returns 0 for the first character, 1 for the second character and so on. It returns -1 if none of the characters match. In this case, you're just checking whether the value returned by indexOf is or isn't -1 - in other words, whether the character is or isn't in the String "AEIOUaeiou".
indexOf(String str) Returns the index within this string of the first occurrence of the specified substring. If no such value of str exists, then -1 is returned.
For examples :
int num1 = "AEIOUaeiou".indexOf("a"); // it gives 5
int num2 = "AEIOUaeiou".indexOf("A"); // It gives 0
int num3 = "AEIOUaeiou".indexOf("z"); // It gives -1
1 Don't do that! Create a scanner in main, read input with it and then call your method(s).
2 How about countVowels(input)? You'd need to write an static int countVowels(String input) method.
3 Returns true since you pass in 'a'.
4 See number 3.
5 See number 2, and add a static boolean isVowel(char a).
Here is what the indexOf method does
string.indexOf(searchvalue,start)
Parameters
searchvalue : Required. The string to search for
start : Optional. Default 0. At which position to start the search
Return Value
Number : The position where the specified searchvalue occurs for the first time, or -1 if it never occurs
In simple terms, the index of method checks the first occurence of the value passed to it from the start position(if specified) and returns the position at which the value was first encountered in the string.
eg.
String s = "AEIOUaeiou";
s.indexOf("a"); //This would get a value of 5.
s.indexOf("v"); //This would get a value of -1, since it doesn't have the character v
To answer your questions,
You can directly declare the scanner as private and use it in the
entire program
`private static Scanner input = new Scanner(System.in);`
you can write a method that receives the String input by the user
and then checks if the String contains any of the vowels. You can
use indexOf or contains methods to check for the each vowel using
the indexOf method.
Already described above.
A better way to do it would be as follows.
public class vowelCounter{
public static void main (String[] args) {
Scanner keyboard = new Scanner (System.in); // No need to declare it as global. You use it only once.
System.out.println ("Enter word : "); //Prompt the user to enter a word
String input = keyboard.nextLine (); //Fetch the word that the user enters into a String
System.out.println ("This word has" + countVowel (input)); // Pass the string to the method to check if it has vowels.
}
private static int countVowel (String a) {
int count = 0;
String s = a.toLowerCase (); // convert the string to lower case so that you only have to check for the lower case characters
// Here you would need to check the number of times each vowel exists in the String and incremenet the count everytime.
return count;
}
}

Categories