This question already has answers here:
Reverse a string in Java
(36 answers)
Closed 5 years ago.
I am having a slight issue with my String Reverse code, and I cannot seem to fix it. I have made a different way that works, involving a for-loop, and that seems to work fine. However, when I run this code, it always gives me a "null" before the reversed String. For example, when I run this and input "StackOverflow", I get an output of null wolfrevOkcatS" (without the Space). I do not understand why an error like this would happen, so I also added a "null" checker, which did not seem to work. For this null checker, I converted the char into an Ascii value before putting it into my reversed string, and then checked if it was 0. (The ascii value of null) However, this did not seem to work, so I did some research, and could not find anything on Overflow, so decided to ask this question. Sorry and apologies in advance if this is a very "dumb" question, as I am quite new to java, and do not know who to ask.
Thanks in advance,
- A novice Java Coder
import java.util.Scanner;
public class StringReverser
{
static String input, reversed;
int i;
public static void main(String[] args)
{
StringReverser ansh = new StringReverser();
ansh.grab();
ansh.reverse(input);
}
public void grab()
{
System.out.println("Enter a word to be reversed: ");
Scanner kys = new Scanner(System.in);
input = kys.next();
i = input.length();
}
public void reverse(String word)
{
if(i == 0)
{
System.out.println(reversed);
}
else
{
//if((int)(word.charAt(i-1)) == 0)
//{i--; reverse(input);}
reversed+=word.charAt(i-1);
i--; reverse(input);
}
}
}
That's because reserved is initialized to null by default.
if(i == 0)
{
System.out.println(reversed);
}
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
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.
use break statement under if(){} body. also your == comparison will give false, use str1.equals(str2) for comparison.
Your problem is you are comparing strings with ==.You have to use equals to write correct if statement.
if (end.equals("f")){...}
You could use the below code to check
if (end.equals("f")) { // end == "f" , it check the reference.
a = false;
}
This question already has answers here:
How to delete stuff printed to console by System.out.println()?
(15 answers)
Closed 3 years ago.
I’m trying to print a string, only for 1 second.
The first thing I looked for was a method for deleting a line of console - terminal, But don't find anything.
Then try to backspace 5 times for example for “hello” then print another string like “ ” to delete hello string, but I couldn’t find out how \b works for java.
Now I'm confused, how I actually can solve my problem.
Any idea for backspace?
Or deleting something that's already printed?
Yor can do it by writing carriage return character \r in equal number of the length of already printed string. It will place the cursor back but will not clear the line but as you will write new characters older will be cleared.
I'm not sure to exactly understand what you need, I hope this code will help:
class Main {
public static void main(String[] args) throws InterruptedException {
String text = "123456";
System.out.print(text);
Thread.sleep(1000);
backspace(text.length());
Thread.sleep(1000);
System.out.print(text);
Thread.sleep(1000);
arrowLeft(3);
Thread.sleep(1000);
System.out.print(text);
}
public static void backspace(int number){
for(int i=0; i<number; i++){
System.out.print("\b \b");
}
}
public static void arrowLeft(int number){
for(int i=0; i<number; i++){
System.out.print("\b");
}
}
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I am trying to separate each word in a string and then add them to a stack. Here is the code I wrote to do this. Every time I run the tester, it always returns an empty stack, but shouldn't the stack have <body> in it?
import java.util.Stack;
public class HTML3{
//main method
public static boolean checkBalance(String str) {
Stack<String> stack = new Stack<String>();
String[] words = str.split(" ");
for (int i = 0; i < words.length; i++) {
String tag = words[i];
if(tag=="<body>" || tag=="<hl>" || tag=="<center>" || tag=="<p>" || tag=="<ol>" || tag=="<li>") {
stack.push(tag);
}
}
return stack.isEmpty();
}
public static void main(String[]args)
{
checkBalance("<body> <li>");
}
}
You're close but == doesn't compare the Strings, it compares the objects in which case tag is a different object from "< body>" for example.
Use .equals() to compare Strings and it will work.
tag.equals("<body>")
If you learn to use the debugger or an IDE that provides code hints you can figure these things out on your own.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
This is the program
import java.util.Scanner; //imports class
public class blank2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean valid = true;
String ans;
ans = in.next(); //answer is a string
If you type in "y", it goes right to the else statement.
while (valid == true)
{
it always skips this statement
if (ans == "y")
{
System.out.println("it works");
valid = false;
{
else
{
System.out.println("no work");
valid = false;
{
}
}
}
It just wont work
if (ans == "y")
Don't compare strings with ==. That compares object references(the same string). Use:
if ("y".equals(answer))
instead. It will compare strings for equality(check if they are identical as opposed to the same one). I do not use answer.equals("y") due to the risk of a null pointer exception if answer was null for any reason.
In strings, don't use the ==, you can use compareTo instead.
if ("y".comprateTo(answer))
With this method you can check if they are the same, or if one is greater than the other.
let us know if you have questions
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
What am I doing wrong? After I compile and run the program, I type in my input and no matter what it is, the program always takes it as an incorrect input and says I'm wrong, here:
import java.util.Scanner;
public class mena3 {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
String Capitol;
System.out.print("Enter the capitol of Morocco: ");
Capitol = user_input.next();
if(Capitol == "Rabat") {
System.out.println("Good Job!");
}
else {
System.out.println("That is incorrect");
}
}
}
And after I put in Rabat, it says That is incorrect. If I put in l, it says That is incorrect. Why can't I win?
Don't compare Strings using ==. Use the equals(...) or the equalsIgnoreCase(...) method instead. Understand that == checks if the two objects are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. So instead of
if (fu == "bar") {
// do something
}
do,
if ("bar".equals(fu)) {
// do something
}
or,
if ("bar".equalsIgnoreCase(fu)) {
// do something
}
Voting to close this question as it's only been asked and answered umpteen million times on this site.
One of the most common mistakes in java. String require a .equals() rather than an ==.
Wrong:
if (str == "foo") {
}
Right:
if ("foo".equals(str)) { // done in this order to avoid NPE
}
Your code is perfect, only your comparison method is wrong. All other languages treats == as comparison operator. But in case of Java it is little bit tricky. Here in Java == is taken as comparison operator for objects, not a string variable.
So, to compare two Strings you have a method called `.equals() which is from String class it self.
hence you need to change your code accordingly,
import java.util.Scanner;
public class mena3
{
public static void main(String[] args)
{
Scanner user_input = new Scanner(System.in);
String Capitol;
System.out.print("Enter the capitol of Morocco: ");
Capitol = user_input.next();
// if(Capitol == "Rabat") // your previous code
if(Capitol .equals ( "Rabat") ) // new updated comparison code
{
System.out.println("Good Job!");
}
else
{
System.out.println("That is incorrect");
}
}
}