Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 12 of 12

Thread: For-looping, if-else statements, charAt(), etc. Beginner programming problem

  1. #1
    Junior Member
    Join Date
    Sep 2011
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Angry For-looping, if-else statements, charAt(), etc. Beginner programming problem

    This is what I was assigned:
    Programming Problem: Wild Equality

    For this assignment you are to write a single class, with main included. The job of the class is as follows: you are to read in two strings from the keyboard, string1 and string2, and then you are to determine if string1 and string2 are equal, character for character. Your program should report its answer as true or false. Note that if the strings are different lengths, then they are definitely not equal.

    There are two "catches" to the problem. First, capitalization in your solution should not matter. Thus if the strings are "dog" and "DoG", then your program should report true - they are equal. The second catch concerns a wild card symbol, here the character '*'. If * appears in one of the strings, then it can match any other character. So "Dog" and D*g" should be judged as equal, since the *, as a wild card, matches any other character, in this case the 'o'.

    More examples:

    Dog and d** -> true
    Dog and *** -> true
    Dog and **** -> false (different lengths)
    bla*k and B***k -> true


    One further suggestion: use theScanner method nextLine() rather than the method next() for reading input.

    Your solution should be in a single class containing main, and that class MUST BE called WildEquality. Enter (paste) your code in the box below. Note that the import statement for Scanner is provided. DO NOT include any import statements in the code you submit.

    import java.util.Scanner;

    Okay. So I imported the scanner easily, and I also converted both strings to lowercase already. With the code I have now, I can type in two of the same word, with DIFFERENT capitalization, and the program recognizes that they are the same word. I am STILL having problems with the wildcard method however.
    import java.util.Scanner;
    public class WildEquality{
      public static void main(String[] args){
        Scanner scan=new Scanner(System.in); //creates a Scanner object
        String string1=scan.nextLine();
        String string2=scan.nextLine();
        string1=string1.toLowerCase();
        string2=string2.toLowerCase();
        string1.toCharArray();
        string2.toCharArray();
        char wildcard='*';
        for (int j=0; j<string1.length();j++){
          if (string1.charAt(j)==wildcard) wildcard=string2.charAt(j);
        }
        for (int k=0; k<string2.length();k++){
          if (string2.charAt(k)==wildcard) wildcard=string1.charAt(k);
        }
        if ((string1.length()==string2.length())&&(string1.equals(string2))) {
          System.out.println("true");
        } else {
          System.out.println("false");
        }
      }
    }

    This is what I have so far. This wildcard stuff is confusing me so much. I would literally appreciate ANY feedback! Thanks in advance!


  2. #2
    Super Moderator Sean4u's Avatar
    Join Date
    Jul 2011
    Location
    Tavistock, UK
    Posts
    637
    Thanks
    5
    Thanked 103 Times in 93 Posts

    Default Re: For-looping, if-else statements, charAt(), etc. Beginner programming problem

    The easiest way to tackle this might be to check first if *either* char is a wildcard, and if it is go on to the next char.

  3. #3
    Junior Member
    Join Date
    Sep 2011
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: For-looping, if-else statements, charAt(), etc. Beginner programming problem

    Quote Originally Posted by Sean4u View Post
    The easiest way to tackle this might be to check first if *either* char is a wildcard, and if it is go on to the next char.
    So wait, how would I check for something like that? A for loop that can check both strings at once and then ONLY continue if there is a wildcard? Maybe I misunderstood what you were saying, but I've literally been in this course for three weeks and we just started for looping this week, so it's still a little fuzzy! Thank you though!

  4. #4
    Super Moderator Sean4u's Avatar
    Join Date
    Jul 2011
    Location
    Tavistock, UK
    Posts
    637
    Thanks
    5
    Thanked 103 Times in 93 Posts

    Default Re: For-looping, if-else statements, charAt(), etc. Beginner programming problem

    You should only be using one for loop for this like (pseudo code)
    check strings are same length
    for (all characters or positions in one of the strings)
      if (character in first string is *)
        great!
      else if (character in second string is *)
        great!
      else if (character in first string is same as character in second string)
        great!
      else
        strings are different - stop comparing

  5. #5
    Junior Member
    Join Date
    Sep 2011
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: For-looping, if-else statements, charAt(), etc. Beginner programming problem

    Quote Originally Posted by Sean4u View Post
    You should only be using one for loop for this like (pseudo code)
    check strings are same length
    for (all characters or positions in one of the strings)
      if (character in first string is *)
        great!
      else if (character in second string is *)
        great!
      else if (character in first string is same as character in second string)
        great!
      else
        strings are different - stop comparing
    Okay, so I already have part of the code that will check to see if the strings are the same length, that was the easy part. I've done this from the pseudo code you provided, but I'm still confused as to what I should be putting in place of the "great!"s. If those statements are true, then great! but I'm not sure how to translate something like that into code!

        for (int j=0; j<string1.length();j++){
          if (string1.charAt(j)==wildcard) 
            wildcard=string2.charAt(j); 
          else 
            if (string2.charAt(j)==wildcard)_________
          else
            if (string1.charAt(j)==string2.charAt(j))__________
          else 
            string1!=string2; __________
        }

    The string1!=string2; at the end does not work, I'm aware. I'm sure there's a very simple reason why, but I figured it'd be fine just as a placeholder for now until I figure out the wildcard part. Blahh, thank you for being to patient!

  6. #6
    Super Moderator Sean4u's Avatar
    Join Date
    Jul 2011
    Location
    Tavistock, UK
    Posts
    637
    Thanks
    5
    Thanked 103 Times in 93 Posts

    Default Re: For-looping, if-else statements, charAt(), etc. Beginner programming problem

    'If' conditions evaluate to a boolean - one of two values. If you're studying computing, you should probably read up on DeMorgan's Laws for the background to why this code works out this way, but you can either try to invalidate the inputs and nest those ifs:
    if (/* char in string1 is not '*' */)
      if (/* char in string2 is not '*' */)
        if (/* chars don't match */)
          fail
    or AND them:
    if (/* char in string1 is not '*' */ AND /* char in string2 is not '*' */ AND /* chars don't match */)
      fail
    or you can look from the point of attempting to validate the inputs, in which case any valid condition is enough. In these kinds of cases I often - maybe it's not the most stylish thing to do - use else if and 'do nothing' as long as a valid condition is met:
    if (/* string1's char is * */)
    { /* do nothing */ }
    else if (/* string2's char is * */)
    { /* that's cool! */ }
    else if (/* the two chars match */)
    { /* excellent! */ }
    else
      fail
    the comments in curly brackets are valid Java, not much else is in that code. The idea is that the loop should keep checking the remaining characters as long as the ones tested so far are good. As soon as the 'else' option is hit then you need to (usually) somehow remember or report that the input is invalid, and terminate the loop at that point (there's no point in continuing). Forum rules say I'm not allowed to spoonfeed, but you can exit a loop with the 'break' statement. Don't tell anybody I told you - but do put the link to this thread in your homework assignment if you get anything of value from it. If you surprise your tutor with excellent code, she will also want to check that someone didn't just give it to you like pureed tasty vegetables.

  7. #7
    Junior Member
    Join Date
    Sep 2011
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: For-looping, if-else statements, charAt(), etc. Beginner programming problem

    That seriously helped so much, thank you! I didn't end up needing to use the break statement anyway, but I do have one more question. Here's what I have right now:
    import java.util.Scanner;
    public class WildEquality{
      public static void main(String[] args){
        Scanner scan=new Scanner(System.in); //creates a Scanner object
        String string1=scan.nextLine();
        String string2=scan.nextLine();
        string1=string1.toLowerCase();
        string2=string2.toLowerCase();
        boolean result=false;
        if (string1.length()!=string2.length()){
          result=false;
          System.out.println(result);
        }
        else
          for (int j=0; j<string1.length();j++){
          if (string1.charAt(j)==string2.charAt(j)){
            result=true;
            System.out.println(result);
          }
          else if (string1.charAt(j)=='*')
          {}
          else if (string2.charAt(j)=='*')
          {}
          else
            result=false;
            System.out.println(result);
          }
        }
      }

    I'm editing this post because I just figured out my original problem. Having another problem though. When the if-else statements nested in the for-loop are "true", the program output has way too many "true"s. I only want one. Is there a way to wait until the END of the loop before the program prints these as true? That way only one "true" prints?

    Thank you for all of your help, seriously. My class schedule limits the time I can go to office hours, so I really appreciate the help!
    Last edited by ayelleeeecks; September 29th, 2011 at 06:13 PM.

  8. #8
    Super Moderator Sean4u's Avatar
    Join Date
    Jul 2011
    Location
    Tavistock, UK
    Posts
    637
    Thanks
    5
    Thanked 103 Times in 93 Posts

    Default Re: For-looping, if-else statements, charAt(), etc. Beginner programming problem

    You would normally use that 'break' - or put the validity condition in your loop expression (for, while, do etc) - so that your loop stops as soon as the input is invalid because there's no more point in checking.
    output has way too many "true"s.
    It looks like the indentation in your code was meant to associate the two lines of code together:
          else
            result=false;
            System.out.println(result);
          }
    Java doesn't work like that - it needs { and } to create blocks of code. (I think Python may work like that and perhaps a few other languages). That last } in your code snippet above is the closing curly bracket for the 'for' loop. Since you set 'result' to flag that the input is invalid, you could wait until the for loop terminates and then do System.out.prin... - just switch the last two lines above with each other so that the System.out.prin... is after the for loop's closing curly bracket.

  9. #9
    Junior Member
    Join Date
    Sep 2011
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: For-looping, if-else statements, charAt(), etc. Beginner programming problem

    Okay, that makes sense. So now I have:
    import java.util.Scanner;
    public class WildEquality{
      public static void main(String[] args){
        Scanner scan=new Scanner(System.in); //creates a Scanner object
        String string1=scan.nextLine();
        String string2=scan.nextLine();
        string1=string1.toLowerCase();
        string2=string2.toLowerCase();
        boolean result=false;
        if (string1.length()!=string2.length()){
          result=false;
        }
        else
          for (int j=0; j<string1.length();j++){
          if (string1.charAt(j)==string2.charAt(j)){
            result=true;
          }
          else if (string1.charAt(j)=='*')
          {}
          else if (string2.charAt(j)=='*')
          {}
          else
            result=false;
          }
          System.out.println(result);
        }
      }

    The code works for every example the assignment requires EXCEPT this one:
    Dog and *** -> true
    And I can't figure out why. The loop should check and ignore every "*" starting with the character at position 0... so I'm not sure why it's doing this. Any idea?

  10. #10
    Super Moderator Sean4u's Avatar
    Join Date
    Jul 2011
    Location
    Tavistock, UK
    Posts
    637
    Thanks
    5
    Thanked 103 Times in 93 Posts

    Default Re: For-looping, if-else statements, charAt(), etc. Beginner programming problem

    I'm not sure why you picked that example - it seems like it should result in 'true'. I notice your logic is not quite right though. Your loop tests each character in turn to see if it is invalid for two-strings-matching. If *any* character is bad, then the whole match is bad. Otherwise, the strings are good. 'Otherwise' means you should default your flag to good. Your code should be:
    flag = valid
    for (all chars)
      if (char fails test)
        flag = invalid
    if (flag is valid)
      "The strings match!"
    else
      "That input is no good"
    Nowhere should there be an instruction which could reset the flag back to valid if a previous validity test had set it to invalid

  11. #11
    Junior Member
    Join Date
    Sep 2011
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: For-looping, if-else statements, charAt(), etc. Beginner programming problem

    Ahhh, thank you so much! Seriously, you have been a HUGE help, and I think all the examples work now! Thanks again! I reallllly appreciate it!

  12. #12
    Junior Member
    Join Date
    Oct 2011
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: For-looping, if-else statements, charAt(), etc. Beginner programming problem

    The boolean result value should be originally set to true rather than false.

    Where you have;
    boolean result = false;

    You should have;
    boolean result = true;

    If you do this the original value is set to true so "dog" and "***" will result in true rather than false. I struggled with this program for a while too. I'm in Moll's class also.

    Kevin

Similar Threads

  1. Can't think of a more specific title than: Problem with if statements
    By Omnamah in forum Loops & Control Statements
    Replies: 4
    Last Post: September 4th, 2011, 11:16 AM
  2. Problem with if statements
    By Omnamah in forum Loops & Control Statements
    Replies: 4
    Last Post: September 4th, 2011, 11:13 AM
  3. Beginner programming- strange problem
    By jkkruse in forum What's Wrong With My Code?
    Replies: 1
    Last Post: August 23rd, 2011, 05:39 AM
  4. Programming beginner
    By LatinaC09 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: October 15th, 2010, 01:33 PM
  5. what is charAt(0) ?
    By low1988 in forum Loops & Control Statements
    Replies: 5
    Last Post: October 11th, 2009, 10:03 AM

Tags for this Thread