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();
}
Related
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
This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
I already have a string let's say
String abc = "Stack";
Now, I want to modify this string using scanner class only ! So, user should to able to see existing string on console and then he can edit that string.
I tried this, but then it just replaces the existing string.
System.out.println("Edit the below string");
System.out.println(abc);
abc = scanner.nextLine();
How would I achieve it ?
Well the issue is you shouldn't with just a String. Your problem is the reason StringBuffer was created. Ideal solution:
StringBuffer buffer = new StringBuffer("Stack");
while (scanner.hasNextLine()){
buffer.append(scanner.nextLine());
System.out.println(buffer.toString());
}
String abc = buffer.toString(); //if you really need to save it to variable 'abc' for some reason.
Here is a terrible example if you hate your computer and can only user a String.
String abc = "Stack";
while (scanner.hasNextLine()){
abc += scanner.nextLine();
System.out.println(abc);
}
The above is a terrible solution for memory reason.
I hope this helps
This question already has answers here:
How to split a String by space
(17 answers)
Closed 5 years ago.
public void display()
{
super.display();
String str = super.getChoices();
System.out.println(str);
while(!str.equals(""))
{
int a = str.indexOf(" ");
System.out.println(str.substring(0, a));
String sentence = str.replaceFirst(str, str.substring(a));
System.out.println(sentence);
}
}
I have a String str containing "Apple Banana Orange". I want to system out print these fruits separately because they are each a choice to a question stored in a single variable. How can I do this? The code above is my failed attempt because the substring doesn't update the str variable rather creates a new string. I can't use a loop and I can't make it dynamic and thus not use it.
You need to change str as well:-
while(!str.equals("") ) {
int a = str.indexOf(" ");
System.out.println(str.substring(0, a));
String sentence = str.replaceFirst(str, str.substring(a));
System.out.println(sentence);
str = str.substring(a); // Remove the bit of str that we've processed.
}
(Untested, but you get the idea). You obviously also need to check if str actually contains a space and drop out.
If i understand you correctly, you should try to use StringTokenizer
StringTokenizer st=new StringTokenizer("Apple Banana Orange");
while (st.hasMoreTokens()){
System.out.println(st.nextToken());
}
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
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
Below is a snippet of code from a class in a simple program I'm writing that plays a simple game of Blackjack. I don't understand why the hit method isn't executing whenever, upon execution of the program, I enter "hit". It goes to the else part of the statement every time regardless of what I enter. I even added a System.out.println statement to make sure that the strings matched. I feel like I must be making a very basic mistake but I just can't seem to figure it out.
System.out.println("Would you like to hit or stand?");
Scanner input = new Scanner(System.in);
String playerDecision = input.nextLine();
//System.out.println(playerDecision);
if(playerDecision == "hit") {
hit();
}
else { System.out.println("ERROR");
}
}
public void hit(){
player.makeHand(deck.draw());
System.out.println("You have the following cards: ");
player.getHand();
System.out.println("Your hand total is ");
System.out.println(player.findHandTotal());
}
Wrong string comparison. Try
if("hit".equals(playerDecision)) {