java - How to read a line of numbers and display the sum? -
i'm working on programme read whole line of numbers , display sum. must written in java , must simple possible. nil much harder arrays or ever needed create work.
this illustration of want:
please come in numbers space in between each. 12 34 7 93 4 sum of numbers: 150
i have had number of attempts , have got @ moment.
public static void main(string[] args) { scanner kb = new scanner(system.in); int numbers; int total; system.out.println("please come in numbers space between each"); numbers = kb.nextint(); for(int i=args.length; i<numbers; i++) { system.out.println("the sum " + numbers); } }
scanner#nextint
reads single int
input stream. instead, want read bunch of numbers , start working on them.
i can think on 2 solutions this:
read whole line (using scanner#nextline
), split blank space (" "
) (using string#split
), convert each string
int
, calculate sum (using integer#parseint
).
int total = 0; system.out.println("please come in numbers space between each"); string linewithnumbers = kb.nexline(); string[] numbers = linewithnumbers.split(" "); (string number : numbers) { total += integer.parseint(number); }
read whole line (using scanner#nextline
), utilize scanner
read integers stored in string
, calculate sum.
int total = 0; system.out.println("please come in numbers space between each"); string linewithnumbers = kb.nexline(); scanner linescanner = new scanner(linewithnumbers); while (linescanner.hasnext()) { total += linescanner.nextint(); }
java
No comments:
Post a Comment