Results 1 to 3 of 3

Thread: Help

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Sep 2006
    Posts
    19

    Help

    I am having trouble with my looping. It keep looping over and over. can somebody help me. For example

    Enter the first string:
    tanning
    Enter the second string:
    tanned
    String Length of s1: 7
    String Length of s2: 6
    tanning follows tanned
    tanning follows tanned
    tanning follows tanned
    tanning follows tanned
    tanning follow tanned

    Another example is it tell me the names are the same and there not.

    Enter the first string:
    fish
    Enter the second string:
    feed
    String Length of s1: 4
    String Length of s2: 4
    The names are the same
    fish follow feed

    Here is my code

    Code:
    public class Strings
    {
    	public static void main(String[] args)
    	{
    		String s1, s2;
    			
    		Scanner scan = new Scanner (System.in);
    		
    		System.out.println("Enter the first string:");
    		s1 = scan.nextLine();
    		
    		System.out.println("Enter the second string:");
    		s2 = scan.nextLine();
    			
    		//Sting length of the characters
    		System.out.println("String Length of s1: " + s1.length());
    		System.out.println("String Length of s2: " + s2.length());
    
    		//Compare the characters
    		char ch1, ch2;
    			
    		for (int i = 0; (i < s1.length()) || (i < s2.length()); i++) { 
    	
    		ch1 = s1.charAt(i);
    	   ch2 = s2.charAt(i);
    		
    			if(ch1 < ch2){
    				System.out.print(s1 + " comes before " + s2);
    				return;
    			}
    				
    			if (ch1 > ch2){
    				System.out.print(s1 + " follow " + s2);
    				return;
    			}
    			if (s1.length()< s2.length()){ 
    				System.out.println(s1 + " comes before " + s2);
    		   }else if (s1.length() > s2.length()) {
    				  	   System.out.println(s1 + " follows " + s2);
    			}else
    					System.out.println("The names are the same"); 
    			}		
    	}
    }

  2. #2
    Frenzied Member DeadEyes's Avatar
    Join Date
    Jul 2002
    Posts
    1,196

    Re: Help

    If the characters are the same but the lengths different your not breaking out of the loop.

  3. #3

    Thread Starter
    Junior Member
    Join Date
    Sep 2006
    Posts
    19

    Re: Help

    Ok how do I get it to just say tanning follows tanned one time instead of it repeating more than once.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width