mercredi 24 février 2016

Show Characters shared between two strings

For a Java exercise I'm writing a program where the user enters two strings. The program then checks to see if the two strings share any similar characters and outputs them to the screen.

For example is Terrarium and Terraform are the two strings it should print t e r r a r. However when I run my program it always simply outputs all the characters in the first string. (In this case T e r r a f o r m.)

I suspect I'm creating a logical error based on a limited understanding of loops. But when I search for answers people seem to always use a similar method to my own.

Here is the code for your viewing:

  import java.util.Scanner;

  public class CountMatches 
  {
     public static void main(String[] args) 
     {
         Scanner keyboard = new Scanner(System.in);
         System.out.println(" Please enter a String >> ");
         String stringA = keyboard.nextLine();
         System.out.println(" Please enter another String >> ");
         String stringB = keyboard.nextLine();

         for(int counter = 0; counter < stringA.length(); counter++ )
         {
            char compareA = stringA.charAt(counter);
            char compareB = stringB.charAt(counter);
            //System.out.println(compareA);
            //System.out.println(compareB);
            //System.out.println("");

            if(compareA != compareB)
            {
                System.out.println("");
            }
            else if(compareA == compareB);
            {
                System.out.println(compareA);
                System.out.println("");
            }
        }
     }
  }

Aucun commentaire:

Enregistrer un commentaire