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); } } - 2Errors, too, the text is better to lay out - Viktorov
|
3 answers
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
|
