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:
- 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 linescanner.nextLine()you from entering numbers. - Are there any other ways to extract numbers from the string without using the
splitmethod? Only parse manually? - What is it for? Exclusively academic interest.