Java programming (Line-oriented input) This program will input as many lines of
ID: 3575920 • Letter: J
Question
Java programming (Line-oriented input)
This program will input as many lines of input as the user wishes, blank line to quit.Each line before the blank line, you may assume without checking, will either be one or more ints separated by spaces, or one or more ints separated by spaces followed by //,followed by a comment. For each line before terminating blank line, your program is supposed to output the sum of the ints in the line. An example run of the program (with user input at the top) is
10 20 30
60
-10 -20 -30 -40 -50// here 5 nums
-150
1 1 1 1 1 1//This followed by blkline
6
(Thanks, pls make sure it work for all)
Explanation / Answer
import java.util.*;
class Test
{
public static void main(String[] args)
{
//Read the input from user(command prompt)
Scanner sc = new Scanner(System.in);
String input;
while((input = sc.nextLine()).length() > 0){
//Split the input with space
String[] split = input.split("\s+");
//Declare an integer array with size of split length
int[] Arrayinput = new int[split.length];
int i=0,sum = 0;
for (String string : split) {
Arrayinput[i++] = Integer.parseInt(string);
}
for(i=0;i<split.length;i++){
sum += Arrayinput[i];
}
System.out.println("sum is : " + sum);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.