Results 1 to 3 of 3
  1. #1
    googgoo is offline Member
    Join Date
    Mar 2008
    Posts
    8
    Rep Power
    0

    Red face Help me please!!!

    I want to compare between char array and char
    charArray keeps {'A','B'}
    inputChar keeps 'A'
    I want to compare charactor by charactor.
    I expect this code below result is :
    >>index[0] equals
    >>index[1] not equals
    but when compile this code result is:
    >>index[0] equal
    I should to solve this problem?

    Java Code:
    //compare 2  char  with for loop
    import java.util.Arrays;
    class TestCheckMethod{
        public static void main (String args[]){
            String str = "AB";
            int len,len2;
            char[] charArray = str.toCharArray();
            char inputChar;
            inputChar = 'B';
            System.out.print("\n");
            System.out.print("String is  "+str);
            System.out.print("\n");
            System.out.print("\n");
            
            for(int i = 0;i<charArray.length;i++){
                System.out.println("char array is>>"+charArray[i]);
            }
            len = charArray.length;
            System.out.println("length of char array is>>"+len);
            System.out.print("\n");
            
            System.out.println("input char is>>  "+inputChar);
    
            Check(charArray,inputChar);
            
        }
        ///////////////////////////////////////////////////////
        //compare charArray and inputChar
        public static int Check(char[] charArray , char inputChar){
            int index = 0;
            for(index = 0;index<charArray.length;index++){
                if(charArray[index] == inputChar){
                    System.out.println(">>index  "+index+"  equals");
                    return index;
                }else{
                    System.out.println(">>index  "+index+"  not equals");
                    return index;
                }
            }
        return index;
        }
    }

  2. #2
    markus-sukram is offline Member
    Join Date
    Mar 2008
    Posts
    5
    Rep Power
    0

    Default

    It is unnecessary to create a new character array, a string is already an array of characters.
    for (i = 0; i < str.length; i++){
    if(str.charAt(i) == 'B') {System.out.println("index "+i+" is equal to B");}
    else {System.out.println("index "+i+" is not equal to B");}
    }

  3. #3
    googgoo is offline Member
    Join Date
    Mar 2008
    Posts
    8
    Rep Power
    0

Posting Permissions

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