2 elements in 1 v.add vector java
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开发者_Python百科
Is there anyway to make them in a single vector like
5.0 1.4?
Please help :(
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 callreplaceAll
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();
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.
精彩评论