Search code examples
javapalindrome

How to "bring back" whitespaces after using a line of code that ignores them? (Palindrome assignment)


I'm struggling to figure out exactly how I'd be able to place spaces back into the output of my code. For example, if the palindrome is "race car," I need to first ignore the spaces in that statement by using userInput = userInput.replace(" ","");, but then I need the program to still print "palindrome: race car" rather than "racecar". Would anyone be able to troubleshoot this for me? (Ignore the weird names for my variable, my professor doesn't believe my validity in my coding and thinks I copy other people so I use these unique phrases/words to make him know I'm not cheating.)

import java.util.Scanner;

public class LabProgram {
   public static void main(String[] args) {
   
   Scanner twice = new Scanner(System.in);
   String wasabi = twice.nextLine();
   String ibasaw = "";
   String[] split = wasabi.split(" ");
   wasabi = wasabi.replace(" ","");
   
   for(int i = wasabi.length()-1;i>=0;i--)
   {
      ibasaw=ibasaw+wasabi.charAt(i);
   }
   if(wasabi.toLowerCase().equals(ibasaw.toLowerCase()))
   {
      System.out.println("palindrome: " + wasabi);
   }
   else
   {
      System.out.println("not a palindrome: " + wasabi);
   }
 }
}

I tried inputs with spaces and String splitting but none of it worked.


Solution

  • You can use a third string variable to store to original/modified string:

    (See sushi)

    
    public class LabProgram {
       public static void main(String[] args) {
       
       Scanner twice = new Scanner(System.in);
       String sushi = twice.nextLine();
       String ibasaw = "";
       String wasabi = sushi.replace(" ","");
       
       for(int i = wasabi.length()-1;i>=0;i--)
       {
          ibasaw += wasabi.charAt(i);
       }
       if(wasabi.toLowerCase().equals(ibasaw.toLowerCase()))
       {
          System.out.println("palindrome: " + sushi);
       }
       else
       {
          System.out.println("not a palindrome: " + sushi);
       }
     }
    }
    

    If you don't want to use another variable, you can also use replace when comparing the strings instead of saving it to variable:

    public class LabProgram {
       public static void main(String[] args) {
       
       Scanner twice = new Scanner(System.in);
       String wasabi = twice.nextLine();
       String ibasaw = "";
       
       for(int i = wasabi.length()-1;i>=0;i--)
       {
          ibasaw += wasabi.charAt(i);
       }
       if(wasabi.toLowerCase().replace(" ", "").equals(ibasaw.toLowerCase().replace(" ", "")))
       {
          System.out.println("palindrome: " + wasabi);
       }
       else
       {
          System.out.println("not a palindrome: " + wasabi);
       }
     }
    }