Question

In Java All methods listed below must be public and static. If your code is using...

  • In Java
  • All methods listed below must be public and static.
  • If your code is using a loop to modify or create a string, you need to use the StringBuilder class from the API.
  • Keep the loops simple but also efficient. Remember that you want each loop to do only one "task" while also avoiding unnecessary traversals of the data.
  • No additional methods are needed. However, you may write additional private helper methods, but you still need to have efficient and simple algorithms. Do not write helper methods that do a significant number of unnecessary traversals of the data.
  • Important: you must not use either break or continue in your code. These two commands almost always are used to compensate for a poorly designed loop. Likewise, you must not write code that mimics what break does. Instead, re-write your loop so that the loop logic does not need break-type behavior.
  • While it may be tempting to hunt through the API to find classes and methods that can shorten your code, you may not do that. The first reason is that this homework is an exercise in writing loops, not in using the API. The second reason is that in a lot of cases, the API methods may shorten the writing of your code but increase its running time. The only classes and methods you can use are listed below. Note: if a method you want to use from the API is not listed, you should not implement the method yourself so you can use it. Rather, you shoud look for the solution that does not need that method.

    You are allowed to use the following from the Java API:

    • class String
      • length
      • charAt
    • class StringBuilder
      • length
      • charAt
      • append
      • toString
    • class Character
      • any method

Create a class called HW2 that contains the following methods:

  1. nthWord takes an int and a String as input and returns a String:
    The input int represents a number n that is assumed to be positive, and the output string contains every nth word of the input string, starting with the first word, separated by a single space. {\em For this method, a word is defined to be a sequence of non-space characters.} There should be no space at the end of the output string.

    > HW2.nthWord(3, "zero one    two  three four five six seven")
    "zero three six"
    
  2. truncateAfter takes an int and a String as input and returns a String:
    The input string may contain hyphens and spaces that mark appropriate places to truncate the string. The output string will be a truncated version of the input string, and the input int value is the desired length of the output string. The output string should truncate the input string at the first legal spot such that the output string will have at least the desired length. If the truncation happens at a space, the space is not included in the output, but if the truncation happens at a hyphen, the hyphen is included. No other hyphens are included in the output, but the other spaces are. (If the input string does not have enough characters to meet the desired minimum, then the output should be the entire input string without the hyphens.)

    > HW2.truncateAfter(5, "La-te-ly the-re.")
    "Late-"
    > HW2.truncateAfter(6, "La-te-ly the-re.")
    "Lately"
    > HW2.truncateAfter(7, "La-te-ly the-re.")
    "Lately the-"
    
  3. truncateBefore: the same as the truncateAfter method, but now the input int value is the maximum, and the string should be truncated at the latest possible point such that the resulting string has no more than the desired length.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

[11:01 AM, 3/7/2019] Narasimha: ]Here are the first 4 methods

======================================================================================

public class HW2 {

public static boolean onlyEnglishLetters(String text) {

for (int i = 0; i < text.length(); i++) {
char letter = text.charAt(i);
if (('a' <= letter && letter <= 'z') || ('A' <= letter && letter <= 'Z')) {
continue;
} else {
return false;
}
}
return true;
}

public static String replaceKth(char find, char replace, int pos, String text) {

int frequency = 0;
int index = -1;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == find) {
frequency += 1;
if (frequency == pos) {
index = i;
break;
}
}
}
if (frequency == pos) {
return text.substring(0, index) + String.valueOf(replace) + text.substring(index + 1);
} else {
return text;
}
}

public static String interleave(String one, String two) {

StringBuilder build = new StringBuilder();
int lengthOne = one.length();
int lengthTwo = two.length();
int max = lengthOne > lengthTwo ? lengthOne : lengthTwo;

for (int i = 0; i < max; i++) {
if (i < one.length()) {
build.append(one.charAt(i));
}
if (i < two.length()) {
build.append(two.charAt(i));
}
}
return build.toString();

}

public static String blankWords(String text) {

String[] words = text.split("\\s+");
StringBuilder builder = new StringBuilder();
for (String word : words) {
if (word.length() <= 2) {
builder.append(word).append(" ");
} else {
for (int i = 0; i < word.length(); i++) {
if (i == 0 || i == word.length() - 1) {
builder.append(word.charAt(i));
} else {
builder.append("-");
}
}
builder.append(" ");
}
}
return builder.substring(0, builder.length() - 1).toString();
}

public static void main(String[] args) {
System.out.println(replaceKth('a', 'x', 6, "aaaaa"));
System.out.println(interleave("abcde", "ABC"));
System.out.println(blankWords("This is a Test ."));
}
}

Add a comment
Know the answer?
Add Answer to:
In Java All methods listed below must be public and static. If your code is using...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • In Java Only can use class String length charAt class StringBuilder length charAt append toString class...

    In Java Only can use class String length charAt class StringBuilder length charAt append toString class Character any method Create the following methods nthWord takes an int and a String as input and returns a String: The input int represents a number n that is assumed to be positive, and the output string contains every nth word of the input string, starting with the first word, separated by a single space. {\em For this method, a word is defined to...

  • Programming project in Java: You are allowed to use the following methods from the Java API:...

    Programming project in Java: You are allowed to use the following methods from the Java API: class String length charAt class StringBuilder length charAt append toString class Character any method Create a class called HW2 that contains the following methods: 1. isAlphabeticalOrder takes a String as input and returns a boolean: The method returns true if all the letters of the input string are in alphabetical order, regardless of case. The method returns false otherwise. Do not use arrays to...

  • You will write three static methods to manipulate an input String in different ways using various...

    You will write three static methods to manipulate an input String in different ways using various String methods. You need to provide the code for each of the three static methods in class StringPlay (requirements for each listed below). You will also change the control statement in the test harness to allow for variations in the sentinel value. You need to modify the loop control condition in Lab09.java so that user inputs of ‘finish’, “FINISH”, “FiniSH”, “fINISH”, etc. will end...

  • *MYST BE I NJAVA* *PLEASE INCORPORATE ALL OF STRING METHODS AND SCANNER METHOD LISTED IN THE...

    *MYST BE I NJAVA* *PLEASE INCORPORATE ALL OF STRING METHODS AND SCANNER METHOD LISTED IN THE DIRECTIONS BELOW* Write a Java class that takes a full name (first and last) as inputted by the user, and outputs the initials. Call the class Initials. The first and last names should be entered on the same input line i.e. there should be only one input to your program. For example, if the name is Jane Doe, the initials outputted will be J...

  • USING JAVA Consider the following methods: StringBuilder has a method append(). If we run: StringBuilder s...

    USING JAVA Consider the following methods: StringBuilder has a method append(). If we run: StringBuilder s = new StringBuilder(); s.append("abc"); The text in the StringBuilder is now "abc" Character has static methods toUpperCase() and to LowerCase(), which convert characters to upper or lower case. If we run Character x = Character.toUpperCase('c');, x is 'C'. Character also has a static isAlphabetic() method, which returns true if a character is an alphabetic character, otherwise returns false. You will also need String's charAt()...

  • Java Question, I need a program that asks a user to input a string && then...

    Java Question, I need a program that asks a user to input a string && then asks the user to type in an index value(integer). You will use the charAt( ) method from the string class to find and output the character referenced by that index. Allow the user to repeat these actions by placing this in a loop until the user gives you an empty string. Now realize that If we call the charAt method with a bad value...

  • ​​​​​​public static int countCharacter(String str, char c) { // This recursive method takes a String and...

    ​​​​​​public static int countCharacter(String str, char c) { // This recursive method takes a String and a char as parameters and // returns the number of times the char appears in the String. You may // use the function charAt(int i) described below to test if a single // character of the input String matches the input char. // For example, countCharacter(“bobbie”, ‘b’) would return back 3, while // countCharacter(“xyzzy”, ‘y’) would return back 2. // Must be a RECURSIVE...

  • JAVA Recursion: For this assignment, you will be working with various methods to manipulate strings using...

    JAVA Recursion: For this assignment, you will be working with various methods to manipulate strings using recursion. The method signatures are included in the starter code below, with a more detailed explanation of what function the method should perform. You will be writing the following methods: stringClean() palindromeChecker() reverseString() totalWord() permutation() You will be using tools in the String class like .substring(), .charAt(), and .length() in all of these methods, so be careful with indices. If you get stuck, think...

  • I need to create a code for this prompt: In this project we will build a...

    I need to create a code for this prompt: In this project we will build a generic UserInput class for getting keyboard input from the user. Implementation: The class UserInput is a 'Methods only' class, and all the methods should be declared static. Look at the TestScanner.java program at the bottom of this page that inputs a string, int and double. It shows you how to use Scanner class to get input from the keyboard. Write FOUR simple methods, one...

  • Class StringImproved public class StringImproved extends java.lang.Object This program replaces the string class with a mutable...

    Class StringImproved public class StringImproved extends java.lang.Object This program replaces the string class with a mutable string. This class represents a character array and provide functionalities need to do basic string processing. It contains an array of characters, representing a textual string. Overview In Java, Strings are a great device for storing arrays of characters. One limitation of Strings in Java, however (there is always at least one), is that they are immutable (ie. they cannot be changed once created)....

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT