Results 1 to 3 of 3

Thread: Vector

  1. #1
    Join Date
    Jan 2010
    Posts
    80
    Rep Power
    0

    Default Vector

    Hi

    I wrote the following program as an example of vector

    When I run the program and enter 'stop', it doesn't stop

    Java Code:
    import java.util.Vector;
    import java.util.Scanner;
    
    public class TryVector {
    	public static void main(String[] args){
    		
    		Scanner scan = new Scanner(System.in);
    		Vector<String> v = new Vector<String>() ;
    		
    		String name="";
    		
    		while(name != "stop"){
    		v.add(name);
    		System.out.println("Add name");
    		name = scan.next();
    		}
    		
    		//print
    		
    		for(int i=0; i<v.size(); i++){
    			v.get(i);
    		}
    	}
    }
    I've tried many times to figure out the problem but I couldn't

  2. #2
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    5

    Default

    Object comparison should always be done with the equals() method, the == operator is used for primitive types, and memory locations of object instances.
    Swap out while(name != "stop) with while(!name.equals("stop")) and you'll be fine.
    And one more thing:
    Java Code:
    for(int i = 0; i < v.size(); i++)
      v.get(i);
    This doesn't acomplish anything, you just get the value from the vector, but you don't store it anywhere, or do anything with it. Maybe you wanted a System.out.println() there?
    Last edited by m00nchile; 05-11-2010 at 12:48 AM.
    Ever seen a dog chase its tail? Now that's an infinite loop.

  3. #3
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,019
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by m00nchile View Post
    Object comparison should always be done with the equals() method, the == operator is used for primitive types, and memory locations of object instances.
    The OP asked a similar question here. Strange he forgot how to do it right ...

    kind regards,

    Jos

Similar Threads

  1. Vector
    By Anandiscool in forum New To Java
    Replies: 4
    Last Post: 03-28-2010, 08:10 PM
  2. Vector<vector> loop thru
    By ocean in forum New To Java
    Replies: 11
    Last Post: 11-21-2009, 02:17 PM
  3. Vector
    By MuslimCoder in forum Advanced Java
    Replies: 4
    Last Post: 08-06-2009, 03:44 PM
  4. Replies: 1
    Last Post: 04-06-2009, 06:45 AM
  5. Vector help
    By king_arthur in forum New To Java
    Replies: 3
    Last Post: 01-22-2008, 07:33 PM

Posting Permissions

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