Question

In: Computer Science

Guidelines for the program: All methods listed below must be public and static. If your code...

Guidelines for the program:

  • 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 are often 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 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. replaceFirstK: takes a String, two chars, and an int as input and returns a String that is the same as the parameter String except that first int occurrences of the first char parameter are replaced with the second char parameter.

    > HW2.replaceFirstK("Mississippi River", 'i', 'I', 3)
    "MIssIssIppi River"
    > HW2.replaceFirstK("Missouri River", 'r', '*', 3)
    "Missou*i Rive*"
    
  2. allChars: takes two char parameters. Creates a String containing all characters, in order, from the first char parameter (inclusive) to the last (inclusive).

    > HW2.allChars('d', 'm')
    "defghijklm"
    
  3. showCharOfString: takes two String parameters. Outputs a new String that is the same as the first String except that: for each character of the first String, if the character is not in the second String, replace that character with the underscore ('_').

    > HW2.showCharOfString("Missouri River", "s SR!r")
    "__ss__r_ R___r"
    
  4. hangman: Takes a String and an int and returns a boolean. The method plays the game of hangman where the String is the word the player must guess and the int is the maximum number of "bad guesses" allowed. The game should work as follows:

    1. Creates a StringBuilder that stores all the letters guessed by the player. The StringBuilder should initially be empty.
    2. Has a loop that does the following:
      1. Calls the showCharOfString on the parameter String and a string containing all the guessed letters.
      2. Uses System.out.println to print the String returned from the previous step as well as the total number of "bad guesses" so far. (For fun, you can print a graphical hangman instead of the number of bad guesses.)
      3. Uses javax.swing.JOptionPane.showInputDialog to get the next guessed letter from the user. The method should not crash if the user does not enter appropriate data.
      4. If the letter has not yet been guessed, adds the letter to the StringBuilder containing the guessed letters and if the letter is not in the input String, increases the count of "bad guesses" by one.
    3. The loop repeats until either: all letters of the parameter String are guessed or the number of "bad guesses" equals the int parameter.
    Finally, the method returns true if the player guessed all the letters of the input String without reaching the limit on "bad guesses", and false if the "bad guesses" limit was reached. You should organize your loop so the return statement is after the loop terminates.
  5. hiddenString: takes an array of char and a String as input parameters and and returns an boolean. The method returns true if we can find the input string inside the array by starting at any position of the array and reading either forwards or backwards.

    > HW2.hiddenString(new char[]{'a','b','r','a','c','a','d','a'}, "acad")
    true
    > HW2.hiddenString(new char[]{'a','b','r','a','c','a','d','a'}, "carb")
    true
    > HW2.hiddenString(new char[]{'a','b','r','a','c','a','d','a'}, "brad")
    false
    
  6. hiddenString: takes a 2-dimensional array of char and a String as input parameters and returns a boolean. The method returns true if we can find the input string inside the array by starting at any position of the array and reading in any straight direction (up, down, left, right, or diagonal).

    > HW2.hiddenString(new char[][]{{'a', 'b', 'c'},{'r','c','a','d'},{'b','r'}}, "bcc")
    true
    > HW2.hiddenString(new char[][]{{'a', 'b', 'c'},{'r','c','a','d'},{'b','r'}}, "ace")
    false
    > HW2.hiddenString(new char[][]{{'a', 'b', 'c'},{'r','c','a','d'},{'b','r'}}, "cad")
    true
    
  7. Extra Credit (up to 10%)capitalizeWords takes a String as input and returns a String as output. Any word in the input string (a word is defined as a sequence of Enlish letters plus the hypen -) that contains any capitalized letter will have all its letters capitalized in the output string.

    > HW2.capitalizeWords("Guess what??  There are twenty-sIx letters in the English alphABEt!")
    "GUESS what??  THERE are TWENTY-SIX letters in the ENGLISH ALPHABET!"

Solutions

Expert Solution

The below program illustrates the above mentioned functionalities upto hangman:

import javax.swing.JOptionPane;

public class HW2 {
        
        public static String replaceFirstK(String str, char c1, char c2, int n){
                char[] cArray = str.toCharArray();
                int count=0;
                for(int i=0;i<cArray.length;i++){
                          if(count==n)
                                  break;
                          if(cArray[i]==c1){
                                  cArray[i]=c2;
                                  count++;
                          }
                }                       
                return String.valueOf(cArray);
        }
        
        public static String allChars(char c1, char c2){
                int ascii1      = (int)c1;
                int ascii2      = (int)c2;
                String result="";
                for(int i=ascii1;i<=ascii2;i++){
                        result= result+(char)i;
                }
                return result;
        }
        
        public static String showCharOfString(String s1, String s2){
                String s3="";
                char[] cArray = s1.toCharArray();
                for(int i=0;i<cArray.length;i++){
                        if(s2.indexOf(cArray[i])==-1){
                                s3=s3+"_"; 
                        }else{
                                s3=s3+cArray[i];   
                        }
                }
                
                return s3;
        }
        
        public static boolean hangman(String s1, int num){
                StringBuilder s2 = new StringBuilder("");
                int badGuesses=0;               
                String guess="",result2="";
                String result1=showCharOfString(s1, s2.toString());
                char c;
                while(badGuesses<=num && !(result2.equals(s1))){
                        while ((guess=JOptionPane.showInputDialog("Guess a letter: ")).length() != 1){
                                System.out.println("enter single character");                           
                        }
                        s2.append(guess.charAt(0));
                        result2=showCharOfString(s1, s2.toString());
                        if(result1.equals(result2)){
                                badGuesses++;
                        }
                        System.out.println(result2+" "+badGuesses);
                        result1=result2;
                }
                if(result2.equals(s1))
                  return true;
                return false;
        }
        
        public static void main(String[] args){
                System.out.println(replaceFirstK("JyothiSreeBhima", 'h', 'p', 1));
                System.out.println(allChars('d','m'));
                System.out.println(showCharOfString("Missouri River","s SR!r"));
                if(hangman("Missouri River",5))
                        System.out.println("You have guessed correctly");       
                else    
                        System.out.println("You re not able to guess the word");        
        }
}

The possible outputs for the above program is :

I have provided the code for only first 4 questions as we can answer maximun 4 parts of a quetion. Please submit the remaining question as a seperated question.

If you have any queries regarding this answer, please reach out through comment section.


Related Solutions

Task 2/2: Java program Based upon the following code: public class Main {   public static void...
Task 2/2: Java program Based upon the following code: public class Main {   public static void main( String[] args ) {     String alphabet = "ABCDEFGHIJKLMNMLKJIHGFEDCBA";     for( <TODO> ; <TODO> ; <TODO> ) {       <TODO>;     } // Closing for loop   } // Closing main() } // Closing class main() Write an appropriate loop definition and in-loop behavior to determine if the alphabet string is a palindrome or not. A palindrome is defined as a string (or more generally, a token) which...
Write the class RecursiveProbs, with the methods listed below. Write all the methods using recursion, not...
Write the class RecursiveProbs, with the methods listed below. Write all the methods using recursion, not loops. You may use JDK String methods like substring() and length(), but do not use the JDK methods to avoid coding the algorithms assigned. For example, don't use String.reverse(). public boolean recursiveContains(char c, String s) returns true if the String contains the char, otherwise returns false. Here is the code for this method, which you should use as an example to see how to...
CODE: C# using System; public static class Lab6 { public static void Main() { // declare...
CODE: C# using System; public static class Lab6 { public static void Main() { // declare variables int hrsWrked; double ratePay, taxRate, grossPay, netPay=0; string lastName; // enter the employee's last name Console.Write("Enter the last name of the employee => "); lastName = Console.ReadLine(); // enter (and validate) the number of hours worked (positive number) do { Console.Write("Enter the number of hours worked (> 0) => "); hrsWrked = Convert.ToInt32(Console.ReadLine()); } while (hrsWrked < 0); // enter (and validate) the...
Using Java Write the class RecursiveProbs, with the methods listed below. Write all the methods using...
Using Java Write the class RecursiveProbs, with the methods listed below. Write all the methods using recursion, NOT LOOPS. You may use JDK String Methods like substring() and length(), but do not use the JDK methods to avoid coding algorithms assigned. For example, don’t use String.revers(). public boolean recursiveContains(char c, String s) { if (s.length() == 0) return false; if (s.charAt(s.length() - 1) == c) return true; else return recursiveContains(c, s.substring(0, s.length() - 1)); } public boolean recursiveAllCharactersSame(String s) return...
Required methods:: public static void processAccount (Account[] acc, printWriter out{}. public static boolean deposit(Account a){}.
Java programming. Required methods::public static void processAccount (Account[] acc, printWriter out{}.public static boolean deposit(Account a){}.public static boolean withdrawal(Account a){}.public static int findAccount(long accountNumber, Account[] acc){}. 1/ Remove the applyRandomBonus method from the test class2/ Create a File, Printwriter for an output file yourlastnameErrorLog.txt4/ Catch InputMismatch and ArrayIndexOutOfBounds exceptions when reading data from the file:a. Skip any lines that cause an exceptionb. Write information about the exception to the log file, yourlastnameError.txtc. Include exception type and line number in exception message...
The code that creates this program using Python: Your program must include: You will generate a...
The code that creates this program using Python: Your program must include: You will generate a random number between 1 and 100 You will repeatedly ask the user to guess a number between 1 and 100 until they guess the random number. When their guess is too high – let them know When their guess is too low – let them know If they use more than 5 guesses, tell them they lose, you only get 5 guesses. And stop...
C++ code Write a program to illustrate how to use the temporary class. Your program must...
C++ code Write a program to illustrate how to use the temporary class. Your program must contain statements that would ask the user to enter data of an object and use the setters to initialize the object. Use three header files named main.cpp, temporary.h, and temporaryImp.cpp An example of the program is shown below: Enter object name (rectangle, circle, sphere, or cylinder: circle Enter object's dimensions: rectangle (length and width) circle (radius and 0) sphere (radius and 0) rectangle (base...
FOR JAVA: Need to write a code for the implementation of this public static method: findLongestPalindrome...
FOR JAVA: Need to write a code for the implementation of this public static method: findLongestPalindrome takes a Scanner scn as its parameter and returns a String. It returns the longest token from scn that is a palindrome (if one exists) or the empty string (otherwise). (Implementation note: You'll find your isPalindrome method helpful here. This method calls for an optimization loop.)
Add comments to the following code: PeopleQueue.java import java.util.*; public class PeopleQueue {     public static...
Add comments to the following code: PeopleQueue.java import java.util.*; public class PeopleQueue {     public static void main(String[] args) {         PriorityQueue<Person> peopleQueue = new PriorityQueue<>();         Scanner s = new Scanner(System.in);         String firstNameIn;         String lastNameIn;         int ageIn = 0;         int count = 1;         boolean done = false;         System.out.println("Enter the first name, last name and age of 5 people.");         while(peopleQueue.size() < 5) {             System.out.println("Enter a person");             System.out.print("First Name: ");             firstNameIn...
Create a new Java file, containing this code public class DataStatsUser { public static void main...
Create a new Java file, containing this code public class DataStatsUser { public static void main (String[] args) { DataStats d = new DataStats(6); d.append(1.1); d.append(2.1); d.append(3.1); System.out.println("final so far is: " + d.mean()); d.append(4.1); d.append(5.1); d.append(6.1); System.out.println("final mean is: " + d.mean()); } } This code depends on a class called DataStats, with the following API: public class DataStats { public DataStats(int N) { } // set up an array (to accept up to N doubles) and other member...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT