Issue
I have a homework assignment in where my teacher has left us the following instructions: Create a new method with String input and String return. Check the string to see if there are any uppercase letter, put together all uppercase together and return this string: Your method header and for-loop provided: No power tools, use ASCII table Your sample output should be as followed: getUpper(“Hello, World”) returns “HW” getUpper(“no way”) returns “”
This is the initial code provided:
public String getUpper(String s) {
String output = "";
for (int i = 0; i < s.length(); i++) {
//i is the index of the string
//Your work here
}
return output;
}
I have managed to create a solution, however this solution is one that is hardcoded as seen below:
public class homework5 {
public homework5() {
}
public String getUpper(String s) {
String output = "";
for (int i = 0; i < s.length(); i++) {
//i is the index of the string
char c1 = s.charAt(i);
int a1 = (int)c1;
if (a1 < 97) {
output += c1; // This segment of code works, but is hardcoded. Find a generalized value for it.
}
}
return output;
}
public static void main(String args[]) {
homework5 obj1 = new homework5();
//method call
System.out.println(obj1.getUpper("Hello"));
}
}
How would I go about this problem to find a general way to find a character, checks its ascii value, and see if it is uppercase, and then print it out?
Solution
You can just compare with 'A'
and 'Z'
(since the uppercase letters are consecutive in ASCII).
char c1 = s.charAt(i);
if (c1 >= 'A' && c1 <= 'Z') output += c1;
Character.isUpperCase
is more general and works for Unicode, not just ASCII.
if (Character.isUpperCase(c1)) output += c1;
Answered By - Unmitigated
Answer Checked By - Marilyn (JavaFixing Volunteer)