1

For example, I am calling a scanner from the user.

double second = sc.nextDouble();
double multiplayer = sc.nextDouble();
v.add(second);
v.add(multiplayer);

And when I display the vector output these 2 inputs appear in 2 lines. Is there anyway to put these 2 elements in a single vector?

e.g. input second is 5.0
     input multiplayer is 1.4

display vector will be:

5.0
1.4

Is there anyway to make them in a single vector like

5.0 1.4?

Please help :(

Jolene
  • 11
  • 1
  • How are you "displaying the vector"? – Oliver Charlesworth Sep 02 '11 at 15:30
  • 2
    It is still a single vector. Just that the display is multi-lined. – adarshr Sep 02 '11 at 15:31
  • @Oli Charlesworth ListIterator iter = v.listIterator(); while (iter.hasNext()) { System.out.println((Double)iter.next()); This is how I display the vector. – Jolene Sep 02 '11 at 15:39
  • @adarshr Really? So if I try getting the vector at that index, I'll get both values? – Jolene Sep 02 '11 at 15:39
  • 1
    @Jolene: A `Vector` is like a box into which you put objects. You've put two apples (doubles) into this box. So depending on which one you want, you can access them using the index. `v.get(0)` will give you `second` where as `v.get(1)` will fetch you `multiplayer`. However, try to avoid using a `Vector` in the first place. `ArrayList` is a more modern collection for you. – adarshr Sep 02 '11 at 15:45
  • @adarshr Wow thanks. I wasn't aware of that. I'm quite new to programming and I'm trying ways to do it instead of Array. But thank you all, I will try to explore :) – Jolene Sep 02 '11 at 15:47
  • @Jolene You are using `System.out.println` instead of `System.out.print`. `System.out.println` adds the newline. See the [documentation](http://download.oracle.com/javase/6/docs/api/java/io/PrintStream.html) – S.L. Barth is on codidact.com Sep 02 '11 at 15:47

2 Answers2

3

First, do not use Vector use an ArrayList (see this question/answer why).

List<Double> v = new ArrayList<Double>();
v.add(5.0);
v.add(1.4);
  • Using toString() of the list:

    The output from v.toString() is [5.0, 1.4]. As you can see there are some "extra characters" [, ], ,. To remove these you can call replaceAll with the regular expression [\\[\\],].

    System.out.println(v.toString().replaceAll("[\\[\\],]", ""));
    
  • Using a for loop:

    for (Double e : v) System.out.print(e);
    System.out.println();
    
Community
  • 1
  • 1
dacwe
  • 43,066
  • 12
  • 116
  • 140
0

for ( Double d : v ) { System.out.print( d ); }

You may wish to put a System.out.println(); in front of that, so that the contents of the Vector are printed on a new line.