Preventing statement in for loop from printing each iteration? - java

I have a program that takes whatever string is entered and prints it backwards. However, the statement I want to print prints after each iteration because it is in the for loop. However, when I move it outside the for loop, it doesn't recognize the variable "letter". How can I fix this?
import java.util.Scanner;
public class ReadBackwards {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String word;
char letter;
int counter, wordLength;
System.out.print("Please type a word: ");
word = keyboard.next();
wordLength = word.length();
for(counter = wordLength-1; counter >= 0; counter--) {
letter = word.charAt(counter);
System.out.print(word + " backwards is " + letter);
}
}
}

By appending each letter to something like a StringBuilder and then printing that. You should also try to limit the scope of your variables (and I'm not sure I see the value in most of them). You could do
String word = keyboard.next();
StringBuilder sb = new StringBuilder();
for (int counter = word.length() - 1; counter >= 0; counter--) {
sb.append(word.charAt(counter));
}
System.out.println(word + " backwards is " + sb.toString());
And, that might be further simplified to
String word = keyboard.next();
System.out.println(word + " backwards is "
+ new StringBuilder(word).reverse().toString());

One option would be to use System.out.print() instead of println() and just print single characters in a single row:
System.out.println(word + " backwards is: ");
for (counter = wordLength-1; counter >= 0; counter--) {
letter = word.charAt(counter);
System.out.print(letter);
}
Demo

Related

A logic error is causing a statement to be printed twice in a While Loop

So the problem that I am currently running into is that the statement "Enter your command (reverse, replace first, replace last, remove all, remove)" is printing twice after I go through all the steps.
What I believe is happening is the loop is executing twice but I don't know why. Any help would be appreciated in solving this problem. Sorry in advance if my code formatting is bad still learning how to properly format.
import java.util.Scanner;
public class StringChangerenter {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
// Output Variables
String userInput = "";
// Variables
String removeChar = "", removeAllChar = "";
int removeIndex = 0;
// First Output
System.out.println("Enter the string to be manipulated");
userInput = keyboard.nextLine();
String command = "";
// While loop
while (!command.equalsIgnoreCase("quit")) {
// Output
System.out.println("Enter your command (reverse, replace first, replace last, remove all, remove)");
command = keyboard.nextLine();
if (command.equalsIgnoreCase("remove")) {
System.out.println("Enter the character to remove");
removeChar = keyboard.nextLine();
int totalCount = 0;
for (int j = 0; j < userInput.length(); j++) {
if (userInput.charAt(j) == removeChar.charAt(0)) {
totalCount = totalCount + 1;
}
}
System.out.println("Enter the " + removeChar
+ " you would like to remove (Not the index - 1 = 1st, 2 = 2nd, etc.):");
removeIndex = keyboard.nextInt();
int currentIndex = 1;
if (removeIndex <= totalCount) {
for (int i = 0; i < userInput.length(); i++) {
if (userInput.charAt(i) == removeChar.charAt(0)) {
if (currentIndex == removeIndex) {
String firstpartOfString = userInput.substring(0, i);
String secondpartOfString = userInput.substring(i + 1, userInput.length());
System.out.println("The new sentence is " + firstpartOfString + secondpartOfString);
userInput = firstpartOfString + secondpartOfString;
break;
} else {
currentIndex = currentIndex + 1;
}
}
}
} else {
System.out.println("Can't find " + removeChar + " occuring at " + removeIndex + " int the string.");
}
// Remove All Code
} else if (command.equalsIgnoreCase("remove all")) {
System.out.println("Enter the character to remove");
removeAllChar = keyboard.next();
String newString = "";
for (int i = 0; i < userInput.length(); i++) {
if (userInput.charAt(i) != removeAllChar.charAt(0)) {
newString = newString + userInput.charAt(i);
}
}
userInput = newString;
System.out.println("The new sentence is " + userInput);
}
// Bracket for while loop
}
}
}
The reason you are getting two entries after you've processed a character, is that you have not fully read the line containing the character.
Specifically, you use keyboard.nextInt(); in the upper branch, and keyboard.next(); in the lower branch. While these read the next integer and character, respectively, they do not process the end of line marker.
Then when you reach the top of the loop, you call keyboard.nextLine() which processes whatever characters occurred after the int (or character, in the remove all case) until the end of line marker. With the expected user input, that's just an empty string.
To fix this, you need to ensure you read all the way through the keyboard.nextLine() in the cases where you are reading only integers, or a single character.
what is happening is, the condition for you while loop is
while (!command.equalsIgnoreCase("quit"))
which in english mean, as long as command is not equal to "quit" then run this loop.
Inside the loop, command is never actually set to "quit". ex if I give input string as "abcde" and ask to remove "c" at position 1.
Then your logic sets command to "remove" here
command = keyboard.nextLine();
and then prints the final value as "abde". Now when the loop ends, command is still "remove" and hence the loop executes again.
A possible solution is to explicitly ask the user if he wants to retry using a do while loop. Also just a tip, i see you have used nextInt. It is advisable to use a nextLine immediately after next int. see this for the reason why: Java Scanner doesn't wait for user input
this is what you code would be if you explicitly took user consent if you want to run any more commands:
public static void main (String[] args) throws java.lang.Exception
{
Scanner keyboard = new Scanner(System.in);
// Output Variables
String userInput = "";
// Variables
String removeChar = "", removeAllChar = "";
int removeIndex = 0;
// First Output
System.out.println("Enter the string to be manipulated");
userInput = keyboard.nextLine();
String command = "";
String retry = "";
// While loop
do {
// Output
System.out.println("Enter your command (reverse, replace first, replace last, remove all, remove)");
command = keyboard.nextLine();
if (command.equalsIgnoreCase("remove")) {
System.out.println("Enter the character to remove");
removeChar = keyboard.nextLine();
int totalCount = 0;
for (int j = 0; j < userInput.length(); j++) {
if (userInput.charAt(j) == removeChar.charAt(0)) {
totalCount = totalCount + 1;
}
}
System.out.println("Enter the " + removeChar
+ " you would like to remove (Not the index - 1 = 1st, 2 = 2nd, etc.):");
removeIndex = keyboard.nextInt();
keyboard.nextLine();
int currentIndex = 1;
if (removeIndex <= totalCount) {
for (int i = 0; i < userInput.length(); i++) {
if (userInput.charAt(i) == removeChar.charAt(0)) {
if (currentIndex == removeIndex) {
String firstpartOfString = userInput.substring(0, i);
String secondpartOfString = userInput.substring(i + 1, userInput.length());
System.out.println("The new sentence is " + firstpartOfString + secondpartOfString);
userInput = firstpartOfString + secondpartOfString;
break;
} else {
currentIndex = currentIndex + 1;
}
}
}
} else {
System.out.println("Can't find " + removeChar + " occuring at " + removeIndex + " int the string.");
}
// Remove All Code
} else if (command.equalsIgnoreCase("remove all")) {
System.out.println("Enter the character to remove");
removeAllChar = keyboard.next();
String newString = "";
for (int i = 0; i < userInput.length(); i++) {
if (userInput.charAt(i) != removeAllChar.charAt(0)) {
newString = newString + userInput.charAt(i);
}
}
userInput = newString;
System.out.println("The new sentence is " + userInput);
}
System.out.println("Do you want to go again?");
retry = keyboard.nextLine();
// Bracket for while loop
}while("yes".equalsIgnoreCase(retry));
}

How to end a do while loop with a user inputted string?

public static void main (String[] args)
{
do {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a string: ");
String sentence = keyboard.nextLine();
System.out.print("Enter a letter: ");
String fullLetter = keyboard.nextLine();
char letter = fullLetter.charAt(0);
keyboard.nextLine();
int amount = 0;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (ch == letter) {
amount++;
}
}
System.out.println(letter + " appears " + amount + " times in " + sentence);
System.out.print("Continue? ");
String decide = keyboard.nextLine();
} while (decide.equals("yes"));
}
}
I want the user to input either "yes" or "no" at the end of the loop, then I want that input to determine whether or not the program will loop again. As it stands right now, the the last line of my code isn't working. I've looked around and I'm not sure what I should do to fix this.
You need to declare your variable decide outside the loop and initialize inside:
String decide;
do {
//do something ...
decide = keyboard.nextLine();
} while (decide.equals("yes"));
You should use keyboard.next() to read a String instead of keyboard.nextLine()
next() only reads a word, nextLine() reads the whole line including Enter so it will never be equal to "yes"
You must declare declare the string describe outside of the do/while loop, otherwise it is a local variable of the do/while loop, and cannot be accessed by the do testing portion. Simply using
public static void main(String[] args) {
String decide;
do {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a string: ");
String sentence = keyboard.nextLine();
System.out.print("Enter a letter: ");
String fullLetter = keyboard.nextLine();
char letter = fullLetter.charAt(0);
keyboard.nextLine();
int amount = 0;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (ch == letter) {
amount++;
}
}
System.out.println(letter + " appears " + amount + " times in "
+ sentence);
System.out.print("Continue? ");
decide = keyboard.nextLine();
} while (decide.equals("yes"));
}
will solve your problem.
You has to define your variable decide outside of the loop:
String decide = null
do {
....
decide = keyboard.nextLine();
} while (decide.equals("yes"));

Slicing a string

I'm trying to slice a string for the first time.
With this code, if I input, for example 'one two three' it works fine until the last word.
This is the last few lines of the output:
Current word is thr
Sentence is now e
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.substring(String.java:1907)
at TestCurr.main(testCurrentWord.java:18)
Has anyone any idea why it does that to the last word?
class TestCurr
{
public static void main (String []args)
{
String s;
int i;
String currentWord;
int length;
int spacePos;
System.out.println("Enter a sentence ");
s = EasyIn.getString();
spacePos = s.indexOf(" ");
length = s.length();
for (i = length -1; i >= 0; i--)
{
currentWord = s.substring(0,spacePos);
s = s.substring(spacePos +1);
System.out.println("Current word is " + currentWord);
System.out.println("Sentence is now " + s);
}
}
}
First of all, you call
spacePos = s.indexOf(" ");
length = s.length();
only once, but these values should change with each iteration of the loop. Furthermore,
s.substring(spacePos +1);
with
spacePos == s.length()-1
means you are passing an index beyond the end of the string as the start index for substring(). Once you fix the first error, this will be your next exception.
Your problem is that you only get the index of the space once. This causes the program to cut the string every three characters, as the first word is three letters long. You need to update spacePos after each iteration.
I believe your problem is in your usage of your spacePos variable.
Outside the loop, you initialize the variable like so:
spacePos = s.indexOf(" ");
Which in your example string of "one two three", yields 3.
But then inside your loop, you never set the variable again, based on what whatever is left that you haven't processed.
Try re-calculating spacePos's value inside the loop and your problem should go away.
Your current approach is too error prone.
And you have too many variables.
Try this just as an idea.
class TestCurr {
public static void main(String[] args) {
String s = null;
System.out.println("Enter a sentence: ");
s = " one two three ";
System.out.println("|" + s + "|");
int i = 0;
int j = 0;
while (true){
while (i<s.length() && s.charAt(i)==' ') i++;
j = i;
if (i>=s.length()) break;
while (i<s.length() && s.charAt(i)!=' ') i++;
System.out.println("Current word is: [" + s.substring(j, i)+ "]");
System.out.println("Sentence is now: [" + s.substring(i) + "]");
if (i>=s.length()) break;
}
}
}
As others have stated, you only get the index once. But I'm curious, why re-invent the wheel?
String s = "one two three";
String[] split = s.split(" ");
for (String out : split) {
System.out.println("Word: " + out);
}

Palindrome program is not giving the correct output in Java

List item
I created a Palindrome program in Java that takes a word or words entered by the user and puts them into an array. It then takes the reversed input and puts it into another array. I then check to see if the two words are the same.
My problem is that the program is changing one of the letters so that it is always true and it's iterating too many times. Any ideas as to what in my code is causing this?
public static boolean isPalindrome(char[] a, int used){
char[] original = a;
int newNumber = used - 1;
for(int i = 0; i <= newNumber; i++){
a[i] = a[newNumber - i ];
System.out.println("Your original word was: " + String.valueOf(original));
System.out.println("Backwards, your word is: " + String.valueOf(a));
}
if(String.valueOf(original).equalsIgnoreCase(String.valueOf(a))){
System.out.println("Your word or words are palindromes.");
}else{
System.out.println("Your word or words are not palindromes");
}
return(String.valueOf(original).equalsIgnoreCase(String.valueOf(a)));
}
public void userInput(){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a word or words that you believe are palindromes: ");
word = keyboard.next();
word = word.replaceAll("\\W","");
int length = word.length();
char[] p = new char[length];
for(int i = 0; i < length; i++){
p[i] = word.charAt(i);
}
Palindrome.isPalindrome(p, length);
}
This is my output when I type in "Candy."
Your original word was: yandy
Backwards, your word is: yandy
Your original word was: ydndy
Backwards, your word is: ydndy
Your original word was: ydndy
Backwards, your word is: ydndy
Your original word was: ydndy
Backwards, your word is: ydndy
Your original word was: ydndy
Backwards, your word is: ydndy
Your word or words are palindromes
Thanks to everyone that answered!
Here is the correct code that works, although not as efficient as it could be:
public static boolean isPalindrome(char[] a, int used){
char[] original = a;
char[] newArray = new char[used];
int newNumber = used - 1;
for(int i = 0; i <= newNumber; i++){
newArray[i] = a[newNumber - i ];
}
System.out.println("Your original word was: " + String.valueOf(original));
System.out.println("Backwards, your word is: " + String.valueOf(newArray));
if(String.valueOf(original).equalsIgnoreCase(String.valueOf(newArray))){
System.out.println("Your word or words are palindromes.");
}else{
System.out.println("Your word or words are not palindromes");
}
return(String.valueOf(original).equalsIgnoreCase(String.valueOf(newArray)));
}
In your Palindrome function:-
for(int i = 0; i <= newNumber; i++){
a[i] = a[newNumber - i ];
System.out.println("Your original word was: " + String.valueOf(original));
System.out.println("Backwards, your word is: " + String.valueOf(a));
}
here you are replacing the existing array.
You can even try the following code:-
String original, reverse="";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to check if it is a palindrome");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
Problem is with your code a[i] = a[newNumber - i ]; you are changing the existing array.
First create new array and then put your reverse string in that.
public static boolean isPalindrome(char[] a, int used) {
char[] newA = new char[a.length];
int newNumber = used - 1;
for (int i = 0; i <= newNumber; i++) {
newA[i] = a[newNumber - i];
System.out.println("Your original word was: " + String.valueOf(a));
System.out.println("Backwards, your word is: " + String.valueOf(newA));
}
if (String.valueOf(String.valueOf(newA)).equalsIgnoreCase(String.valueOf(a))) {
System.out.println("Your word or words are palindromes.");
} else {
System.out.println("Your word or words are not palindromes");
}
return (String.valueOf(String.valueOf(newA)).equalsIgnoreCase(String.valueOf(a)));
}
There are many other efficient ways to write this code.
If you want to check palindrome in this easy way, you can try with StringBuilder.
public static boolean isPalindrome(String input) {
StringBuilder sb=new StringBuilder(input);
return input.equals(sb.reverse().toString());
}
In your case change your isPalindrome method as follows
public static void isPalindrome(char[] a, int used){
char[] newArr = new char[a.length]; // create a new array in same length as a
int newNumber = used - 1;
System.out.println("Your original word was: " + String.valueOf(a));
for(int i = 0; i <= newNumber; i++){
newArr[i] = a[newNumber - i ];
}
System.out.println("Backwards, your word is: " + String.valueOf(newArr));
if(String.valueOf(newArr).equalsIgnoreCase(String.valueOf(a))){
System.out.println("Your word or words are palindromes.");
}else{
System.out.println("Your word or words are not palindromes");
}
}
there is no need to copy the array (you only copied the referenz), only creat a new array with the same size and use a as the original array.
char[] reverse = new char[used];
put the system.out, out of the for loop:
for(int i = 0; i <= newNumber; i++){
reverse[i] = a[newNumber - i ];
}
System.out.println("Your original word was: " + String.valueOf(a));
System.out.println("Backwards, your word is: " + String.valueOf(reverse));
the whole isPalindrom function:
public static boolean isPalindrome(char[] a, int used){
char[] reverse = new char[used];
int newNumber = used -1;
for(int i = 0; i <= newNumber; i++){
reverse[i] = a[newNumber - i ];
}
System.out.println("Your original word was: " + String.valueOf(a));
System.out.println("Backwards, your word is: " + String.valueOf(reverse));
if(String.valueOf(reverse).equalsIgnoreCase(String.valueOf(a))){
System.out.println("Your word or words are palindromes.");
}else{
System.out.println("Your word or words are not palindromes");
}
return(String.valueOf(reverse).equalsIgnoreCase(String.valueOf(a)));
}
The problem is in isPalindrome method where you assigned
char[] original = a;
The char[] variables are references. By setting original = a, you're copying the reference, so now both the arrays are pointing to the same chunk of memory.
Now, when you modify a, original also gets modified because both are pointing to same memory.
You can fix this by creating a new instance as shown below:
char[] original = new char [a.length];
System.arraycopy( a, 0, original, 0, a.length );

Infinite Loop not working

The code works the first time through. But after that, the output doesnt work.
The main goal of this is to create an infinite loop, of asking a user for a phrase, then a letter. Then, to output the number of occurences of the letter in the phrase.
Also - - how would i go about breaking this loop by entering a word?
Scanner in = new Scanner(System.in);
for (;;) {
System.out.println("Enter a word/phrase");
String sentence = in.nextLine();
int times = 0;
System.out.println("Enter a character.");
String letter = in.next();
for (int i = 0; i < sentence.length(); i++) {
char lc = letter.charAt(0);
char sc = sentence.charAt(i);
if (lc == sc) {
times++;
}
}
System.out.print("The character appeared:" + times + " times.");
}
Remove the for loop and replace it with a while.
The while loop should check for a phrase and it will drop out automatically when the phrase is met.
So something like
while (!phraseToCheckFor){
// your code
}
This sounds like homework so I won't post all the code but this should be enough to get you started.
If you need an infinite loop, just do this:
for(;;) { //or while(true) {
//insert code here
}
You can break the loop by using the break statement, for example like this:
for(;;) {
String s = in.nextLine();
if(s.isEmpty()) {
break; //loop terminates here
}
System.out.println(s + " isn't empty.");
}
In order for your program to run correctly, you need to consume the last new line character. You can do this by adding a call to nextLine.
Working example,
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
for (;;) {
System.out.println("Enter a word/phrase");
String sentence = in.nextLine();
if (sentence.trim().equals("quit")) {
break;
}
int times = 0;
System.out.println("Enter a character.");
String letter = in.next();
for (int i = 0; i < sentence.length(); i++) {
char lc = letter.charAt(0);
char sc = sentence.charAt(i);
if (lc == sc) {
times++;
}
}
System.out.println("The character appeared:" + times + " times.");
in.nextLine();//consume the last new line
}
}

Categories