Reverse(String s): String -take a String as an argument and return the String re
ID: 3861774 • Letter: R
Question
Reverse(String s): String -take a String as an argument and return the String reversed. Eg. "Hello" would be returned as "olleH". binaryToDecimal(String s): int -take a String as an argument and return the decimal equivalent as an integer. If any of the characters are neither zero nor one return -1. Eg. "1000" would return 8. "10001" would return 17. "111111" would return 63. "111112" would return -1. "100001.1" would return -1. stats(String s, char c): void -take a String us an argument and print the number of words, the number of characters and the number of times char c appears in the String.Explanation / Answer
MethodsTest.java
public class MethodsTest {
public static void main(String[] args) {
String s = "hello";
MethodsTest m = new MethodsTest();
System.out.println(m.reverse(s));
System.out.println(m.binaryToDecimal("10001"));
System.out.println(m.binaryToDecimal("10001.1"));
s = "hello how are you";
m.stats(s, 'l');
}
public String reverse(String s){
String reverseString ="";
for(int i=s.length()-1; i>=0; i--){
reverseString = reverseString+s.charAt(i);
}
return reverseString;
}
public int binaryToDecimal(String s){
int decimal = 0;
for(int i=s.length()-1,j=0; i>=0; i--,j++){
if(s.charAt(i) == '1' || s.charAt(i) == '0'){
if(s.charAt(i) == '1'){
decimal=decimal+(int)Math.pow(2, j);
}
}
else{
return -1;
}
}
return decimal;
}
public void stats(String s, char c){
int numberOfWords = 0;
int numberOfChars = s.length();
int charCount = 0;
for(int i=0; i<s.length(); i++){
if(s.charAt(i)==c){
charCount++;
}
}
numberOfChars = s.split("\s+").length;
System.out.println("Number of Words: "+numberOfWords);
System.out.println("Number of characters: "+numberOfChars);
System.out.println("Number of times character "+c+" appears: "+charCount);
}
}
OUtput:
olleh
17
-1
Number of Words: 4
Number of characters: 17
Number of times character l appears: 2
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.