package com.company; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = 0; int S = 0; String current = ""; System.out.println("Π’Π²Π΅Π΄ΠΈΡ‚Π΅ количСство чисСл для суммирования"); n = sc.nextInt(); System.out.println("Π’Π²Π΅Π΄ΠΈΡ‚Π΅ числа для суммирования"); current = sc.nextLine(); ArrayList<String> row = new ArrayList<String>(Arrays.asList(current.split(" "))); ArrayList <Integer> introw = new ArrayList <Integer>(); for (int i = 0; i < row.size(); i++) { introw.add(Integer.parseInt(row.get(i))); } for (int i = 0; i < introw.size(); i++) { S = S + introw.get(i); } System.out.println("Π‘ΡƒΠΌΠΌΠ° S = " + S); } } 

Error screenshot: enter image description here

  • 2
    Errors, too, the text is better to lay out - Viktorov

3 answers 3

nextInt() - reads the value before the carriage transfer \n , so the nextLine reads it (this is the carriage return itself).

As a result, you either need to write nextLine() even on the first line and then convert it via parseInt() , or add another nextLine() after nextInt()

    The nextInt() method simply reads the first numeric value from the input stream, but does not "translate" the scanner to the next line β€” after that, the nextLine() call reads everything that is left in the current line (and there is nothing left).

    The simplest solution is to add another call to sc.nextLine(); immediately after reading the first number and then read the next line.

       import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Π’Π²Π΅Π΄ΠΈΡ‚Π΅ числа для суммирования: "); String current = sc.nextLine(); boolean prevIsDigit=false; StringBuilder sb = new StringBuilder(); for (char ch : current.toCharArray()) { if (Character.isDigit(ch)) { sb.append(ch); prevIsDigit=true; } else if (prevIsDigit) { sb.append("@"); prevIsDigit=false; } } int result = 0; for (String s : sb.toString().split("@")) result+=Integer.valueOf(s); System.out.println("Π‘ΡƒΠΌΠΌΠ° S = " + result); } } 
      • Write like this. You do not need the number of digits, they can be calculated depending on user input. Simply enter a string with numbers using any delimiters, and everything will be counted. It's easier and safer - Dmitriy
      • Only negative numbers you seem to ignore. - Alex Chermenin
      • Well, this is already on the "independent study" along with refactoring and adding fractional numbers. everything on a platter is also not good. I just showed one of the possible solutions - Dmitriy