In: Computer Science
Hello I have a question about Java.
example
So when you put “sum 1 2 3” in console, you do not separate those. Need a space between sum 1, 2 in the console.
What is Sum?
sum 1 2 3
6 (answer)
sum 123456
21
sum 100 2000 3000
5100
sum 20 50 40 1
111
public static void main (String[] args) {
System.out.Println(“What is Sum?”);
String a=“”;
a = scnr.nextLine();
String[] b = a.split(“”);
if(b[0].equals(“sum”) {
}
Please do not change the above code. If I put sum in the console, it calculate the sum.
you may need to convert type from String to double.
I don’t know how to make code for the sum. Please help me by above code.
ANSWER: Here I am giving you the code and output if you have any problem then comment or like it please.
CODE:
import java.util.Scanner;
public class ReferenceMystery {
/**
* @param args
*/
static int getSum(int n) // method to find the sum of
a digit
{
int sum = 0;
while (n != 0)
{
sum = sum + n % 10;
n = n/10;
}
return sum;
}
public static void main(String[] args) {
Scanner scnr= new
Scanner(System.in);
System.out.println("What is
Sum?");
String a="";
a = scnr.nextLine();
String[] b = a.split(" ");
int add=0;
if(b[0].equals("sum") ){
if(b.length==2)
{ // when your array has only 2 elements only
int a1=Integer.parseInt(b[1]);
int add0=getSum(a1);
System.out.println(add0);
}else {
for(int
i=1;i<b.length;i++)
add=add+Integer.parseInt(b[i]);
System.out.println(add);
}
}
}
}
OUTPUT: