Line-oriented input programming in Java: This program will input as many lines o
ID: 3571175 • Letter: L
Question
Line-oriented input programming in Java:
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 program with user input at top might go as
10 20 30
60
-10 -20 -30 -40 -50//here are 5 nums
-150
1 1 1 1 1 1 1 1 1 1//Follow by blk lin
10
Explanation / Answer
Please follow the code and comments for description :
CODE :
import java.util.Scanner; // required imports for the class to run
public class lineOrientedInput { // class to run the code
public static void main(String[] args) { // driver method
Scanner keyboard = new Scanner(System.in); // scanner class to get the input
String line = null; // local variables
String data = null;
double sum = 0;
System.out.println("Please Enter the data : "); // message
while (!(line = keyboard.nextLine()).isEmpty()) { // check for blank line
data = line; // temporary variable of data
}
data = data.substring(0, data.indexOf("//")); // concatenate the comments
String[] values = data.split("\s+"); // split based on the delimiter
for (int i = 0; i < values.length; i++) { // iterate over the array
sum = sum + Integer.parseInt(values[i]); // sum up the values
}
System.out.println(sum); // print to console
}
}
OUTPUT :
Please Enter the data :
10 20 30
60
-10 -20 -30 -40 -50//here are the 5 numbers
-150
1 1 1 1 1 1 1 1 1 1 1 -15//follwed by a blank line
entered: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -15]
-4.0
Hope this is helpful.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.