Java Homework: Write a program that takes one string as the input. Then change a
ID: 3760620 • Letter: J
Question
Java Homework:
Write a program that takes one string as the input. Then change all the characters to the order number in alphabet and then sum them together. A sample execution of this program is like: Please input one string: ABCDEfg The sum of your input string is 1+2+3+4+5+6+7=28.
Requirement:
1. Create a method named sumString with one parameter of String type, and the return value will be the summation of the order numbers.
2. Create a method to check if the string contains only English letters. If not, print some hint message and ask the user to input again.
Hint:
1. Change the characters to lower case or upper case using String.toLowerCase() or String.toUpperCase()
2. Use the ASCII number to map the character into the order number. For example, ‘A’ is 97 in decimal, so the order number of ‘A’ is ‘A’ – 96.
Explanation / Answer
/* Please note Ascii Value of 'A' is not 97. Ascii value of 'A' is 65. Ascii value of 'a' is 97 */
import java.util.Scanner;
public class sample
{
public static int sumString(String s)
{ int sum=0;
// converting all the characters in string to uppercase.
s=s.toUpperCase();
for(int i=0;i<s.length();i++)
{
sum=sum+(s.charAt(i)-64); // Logic to find order number
}
return sum;
}
public static String checkString(){
Scanner sc=new Scanner(System.in);
String s=" ";
int count=0;
while(count<s.length()){
count=0;
System.out.println("Input String with English Letters only");
s=sc.next();
for(int i=0;i<s.length();i++)
{
if((s.charAt(i)>='a'&& s.charAt(i)<='z' )|| (s.charAt(i)>='A'&& s.charAt(i)<='Z'))
count++;
}
}
return s;
}
public static void main(String[] args)
{
String s=checkString();
System.out.println("The sum is "+sumString(s));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.