1. Write a method named digitSum that takes a non-negative integer as a paramete
ID: 3540340 • Letter: 1
Question
1. Write a method named digitSum that takes a non-negative integer as a parameter and that returns the sum of its digits.
For example, digitSum(20879) should return 26 (2 + 0 + 8 + 7 + 9). You may assume that the method is passed a value greater than or equal to 0. You may not use a String to solve this problem; you must solve it using integer arithmetic.
2.Write a method named longestWord that accepts a String as its parameter and returns the length of the longest word in the string.
A word is a sequence of one or more non-space characters (any character other than the space character).
You may assume that the string doesn't contain any other white-space characters such as tabs or newlines.
Here are some example calls to your method and their expected results:
Call
Value returned
longestWord("to be or not to be")
3
longestWord("oh hello, how are you?")
6
longestWord("I am OK")
2
Call
Value returned
longestWord("to be or not to be")
3
longestWord("oh hello, how are you?")
6
longestWord("I am OK")
2
Explanation / Answer
import java.util.*;
public class test
{
public static void main(String []args)
{
System.out.println("longestWord(" + "to be or not to be" + ") " + longestWord("to be or not to be"));
System.out.println("longestWord("+"oh hello, how are you?"+ ") " + longestWord("oh hello, how are you?"));
System.out.println("longestWord("+"I am OK" +") " + longestWord("I am OK"));
System.out.println("digitSum(20879) " + digitSum(20879) );
}
public static int longestWord(String str)
{
String[] stringArray= str.split("\s");
int max_length = stringArray[0].length();
for(int i=1; i<stringArray.length; i++)
{
if(stringArray[i].length() > max_length)
{
max_length = stringArray[i].length();
}
}
return max_length;
}
public static int digitSum(int k)
{
int sum = 0;
while(k>0)
{
sum = sum+(k%10);
k = k/10;
}
return sum;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.