Reputation: 5
I'm a beginner in Java and I have to write a program that allows the user to enter in words, then the program returns the word backwards until the user writes "stop". Every time the user enters a word, java outputs it backwards plus the previous word which is outputted and I don't want that. For example, if I put input pots it outputs, stop if I print cat it outputs potstac How can I just get java to just output the words backwards without adding it on to the prior words For example, i want to input in pots it should output, stop i want to print cat it should output, tac
import java.util.*;
public class javapdf2413 {
public static void main (String [] args) {
Scanner in = new Scanner (System.in);
String wordEntered = "";
String backWords = "";
do {
System.out.println("Enter in a word");
wordEntered = in.next();
for (int i = wordEntered.length()-1; i>=0; i--) {
backWords = backWords + wordEntered.charAt(i);
}
System.out.println(backWords);
}while(!wordEntered.equals("stop"));
}
}
Upvotes: 0
Views: 1559
Reputation: 91
Just beware - Strings are immutable objects. Use it with right use case and approach. Try to use StringBuilder for non concurrent code as much as possible where ever you can.
Upvotes: 0
Reputation: 468
Just initialize your variables inside your do loop
String wordEntered;
String backWords;
do {
wordEntered = "";
backWords = "";
System.out.println("Enter in a word");
wordEntered = in.next();
for (int i = wordEntered.length()-1; i>=0; i--) {
backWords = backWords + wordEntered.charAt(i);
}
System.out.println(backWords);
}while(!wordEntered.equals("stop"));
Upvotes: 0
Reputation: 256
Try to do this with while loop
import java.util.Scanner;
public class TestRun {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String wordEntered = "";
String backWords = "";
while (true) {
System.out.println("Enter in a word");
wordEntered = in.next();
if (wordEntered.equals("stop")) {
break;
} else {
for (int i = wordEntered.length() - 1; i >= 0; i--) {
backWords = backWords + wordEntered.charAt(i);
}
System.out.println(backWords);
backWords = "" ;
}
}
}
}
Upvotes: 0
Reputation: 1590
You'll need to set backWords
back to an empty string at the beginning of the do
loop. If you don't it will just concatenate onto the end of the previous string - which is what you said is happening. Setting it back to ""
at the beginning of the loop body will essentially "reset" it for the next word.
Like this:
do {
backWords = "";
System.out.println("Enter in a word");
wordEntered = in.next();
for (int i = wordEntered.length()-1; i>=0; i--) {
backWords = backWords + wordEntered.charAt(i);
}
System.out.println(backWords);
}while(!wordEntered.equals("stop"));
Upvotes: 1