Adblock breaks this site

Execution problem

Discussion in 'Programming General' started by Grave, Jan 18, 2011.

  1. Grave

    Grave #1 preferred sexual partner of Ciara "5/5" -New York Times
    $5 USD Donor

    Joined:
    Jul 12, 2008
    Posts:
    5,305
    Referrals:
    162
    Sythe Gold:
    49,778
    Discord Unique ID:
    895547875277299712
    Discord Username:
    grave#9889
    Pizza Muncher Brony (3) MushyMuncher (2) Le Monkey (2) Not sure if srs or just newfag... Bojack Penguin (2) Wubba Lubba Dub Dub (2) Gohan has AIDS (2) Dunce
    Rust Player I'm LAAAAAAAME Yellow rat
    Execution problem

    Posting for a friend

    Code:
    itemCode = scanz.next();  
    for(int i = 0; i < inventory.length; i++){ 
    if(itemCode == inventory[i].getItemCode()){ 
    System.out.println("Success!"); 
    counter = i; 
    } 
    } 
    
    Why does the if statement never execute?
     
  2. Jimmy

    Jimmy Ghost
    Retired Sectional Moderator $5 USD Donor

    Joined:
    Jun 24, 2008
    Posts:
    2,421
    Referrals:
    10
    Sythe Gold:
    25
    Execution problem

    I can't really make too many comments without knowing more about the context of the code, but if itemCode is a String and inventory is a String[], then compare it to inventory.getItemCode() using the equals() method, rather than the == operator.

    tl;dr
    try
    Code:
    itemCode = scanz.next();  
    for(int i = 0; i < inventory.length; i++){ 
        if(itemCode.equals(inventory[i].getItemCode())){ 
            System.out.println("Success!"); 
            counter = i; 
        } 
    }
     
  3. slay blad3

    slay blad3 Active Member

    Joined:
    Jul 13, 2005
    Posts:
    248
    Referrals:
    0
    Sythe Gold:
    0
    Execution problem

    Code:
    itemCode = scanz.next(); // Execution will stop here until information can be read
    for(int i = 0; i < inventory.length; i++) // inventory.length may be 0
    { 
    	if(itemCode == inventory[i].getItemCode()) // itemCode may not match
    	{ 
    		System.out.println("Success!"); 
    		counter = i; 
    	} 
    } 
    
    Scanner.next() returns a String.
    if Inventory.getItemCode() returns a String, they should be compared with String.equals(String).

    Code:
    itemCode = scanz.next();
    for(int i = 0; i < inventory.length; i++)
    { 
    	if(itemCode.equals(inventory[i].getItemCode()))
    		System.out.println("Success!"); 
    		counter = i; 
    	} 
    } 
    
     
< In need of an expert programmer from the east coast US | Stanford Java >


 
 
Adblock breaks this site