(fix this line oriented Java programming code) import java.until.Scanner; public
ID: 3581080 • Letter: #
Question
(fix this line oriented Java programming code)
import java.until.Scanner;
public class LineOriented{
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
String line=null;
String data=null;
double sum=0.0;
System. out.println("Enter data");
while(!(line=in.nextLine()).isEmpty()){
data=line;
}
data=data.subString(0,data.indexOf("//"));
String [] values=data.split("\s+");
for(int i=0;i<values.length;i++){
sum+=Integer.parseInt(values[I]);
}
System. out.println(sum);
}
}
//This code worked for the line oriented input with the comment sign i.e
if we put
-10 -10 -10// here is three numbers
and press enter we get the out put
-30
can you look at the code above and fix it for inputs without. // i.e
if we put
10 10 10
the output should be 30
(I tried but couldn't get it, I have final exam tommorow. pls help)
Explanation / Answer
import java.util.Scanner;
public class LineOriented{
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
String line=null;
double sum=0.0;
String data="";
System. out.println("Enter data:");
line = in.nextLine();
int index = line.indexOf("//");
//if Comments are not there the value of index is -1
//so to get data, use substring(0)
if(index == -1) {
data = line.substring(index+1);
}
else{
data = line.substring(0,index);
}
//split method of String Object
//takes parameter as space, and returns String array
String inputs[] = data.split(" ");
int i=0;
while(inputs.length > i) {
sum = sum +Integer.parseInt(inputs[i]); // Parsing each String into Integer
// sum = sum +Double.parseDouble(inputs[i]);
i++;
}
System.out.println("The sum is:"+sum);
in.close();
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.