Why Integer.parseInt(s) method summarize only the first number? (Instead of all the numbers entered?)

 Scanner in = new Scanner(System.in); System.out.println("ะ’ะฒะตะดะธั‚ะต ั‡ะธัะปะพ ะพั‚ 1 ะดะพ 10"); int count = in .nextInt(); System.out.print("ะ’ะฒะตะดะธั‚ะต" + " " + count + " " + "ั‡ะธัะตะป, ั‡ะตั€ะตะท ะฟั€ะพะฑะตะป"); Scanner scan = new Scanner(System.in); String str = scan.next(); String[] numbers = str.split(" "); int res = 0; for (int i = 0; i <= count - 1; i++) { for (String s: numbers) { res += Integer.parseInt(s); } } System.out.println("ะกัƒะผะผะฐ ั‡ะธัะตะป= " + res); 

    1 answer 1

    It's not very clear why you need two cycles. Instead of next () use nextLine ()

     public static void main(String []args){ Scanner in = new Scanner(System.in); System.out.println("ะ’ะฒะตะดะธั‚ะต ั‡ะธัะปะพ ะพั‚ 1 ะดะพ 10"); int count=in.nextInt(); System.out.print("ะ’ะฒะตะดะธั‚ะต"+" "+count+" "+"ั‡ะธัะตะป, ั‡ะตั€ะตะท ะฟั€ะพะฑะตะป"); in.nextLine(); String str = in.nextLine(); String[] numbers = str.split(" "); int res = 0; for (String s : numbers) { res += Integer.parseInt(s); } System.out.println("ะกัƒะผะผะฐ ั‡ะธัะตะป= " + res); } 

    In general, this is not python, to come up with workarounds for entering numbers separated by spaces. You can enter numbers separated by a space and the Scanner will read them one after the other in a cycle.

     public static void main(String []args){ Scanner in = new Scanner(System.in); System.out.println("ะ’ะฒะตะดะธั‚ะต ั‡ะธัะปะพ ะพั‚ 1 ะดะพ 10"); int count = in.nextInt(); System.out.print("ะ’ะฒะตะดะธั‚ะต"+" "+count+" "+"ั‡ะธัะตะป, ั‡ะตั€ะตะท ะฟั€ะพะฑะตะป"); int res = 0; for (int i = 0; i < count; i++) { res += in.nextInt(); } System.out.println("ะกัƒะผะผะฐ ั‡ะธัะตะป= " + res); } 
    • Indeed with nextLine works! Well, thank you! But for some reason it is necessary to first enter the number of elements in one number in the tasks, then read the numbers from one line, for this the 2nd cycle was used - yonce