Question

I am having some trouble writing some java code involving strings. I have included the code...

I am having some trouble writing some java code involving strings. I have included the code provided by my professor below. that has the instructions in it as well

public class StringExercise {
  public static void main(String[] args) {
    String given = "The quick brown fox jumped over the moon!";
    
    String given2 = "mary";
    
    String given3 = "D";
    
    
    //Write a Java code snippet to check (print a boolean) whether the given String ends with the contents of "oon!", see endsWith method
    
    //Write a Java code snippet to check (print a boolean) whether the given String starts with the contents of "Th", see startsWith method
    
    //Write a Java code snippet to check (print a boolean) whether the given2 String has the same contents as the String "mark", see equals method
    
    //Write a Java code snippet to check (print a boolean) whether the given2 String has the same contents, ignoring case, as the String "MARY", see equalsIgnoreCase method
    
    //Write a Java code snippet to print all the indices where the letter 'o' is located at in the given String. See indexOf method and use a while loop.
    
    //Write a Java code snippet to print the substring of the given String from indices 3 through 8. See substring method.
    
    
    //Write a Java code snippet to compare the given3 String with the String "Z" using the compareTo method. Print the integer that is
    //returned from the compareTo method.
    
    
    //Write a Java code snippet to compare the given3 String with the String "A" using the compareTo method. Print the integer that is
    //returned from the compareTo method.
    
    
    //Write a Java code snippet to compare the given3 String with the String "D" using the compareTo method. Print the integer that is
    //returned from the compareTo method.
    
  }

}

Homework Answers

Answer #1

Code:

public class StringExercise {

    public static void main(String[] args) {

        String given = "The quick brown fox jumped over the moon!";
  String given2 = "mary";
  String given3 = "D";

        // Write a Java code snippet to check (print a boolean) whether the given String

        // ends with the contents of "oon!", see endsWith method

        System.out.println(given.endsWith("oon!"));

        // Write a Java code snippet to check (print a boolean) whether the given String

        // starts with the contents of "Th", see startsWith method

        System.out.println(given.startsWith("Th"));

        // Write a Java code snippet to check (print a boolean) whether the given2

        // String has the same contents as the String "mark", see equals method

        System.out.println(given2.equals("mark"));

        // Write a Java code snippet to check (print a boolean) whether the given2

        // String has the same contents, ignoring case, as the String "MARY", see

        // equalsIgnoreCase method

        System.out.println(given2.equalsIgnoreCase("MARY"));

        // Write a Java code snippet to print all the indices where the letter 'o' is

        // located at in the given String. See indexOf method and use a while loop.

        int index = given.indexOf('o');

        while (index >= 0) {

            System.out.println(index);

            index = given.indexOf('o', index + 1);

        }

// we get the first index of 'o' and then iterate to find the next occurences in the remaining string.
// .indexOf('o',index) begins the search from index, so the previous one is not counted.

        // Write a Java code snippet to print the substring of the given String from

        // indices 3 through 8. See substring method.

        System.out.println(given.substring(3, 9));

  //9 is exculsive. So, to get the substring from 3 to 8, we pass 3 and 9 as parameters.

        // Write a Java code snippet to compare the given3 String with the String "Z"

        // using the compareTo method. Print the integer that is

        // returned from the compareTo method.

        System.out.println(given3.compareTo("Z"));

        // Write a Java code snippet to compare the given3 String with the String "A"

        // using the compareTo method. Print the integer that is

        // returned from the compareTo method.

        System.out.println(given3.compareTo("A"));

        // Write a Java code snippet to compare the given3 String with the String "D"

        // using the compareTo method. Print the integer that is

        // returned from the compareTo method.

        System.out.println(given3.compareTo("D"));

    }

}

Reference screenshot:

Output of the code:

Explanation:

The string object in java comes with many predefined functions to perform operations on strings. In this exercise you are being asked to use some of them.

  • stringVariable.endsWith("parameterString") -- checks if our string ends with the specified string.
  • stringVariable.startsWith("parameterString") -- checks if our string starts with the specified string.
  • stringVariable.equals("parameterString") -- compares the string charater by charater to find if they are equal or not
  • stringVariable.equalsIgnoreCase("parameterString") -- compares the string charater by charater to find if they are equal or not while ignoring the case of characters whether upper or lower.
  • stringVariable.indexOf("string/character") -- returns the first index in the string of character passed as parameter.
  • stringVariable.indexOf("string/character", int index) -- returns the first index in the string of character passed as parameter. It starts the search after the input index.
  • stringVariable.substring(beginIndex, endIndex) -- returns the part of whole string specified by the indices given in parameter. The endIndex is exclusive, meaning substring(3,8) returns the string from index 3 to 7.
  • stringVariable.compareTo("parameterString") -- Compares the strings lexicographically. The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal.
Know the answer?
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
Similar Questions
You are given the following Java files: TestCharacterStack.java that contains class LLStack with class stackNode listed...
You are given the following Java files: TestCharacterStack.java that contains class LLStack with class stackNode listed as inner class.    You are given the following Java file: TestCharacterStack.java inside the class add the method below:         public boolean ParenthesesMatching (String text) takes a string text, and parenthesis whether its parenthesis are "balanced." Hint: for left parenthesis, push onto stack; for right parenthesis, pop from stack and check whether popped element matches right parenthesis, else return false. If returned value is...
I need a Flowchart and Code for the following Java Program Write a method that converts...
I need a Flowchart and Code for the following Java Program Write a method that converts milliseconds to hours, minutes, and seconds using the following header: public static String convertMillis(long millis) The method returns a string as hours:minutes:seconds. For example,convertMillis(5500) returns a string 0:0:5, convertMillis(100000) returns a string 0:1:40, and convertMillis(555550000) returns a string 154:19:10. Write a test program that prompts the user to enter a long integer for milliseconds and displays a string in the format of hours:minutes:seconds.
Write Java code that attempts to call a method named bootUp() which takes a String parameter...
Write Java code that attempts to call a method named bootUp() which takes a String parameter and returns an integer value. The String parameter should be read from a file named "bootConfig.txt" and is the only value in the file. If a BootUpException is thrown, print the Exception object's message. If a DriverException occurs, call the reboot() method and rethrow the original DriverException object. If any other type of Exception is thrown, print a generic error message to the console....
[Java] I'm not sure how to implement the code. Please check my code at the bottom....
[Java] I'm not sure how to implement the code. Please check my code at the bottom. In this problem you will write several static methods to work with arrays and ArrayLists. Remember that a static method does not work on the instance variables of the class. All the data needed is provided in the parameters. Call the class Util. Notice how the methods are invoked in UtilTester. public static int min(int[] array) gets the minimum value in the array public...
What's wrong with this code? #Java Why I am getting error in : int BusCompare =...
What's wrong with this code? #Java Why I am getting error in : int BusCompare = o1.numberOfBusinesses.compareTo(o2.numberOfBusinesses); public class TypeComparator implements Comparator<Type> { @Override public int compare(Type o1, Type o2) { // return o1.name.compareTo(o2.name); int NameCompare = o1.name.compareTo(o2.name); int BusCompare = o1.numberOfBusinesses.compareTo(o2.numberOfBusinesses); // 2-level comparison using if-else block if (NameCompare == 0) { return ((BusCompare == 0) ? NameCompare : BusCompare); } else { return NameCompare; } } } public class Type implements Comparable<Type> { int id; String name; int...
Here is the code I am supposed to Analyze: // If we want to use the...
Here is the code I am supposed to Analyze: // If we want to use the Scanner class (type) to get user input, we need // to import the following Java package that includes the Scanner class // definitions. We do not have to add an import statement to use the // print() or println() methods of the System object, because they // are built in. import java.util.Scanner; public class PRG420Week1_AnalyzeAssignment { /* The main() method you see below is...
is there anything wrong with the solution. the question are from java course Write a main...
is there anything wrong with the solution. the question are from java course Write a main method that will request the user to enter Strings using a JOptionPane input dialog. The method should continue accepting strings until the user types “STOP”.       Then, using a JOptionPane message dialog, tell the user how many of the strings begin and end with a digit. Answer: import javax.swing.*; public class IsAllLetters {     public static void main(String[] args) {         String input;         int count =...
Assignment 1 - ITSC 2214 I have to complete the array list for a shopping list...
Assignment 1 - ITSC 2214 I have to complete the array list for a shopping list code and can't figure out how to complete it: Below is the code Complete the three empty methods (remove(), find(), and contains()) in the ShoppingListArrayList.java file. These methods are already implemented in the ShoppingListArray class. /////////////////////////////////////////////////////////////////////////////////////////////////////////// Grocery Class (If this helps) package Shopping; public class Grocery implements Comparable<Grocery> { private String name; private String category; private int aisle; private float price; private int quantity;...
Below is the assignment, I have completed and tested every step except for the last one....
Below is the assignment, I have completed and tested every step except for the last one. "Print aLine with the first 'c' 'C' 'd' or 'D' removed." any help would be appreciated ASSIGNMENT Write a program using Scanner and its nextLine method. The following is an example of how to use nextLine Scanner kybd = new Scanner(System.in); System.out.println("Enter a line of text"); String aLine = kybd.nextLine(); If the user's input is shorter than 7 characters, print the message "The input...
JAVA CODE BEGINNERS, I already have the demo code included Write a Bottle class. The Bottle...
JAVA CODE BEGINNERS, I already have the demo code included Write a Bottle class. The Bottle will have one private int that represents the countable value in the Bottle. Please use one of these names: cookies, marbles, M&Ms, pennies, nickels, dimes or pebbles. The class has these 14 methods: read()(please use a while loop to prompt for an acceptable value), set(int), set(Bottle), get(), (returns the value stored in Bottle), add(Bottle), subtract(Bottle), multiply(Bottle), divide(Bottle), add(int), subtract(int), multiply(int), divide(int), equals(Bottle), and toString()(toString()...