Java program which sums numbers from 1 to 100

前端 未结 5 1536
别那么骄傲
别那么骄傲 2021-01-29 16:50

I have been recently started learning Java and would want to make code that sums the numbers from 1 to 100 (result would be 5050)

The code should go like 1+2+3+4+5+6+7+8+

5条回答
  •  我在风中等你
    2021-01-29 16:53

    You have started to learn Java by implementing a for loop. Unfortunately that is probably the least intuitive syntax in the entire language. It was inherited from c and, while convenient, really makes no sense: the meaning of the three positions bears no resemblance to natural language (unlike if, while, implements etc.). Much better to start with simpler constructs until you get the hang of things.

    Java 8 provides a more intuitive (in my opinion) way of representing a group of numbers to add. In your case you don't really want to iterate through all the numbers from 1 to 100. You just want a way to represent all those numbers and then sum them. In Java 8 this concept is represented by a stream of integers: the IntStream class. It provides a handy way of asking for 'all integers between x and y': the rangeClosed method. And it provides a method for adding all the integers together: the sum method.

    So your operation could be implemented with a single, simple Java statement:

    IntStream.rangeClosed(1, 100).sum();
    

    That seems a pretty straightforward statement to read: give me a stream of integers in the range from 1 to 100 and then sum them. Even better you don't need to declare a variable you have no real use for.

提交回复
热议问题