+ 5

Could you please help me with varargs in Java?

I am practicing the use of varargs in Java now and I am trying to create a code, in which arguments in vararags will be iserted by a user. I have created a simple code which counts a perimeter of a figure with an arbitrary number of sides. I don't know whether it actually has any sense, since it doesn't work in a proper way. May be there is a way to change it or it should be rewritten in an absolutely different way... I would be grateful for any assistance! https://code.sololearn.com/cfr1w8m62aUH/?ref=app

2nd Nov 2018, 3:48 PM
ZdzichPych
ZdzichPych - avatar
6 odpowiedzi
+ 5
Why did you post the same Question two Times? Was it accidentally? Please delete the Duplicate.
2nd Nov 2018, 8:10 PM
Sebastian Keßler
Sebastian Keßler - avatar
+ 5
Sure, it wasn't on purpose, it was uploading rather slowly, and got duplicated. Thank you, I haven't noticed it :)
2nd Nov 2018, 11:11 PM
ZdzichPych
ZdzichPych - avatar
+ 4
Monas Shukla, thank you very much for your answer. I was practicing the use of varargs and hoped it would be possible to use it for the user's input (here the number of sides counted in a perimeter is not defined). Unfortunately, I don't know how this can be done. When it comes to the use of a function, I can't tell you anything, as I am yet not well acquainted with its usage :/
16th Nov 2018, 7:16 AM
ZdzichPych
ZdzichPych - avatar
+ 4
Thank you very much for your solution, it is really useful!
16th Nov 2018, 10:31 AM
ZdzichPych
ZdzichPych - avatar
+ 1
actually its not working because of this line: int sides = Integer. parseInt(in.nextLine); this will throw an error since the input string will be something like "1 2 3" which cant be converted into a integer, i think your idea is to somehow copy paste the input between ( ) ,eg if your input was 1 2 6, you want a function call like func(1,2,6).but as far as i know this is not possible (please let me know if it is) .The way varargs work is that it collects all the arguments into a container like array.So if you want your code to work store the input in an array and send the array to function. Mostly varargs are used in cases when you can manually type all the arguments.If the number of arguments are large better use arrays.
16th Nov 2018, 6:40 AM
Manas Shukla
Manas Shukla - avatar
+ 1
okay,, here is little thing that you might find useful :to calculate perimeter when number of sides are unknown; int sum=0; while(in.hasNext){ sum += in.nextInt(); } System.out.println(sum); while giving input just type the numbers you want and hit ctrl-D. the while loop breaks as in. hasNext returns false and sum gets printed.
16th Nov 2018, 9:53 AM
Manas Shukla
Manas Shukla - avatar