• Post Reply Bookmark Topic Watch Topic
  • New Topic

Vectors and Randoms  RSS feed

 
jason tourne
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I need to fill in the blanks to complete the code below using a for loop to add 3 random ints to a Vector and print them to the command line using System.out.println().

Here is what I have:

Vector names = new Vector();
Random rand = new Random();

for(_____ i = 0; i ____ 3; i++){
names._____(_____.____());
_____.____.____( (
____) names._____(i));
}

what i think is right for the first line is : int, <
second line is: add, r.nextInt
third line is : System, out, println

I don't know the last line
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"r" is incorrect. The correct answer is part of what you have written yourself. Are you sure you have copied the 3rd line correctly? I think there is an error if you are using System.out.println( . . . )
You will have to go through the Vector class in the API. Assuming it is java.util.Vector, you can find it by clicking whichever word "Vector" is underlined. You will find a list of methods which you can use on a Vector.

By the way: Why have you been told to use Vector? Most of us consider it to be legacy code, and would use ArrayList instead.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't think it's an error. The line says "gap gap gap" (looks like that should indeed be System.out.println). After that there is a cast (the (___) part) of the result of some method called on names, with argument i.
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I never thought of a cast. Thank you, Rob.

But why would a cast be necessary; since toString() is inherited from Object, it can be called polymorphically without a cast.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, this code is using Vector, and it's not even generic.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!