Question

This looks long but it is easy just having some trouble please help out thank you....

This looks long but it is easy just having some trouble please help out thank you.

  1. Find and fix all syntax and semantic errors which prevent the program from compiling.
  2. Find and fix all logical errors which cause the program to crash and/or produce unexpected results.
  3. In addition to making sure the code compiles, we have one final method which we need to complete. There is a method in the code, printAll, which is responsible for printing out the entirety of the text. The functionality in this section needs to be completed by you. Look for the TODO in the comments. You should insert code at this spot, which will print out the contents of the input array, line by line and in order. A newline should be printed at the end of each line (println does this automatically). Completing this section is necessary in order for the program to produce an output. Even if the rest of the code still has bugs in it, we can test just this method by passing it a test input.
  4. Once the program successfully compiles, we can attempt to run it. However, we will quickly discover that our work is not done yet. For one thing, the program will hit an infinite loop if we try to run it. Even if we figure out why, the output isn't what we expect. We expect that each line of output fits inside the correct line lengths, and there aren't extraneous newlines in the output. Our goal is to find and fix all bugs which might be preventing the program from running correctly.

    Tip: there are 4 errors to find.

public class StringFormatter {
  
  /** A method which tells us whether the input character c is 
    * whitespace or not.  For the purposes of this method, 
    * whitespace is spaces, newlines, and tab characters. If the
    * character c is one of the whitespace characters, this method
    * will return true, otherwise it will return false. */
  public static boolean isWhiteSpace(char c) {
    return (c == ' ') && (c == '\n') && (c == '\t');
  }
  
  /** Starting from position 'from', this method finds the position of
    * the first non-whitespace character in 's' (in other words, the
    * position of the start of the next word).  Thus, if s="hello  world"
    * and from=5, the method would return 7, i.e. the start position of
    * the word "world".  If there are no more words in the string, the
    * method will return s.length(). */
  public static int getNextWordStart(String s, int from) {
    int pos = from;
    while (pos < s.length() && isWhiteSpace(s.charAt(pos))) { pos++; }
    return pos;
  }

  /** Starting from position 'from', this method finds the position of
    * the first whitespace character in 's' (in other words, the
    * position just after the end of the current word).  Thus, if 
    * s="hello  world" and from=2, the method would return 5, i.e. the 
    * position of the space right after the end of the word "hello".
    * If the current word is at the end of the string, the method will
    * return s.length(). */
  public static getNextWordEnd(String s, int from) {
    int pos = from;
    while (pos < s.length() && !isWhiteSpace(s.charAt(pos)) { pos++; }
    return pos;
  }
  
  /** This method takes an input string, and reformats it so that
    * the length of each line is at most 'size'.  It does this by
    * reading words from the input one by one, and appending to a
    * line of output, moving on to the next line if the size of the
    * line is exceeded.  The output is returned as an array of strings,
    * with each string representing one line of output. */
  public static String[] format(String s, int size) {
    // save the current position in the input string and the 
    // size of the current line of output
    int pos = 0, sizeCurrent = 0;
    
    // we'll store the output text in 'result', with each line separated
    // by newlines
    String result = "";
    
    // keep going until we reach the end of the input string
    while (pos <= s.length()) {
      
      // find the location of the start of the next word
      pos = getNextWordStart(s, pos);
      int start = pos;
      
      // find the location of the end of the word
      pos = getNextWordEnd(s, pos);
      int end = pos;
      
      // use the start and end to get the word
      String nextWord = s.substring(start, end);
      len = nextWord.length();
      
      // case 1, the current line is not empty, but adding this word
      // would cause us to go over the line length.  Restart from
      // the next line
      if (sizeCurrent > 0 && sizeCurrent + 1 + len > size) 
        sizeCurrent = 0;
        result += "\n";
      
      
      // case 2, we're not at the beginning of the line, so add
      // a space before including this world
      if (sizeCurrent > 0) 
        result += " ";
      
      
      // regardless of the case, we want to add this word to the end of the line
      result += nextWord;
      sizeCurrent += len;
      
    }
    
    // we've used newlines to separate lines, so let's use the newlines 
    // as markers to turn the output into an array of Strings
    return result.split("\n");
  
 
  /** A method which prints out the contents of the input.  The input
    * is an array of Strings, so this method should print out each
    * string line by line, with one string per line. */
  public static void printAll(String[] lines) {
    // TODO: enter the code to print all of the input lines here
  }
  
  
  /** The main method will take a text, reformat it to 25-character lines,
    * print the result, then do the same with 70-character lines. */
  public static void main(String[] args) {
    
    // the text to print:
    String text = ""
      + "Mostly, when you see programmers, "
      + "they aren't doing anything. "
      + "One of the attractive things about programmers "
      + "is that you cannot tell whether or not they are "
      + "working simply by looking at them. "
      + "Very often they're "
      + "sitting there seemingly drinking coffee and gossiping, "
      + "or just staring into space. "
      + "What the programmer is trying to do is "
      + "get a handle on all the individual and unrelated "
      + "ideas that are scampering around in his head. "
      + "- Charles M. Strauss"
      
    
    // first, format the text to 25-character lines, and use printAll
    // to print the result.  Note that the format method returns an
    // array of Strings, in which each string represents one line.
    System.out.println("Output formatted to max 25 character lines:");
    System.out.println("-------------------------");
    String[] formatted = format(text, 25);
    printAll(formatted);
    System.out.println("-------------------------");

    // do the same thing, but with 70-character lines
    System.out.println();
    System.out.println("Output formatted to max 70 character lines:");
    System.out.println("----------------------------------------------------------------------");
    formatted = format(text, 70);
    printAll(formatted);
    System.println("----------------------------------------------------------------------");
  }
}
0 0
Add a comment Improve this question Transcribed image text
Answer #1

CORRECTED CODE IS:


public class StringFormatter {

/**
* A method which tells us whether the input character c is whitespace or
* not. For the purposes of this method, whitespace is spaces, newlines, and
* tab characters. If the character c is one of the whitespace characters,
* this method will return true, otherwise it will return false.
*/
public static boolean isWhiteSpace(char c) {
// logical error. Wrong - &&, Correct - ||
return (c == ' ') || (c == '\n') || (c == '\t');
}

/**
* Starting from position 'from', this method finds the position of the
* first non-whitespace character in 's' (in other words, the position of
* the start of the next word). Thus, if s="hello world" and from=5, the
* method would return 7, i.e. the start position of the word "world". If
* there are no more words in the string, the method will return s.length().
*/
public static int getNextWordStart(String s, int from) {
int pos = from;
while (pos < s.length() && isWhiteSpace(s.charAt(pos))) {
pos++;
}
return pos;
}

/**
* Starting from position 'from', this method finds the position of the
* first whitespace character in 's' (in other words, the position just
* after the end of the current word). Thus, if s="hello world" and from=2,
* the method would return 5, i.e. the position of the space right after the
* end of the word "hello". If the current word is at the end of the string,
* the method will return s.length().
*/
public static int getNextWordEnd(String s, int from) {
int pos = from;
// syntax error. closing bracket missing
while (pos < s.length() && !isWhiteSpace(s.charAt(pos))) {
pos++;
}
return pos;
}

/**
* This method takes an input string, and reformats it so that the length of
* each line is at most 'size'. It does this by reading words from the input
* one by one, and appending to a line of output, moving on to the next line
* if the size of the line is exceeded. The output is returned as an array
* of strings, with each string representing one line of output.
*/
public static String[] format(String s, int size) {
// save the current position in the input string and the
// size of the current line of output
int pos = 0, sizeCurrent = 0;

// we'll store the output text in 'result', with each line separated
// by newlines
String result = "";

// keep going until we reach the end of the input string
// logical error (cause of infinite loop). Wrong - " <= ", Correct - " < "
while (pos < s.length()) {

// find the location of the start of the next word
pos = getNextWordStart(s, pos);
int start = pos;

// find the location of the end of the word
pos = getNextWordEnd(s, pos);
int end = pos;

// use the start and end to get the word
String nextWord = s.substring(start, end);
int len = nextWord.length();

// case 1, the current line is not empty, but adding this word
// would cause us to go over the line length. Restart from
// the next line
if (sizeCurrent > 0 && sizeCurrent + 1 + len > size) {
sizeCurrent = 0;
result += "\n"; // logical error. this statement was outside if-statement before
}

// case 2, we're not at the beginning of the line, so add
// a space before including this world
if (sizeCurrent > 0) {
result += " ";
sizeCurrent++; // logical error. when we add a space we should also increase length of current line
}

// regardless of the case, we want to add this word to the end of the line
result += nextWord;
sizeCurrent += len;

}

// we've used newlines to separate lines, so let's use the newlines
// as markers to turn the output into an array of Strings
return result.split("\n");
}

/**
* A method which prints out the contents of the input. The input is an
* array of Strings, so this method should print out each string line by
* line, with one string per line.
*/
public static void printAll(String[] lines) {
// TODO: enter the code to print all of the input lines here
for (String line : lines) {
System.out.println(line);
}
}

/**
* The main method will take a text, reformat it to 25-character lines,
* print the result, then do the same with 70-character lines.
*/
public static void main(String[] args) {

// the text to print:
String text = ""
+ "Mostly, when you see programmers, "
+ "they aren't doing anything. "
+ "One of the attractive things about programmers "
+ "is that you cannot tell whether or not they are "
+ "working simply by looking at them. "
+ "Very often they're "
+ "sitting there seemingly drinking coffee and gossiping, "
+ "or just staring into space. "
+ "What the programmer is trying to do is "
+ "get a handle on all the individual and unrelated "
+ "ideas that are scampering around in his head. "
+ "- Charles M. Strauss"; // syntax error : semi-colon missing.
  
// first, format the text to 25-character lines, and use printAll
// to print the result. Note that the format method returns an
// array of Strings, in which each string represents one line.
  
System.out.println("Output formatted to max 25 character lines:");
System.out.println("-------------------------");
String[] formatted = format(text, 25);
printAll(formatted);
System.out.println("-------------------------");

// do the same thing, but with 70-character lines
System.out.println();
System.out.println("Output formatted to max 70 character lines:");
System.out.println("----------------------------------------------------------------------");
formatted = format(text, 70);
printAll(formatted);
System.out.println("----------------------------------------------------------------------");
}
}

SCREENSHOT OF CODE TO UNDERSTAND INDENTATION:





OUTPUT:



A SCREENSHOT SHOWING THE NUMBER OF CHARACTERS IN EACH LINE (For Verification Purpose Only):

Add a comment
Know the answer?
Add Answer to:
This looks long but it is easy just having some trouble please help out thank you....
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
  • Java class quiz need help~ This is the Backwards.java code. public class Backwards { /** *...

    Java class quiz need help~ This is the Backwards.java code. public class Backwards { /** * Program starts with this method. * * @param args A String to be printed backwards */ public static void main(String[] args) { if (args.length == 0) { System.out.println("ERROR: Enter a String on commandline."); } else { String word = args[0]; String backwards = iterativeBack(word); // A (return address) System.out.println("Iterative solution: " + backwards); backwards = recursiveBack(word); // B (return address) System.out.println("\n\nRecursive solution: " +...

  • Java: Please help with my Tester. I'm having a hard time figuring out my error. Thank...

    Java: Please help with my Tester. I'm having a hard time figuring out my error. Thank you. What the tester requires: The AccountTester This class should consists of a main method that tests all the methods in each class, either directly by calling the method from the Tester or indirectly by having another method call a method. User and Bot information will be read from a file. A sample file is provided. Use this file format to aid in grading....

  • Please help me. package a1; public class Methods {    /*    * Instructions for students:...

    Please help me. package a1; public class Methods {    /*    * Instructions for students: Use the main method only to make calls to the    * other methods and to print some testing results. The correct operation of    * your methods should not depend in any way on the code in main.    *    * Do not do any printing within the method bodies, except the main method.    *    * Leave your testing code...

  • !!!!!!!Java!!!!! When you are confident that your methods work properly and that you can generate random...

    !!!!!!!Java!!!!! When you are confident that your methods work properly and that you can generate random text with my generateText method, you can move on to the second step. Create a third class called Generator within the cs1410 package. Make class. This class should have a main method that provides a user interface for random text generation. Your interface should work as follows: Main should bring up an input dialog with which the user can enter the desired analysis level...

  • Having trouble with the do while/while loop and the switch statement. I got some of the...

    Having trouble with the do while/while loop and the switch statement. I got some of the switch statement but cant get the program to repeat itself like it should.What i have so far for my code is below. Any help is appreciated... i am not sure what I am doing wrong or what i am missing. I am completely lost on the while loop and where and how to use it in this scenario. import java.util.Scanner; public class sampleforchegg {...

  • Looking for some simple descriptive pseudocode for this short Java program (example italicized in bold directly...

    Looking for some simple descriptive pseudocode for this short Java program (example italicized in bold directly below): //Create public class count public class Count {     public static void main(String args[])     {         int n = getInt("Please enter an integer value greater than or equal to 0");                System.out.println("Should count down to 1");         countDown(n);                System.out.println();         System.out.println("Should count up from 1");         countUp(n);     }            private static void countUp(int n)     {...

  • I have already finished most of this assignment. I just need some help with the canMove...

    I have already finished most of this assignment. I just need some help with the canMove and main methods; pseudocode is also acceptable. Also, the programming language is java. Crickets and Grasshoppers is a simple two player game played on a strip of n spaces. Each space can be empty or have a piece. The first player plays as the cricket pieces and the other plays as grasshoppers and the turns alternate. We’ll represent crickets as C and grasshoppers as...

  • 1. What is the height of a full binary search tree that contains 63 nodes 2....

    1. What is the height of a full binary search tree that contains 63 nodes 2. What is the output of this code? Describe what this recursive code does. public class Driver {    public static void main (String[ ] args)   {        String text = “what do I do”;        System.out.println(Mystery.task(text));   } } public class Mystery {    public static int task(String exp)   {         if(exp.equals(“”)           return 0;        else           return 1 + task(exp.substring(1));    } } //from the Java 7 API documentation: public String substring(int...

  • Ask the user for the name of a file and a word. Using the FileStats class,...

    Ask the user for the name of a file and a word. Using the FileStats class, show how many lines the file has and how many lines contain the text. Standard Input                 Files in the same directory romeo-and-juliet.txt the romeo-and-juliet.txt Required Output Enter a filename\n romeo-and-juliet.txt has 5268 lines\n Enter some text\n 1137 line(s) contain "the"\n Your Program's Output Enter a filename\n romeo-and-juliet.txt has 5268 lines\n Enter some text\n 553 line(s) contain "the"\n (Your output is too short.) My...

  • JAVA: Run length encoding is a simple form of data compression. It replaces long sequences of...

    JAVA: Run length encoding is a simple form of data compression. It replaces long sequences of a repeated value with one occurrence of the value and a count of how many times to repeat it. This works reasonably well when there are lots of long repeats such as in black and white images. To avoid having to represent non-repeated runs with a count of 1 and the value, a special value is often used to indicate a run and everything...

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