-4

JAVA problem!! CodeQuotient

so, suppose I have a list of number-

6
36
16
9
20
1
11

and I want to find the square root of the above numbers in a way that the output shows as-

6.00
4.00
3.00
4.47
1.00
3.32

I want to know how we take a list of number as user input and perform square root operation on all the number and display the output

I tried using list but, I have no idea how to perform square root operation on the numbers inside the list separately

I tried using list but,   I have no idea how to perform square root operation on the numbers inside the list separately

**Note - the program doesn't use list!!

...it seems that we cannot use list to solve this problems as using list adds square brackets[] to the output and i need the output in a vertical order without brackets as shown in the image below**

  • 2
    please don't put pictures of code. Copy the code and paste it here. – Yoshikage Kira May 18 '21 at 16:35
  • If you've never done so before, now would be a good time to familiarize yourself with the concept of [iterating over a collection](https://stackoverflow.com/questions/18410035/ways-to-iterate-over-a-list-in-java). Iterating over the list will allow you to perform operations on (or for) every element of that collection. – OH GOD SPIDERS May 18 '21 at 16:39
  • thank you for the help! – Jubin Saud May 18 '21 at 17:45
  • Just use a loop and take the square root of each element and print it. – NomadMaker May 18 '21 at 17:53

1 Answers1

1

You can do it as in the following.

Scanner scanner = new Scanner(System.in);
// allocate array list
List<Double> results = new ArrayList<>();
// get the number of input items
int count = scanner.nextInt();
// and read them while counting down
while (count-- > 0) {
    int val = scanner.nextInt();
    // compute square root and add to list
    results.add(Math.sqrt(val));
}

Now print them

results.forEach(s->System.out.printf("%.2f%n", s));
WJS
  • 36,363
  • 4
  • 24
  • 39
  • This answer is almost perfect except. I would change the print line to `results.forEach(number -> System.out.printf("%.2f\n", number.doubleValue()));` since the question tells that you have to print only two decimal places. – Yoshikage Kira May 18 '21 at 18:12
  • thats exactly what i was trying to find....to format it to 2 decimal points THANKS – Jubin Saud May 18 '21 at 18:37
  • @JubinSaud Instead of saying thanks in comments select the check mark next to answer. This will mark the question as solved so the anyone who later sees this thread knows which solution worked. – Yoshikage Kira May 18 '21 at 19:00
  • @Goion Regarding printf - good idea. I made the change. Thanks. – WJS May 18 '21 at 19:51