There is a task:
In the first line, enter n - the number of integers. In the second line enter numbers separated by spaces; numbers can be entered> n. Print the sum of n first entered numbers.
The solution is quite simple:

public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int amountOfNum = scanner.nextInt(); scanner.skip("\n"); String numString = scanner.nextLine(); String[] arrayNum = numString.split(" "); int summ = 0; for (int i = 0; i < amountOfNum; i++) { summ += Integer.parseInt(arrayNum[i]); } System.out.println(summ); } 

But by the decision itself there are questions:

  1. How to do the same without the scanner.skip("\n"); ? Because This is an obvious crutch, but without this line, scanner.nextLine() reads the previous line scanner.nextLine() you from entering numbers.
  2. Are there any other ways to extract numbers from the string without using the split method? Only parse manually?
  3. What is it for? Exclusively academic interest.
  • 2
    Specify a programming language. - Vlad from Moscow
  • it looks like java. - Sublihim
  • "what is it for?" - "this" is what exactly? If "why all this to do?", Then it is necessary to ask the one who created this task. - Regent

1 answer 1

Concerning points 1 and 2: it is enough to use nextInt instead of nextLine :

 public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int amountOfNum = scanner.nextInt(); int summ = 0; for (int i = 0; i < amountOfNum; i++) { summ += scanner.nextInt(); } System.out.println(summ); } 

Regarding paragraph 3: if the task is invented in order to teach reading numbers from the console, then you need this ... for learning to read numbers from the console. In practice, this may be necessary only in some wonderful situation in which you need to calculate the sum of large numbers, but you cannot use the calculator, but you have this program and the ability to run it.

  • Thank! Understood - kernel40
  • @ kernel40 to health. If you are satisfied with the answer, do not forget to mark it as accepted. - Regent