Question

create a new Java application called "CheckString" (without the quotation marks) according to the following guidelines....

create a new Java application called "CheckString" (without the quotation marks) according to the following guidelines.

** Each method below, including main, should handle (catch) any Exceptions that are thrown. ** ** If an Exception is thrown and caught, print the Exception's message to the command line. **

Write a complete Java method called checkWord that takes a String parameter called word, returns nothing, and is declared to throw an Exception of type Exception. In the method, check if the first character of the parameter is a letter. If it is not a letter, the method throws an Exception of type Exception with the message of: "This is not a word."

Write a complete Java method called getWord that takes no parameters and returns a String. The method prompts the user for a word, and then calls the checkWord method you wrote in #1 above, passing as a parameter the word the user provided as input. Make sure the getWord method handles the Exception that may be thrown by checkWord.

Write a complete Java method called writeFile that takes two parameters: an array of Strings (arrayToWrite) and a String (filename). The method writes the Strings in the arrayToWrite array to a text file called filename (the parameter), with each String on a separate line.

Write a complete Java method called readFile that takes a String as a parameter (filename) and returns an ArrayList of Strings (fileContents). The method reads the text file identified by the filename parameter and populates the ArrayList with an element for each line in the text file.

In your main method, do the following in the order specified:

Call the getWord method you wrote in #2 above and print the result to the command line.

Create an array of Strings called testData and populate it with at least three elements.

Call the writeFile method you wrote in #3 above passing the array you created in #5.2 and the String "data.txt".

Call the readFile method you wrote in #4 above to read the file you wrote in #5.3. Assign the result of readFile to an ArrayList variable in main called fileContents.

Write a loop to print the contents of the fileContents ArrayList to the command line.

Notes

For this PA you can use any of the IO classes. For example, you can use either FileWriter or PrintWriter, and for reading Strings probably you will want to use BufferedReader. There should be a total of four methods in additional to main: checkWord, getWord (which calls checkWord), writeFile, and readFile. Also, the PA instructions say that the methods including main should handle exceptions. When coding up the solution experiment with try-catch within methods vs having the methods throw an exception and then catching it in main. Be sure to test your code for throwing a FileNotFoundException (it is an easy exception to test).

If you are not sure or want to experiment with different io classes, you can import them all using:

import java.io.*;

There are several implementation approaches. Below is one example framework/outline which might be helpful. Please feel free to experiment with other approaches.

public static void checkWord(String word) throws Exception {

// Uses charAt method to test if the first letter of string variable word

// is a character. If not, throw new exception

}

public static String getWord() {

// Declare a local scanner

// Prompt the user to enter a word

// Think about using a loop to give the user multiple opportunities to correctly enter a string

// Read into a string

// Call checkWord method passing the string as a parameter

// checkWord can throw an exception; call checkWord in a try/catch block

// Return the string to main if a valid string

}

public static void writeFile(String[] arrayToWrite, String filename) throws IOException {

// Example using FileWriter but PrintWriter could be used instead

// Create a FileWriter object

FileWriter fileWordStream = new FileWriter(filename);

// Use a loop to write string elements in arrayToWrite to fileWordStream

// In the loop use the lineSeparator method to put each string on its own line

fileWordStream.write(System.lineSeparator());

}

public static ArrayList readFile(String filename) throws FileNotFoundException, IOException {

  // Declare local ArrayList

// Create a new File object using filename parameter

// Check if the file exists, if not throw a new exception

// Create a new BufferedReader object     

BufferedReader fileWordStream = new BufferedReader(new FileReader(filename));

// use a loop and the readLine method to read each string (on its own line) from the file

// return the filled ArrayList to main

}

public static void main(String[] args) {

// create a string with literal values to write to the file

String[] testData = {"cat", "dog", "rabbit"};

// Create an ArrayList for reading the file

// Declare a string variable containing the file name “data.txt”

// Call getWord, assign the returned string to a variable and display it

// Call writeFile and readFile methods in a try block

// Printout the contents of the ArrayList after the call to readFile

// catch two types of exceptions

}

An example run might look like:

run:

Please enter a word: testing

The word is: testing

cat

dog

rabbit

BUILD SUCCESSFUL (total time: 7 seconds)

Here is an example run where an integer is entered instead of a word. A while loop is used to keep the user in the loop until they enter a string:

run:

Please enter a word: 78

This is not a word.

Please enter a word: 59

This is not a word.

Please enter a word: testing

The word is: testing

cat

dog

rabbit

BUILD SUCCESSFUL (total time: 21 seconds)

Here is a run that tests the exception thrown by the readFile method. I passed the readFile method a different file name as a parameter (not data.txt). Of course, that file name was not found which throws the exception ‘FileNotFoundException’ which is catch in main:

run:

Please enter a word: testing

The word is: testing

FileNotFoundException: File not found

BUILD SUCCESSFUL (total time: 4 seconds)

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

here is your program : ------------->>>>>>>>>>>

import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;

public class StringCheck{
//There are several implementation approaches. Below is one example framework/outline which might be helpful. Please f//eel free to experiment with other approaches.
public static void checkWord(String word) throws Exception {
// Uses charAt method to test if the first letter of string variable word
// is a character. If not, throw new exception
if(Character.isLetter(word.charAt(0))){
  return;
}else{
  throw new Exception("This is not a word");
}
}
public static String getWord() {
// Declare a local scanner
// Prompt the user to enter a word
// Think about using a loop to give the user multiple opportunities to correctly enter a string
// Read into a string
// Call checkWord method passing the string as a parameter
// checkWord can throw an exception; call checkWord in a try/catch block
// Return the string to main if a valid string
Scanner sc = new Scanner(System.in);
boolean st = true;
String word = null;
while(st){
  System.out.println("Enter a Word : ");
  word = sc.next();
  try{
   checkWord(word);
   st = false;
  }catch(Exception e){
   System.out.println(e);
   st = true;
  }
}
sc.close();
return word;
}
public static void writeFile(String[] arrayToWrite, String filename) throws IOException {
// Example using FileWriter but PrintWriter could be used instead
// Create a FileWriter object
FileWriter fileWordStream = new FileWriter(filename);
// Use a loop to write string elements in arrayToWrite to fileWordStream
for(int i = 0;i<arrayToWrite.length;i++){
fileWordStream.write(arrayToWrite[i]+System.lineSeparator());
}
fileWordStream.flush();
fileWordStream.close();
// In the loop use the lineSeparator method to put each string on its own line
}
public static ArrayList readFile(String filename) throws FileNotFoundException, IOException {
// Declare local ArrayList
ArrayList<String> words = new ArrayList<>();
// Create a new File object using filename parameter
File file = new File(filename);
// Check if the file exists, if not throw a new exception
if(!file.exists()){
  throw new FileNotFoundException("File not Found");
}
// Create a new BufferedReader object     
Scanner fsc = new Scanner(file);
// use a loop and the readLine method to read each string (on its own line) from the file
while(fsc.hasNextLine()){
words.add(fsc.nextLine());
}
fsc.close();
// return the filled ArrayList to main
return words;
}
public static void main(String[] args) {
// create a string with literal values to write to the file
String[] testData = {"cat", "dog", "rabbit"};
// Create an ArrayList for reading the file
ArrayList<String> words = new ArrayList<>();
// Declare a string variable containing the file name "data.txt"
String file = "data.txt";
// Call getWord, assign the returned string to a variable and display it
String word = getWord();
System.out.println("The word is : "+word);
// Call writeFile and readFile methods in a try block
try{
writeFile(testData,file);
words = readFile(file);
// Printout the contents of the ArrayList after the call to readFile
for(int i = 0;i<words.size();i++){
  System.out.println(words.get(i));
}
}catch(FileNotFoundException e){
System.out.println(e);
}catch(IOException e){
System.out.println("IOException: error occured in input output");
}
// catch two types of exceptions
}
}

Add a comment
Know the answer?
Add Answer to:
create a new Java application called "CheckString" (without the quotation marks) according to the following guidelines....
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
  • I've been assigned to create a new Java application called "CheckString" (without the quotation marks) according...

    I've been assigned to create a new Java application called "CheckString" (without the quotation marks) according to the following guidelines. ** Each method below, including main, should handle (catch) any Exceptions that are thrown. ** ** If an Exception is thrown and caught, print the Exception's message to the command line. ** Write a complete Java method called checkWord that takes a String parameter called word, returns nothing, and is declared to throw an Exception of type Exception. In the...

  • create a new Java application called "WeightedAvgDataAnalyzer" (without the quotation marks), that modifies the DataAnalyzer.java in...

    create a new Java application called "WeightedAvgDataAnalyzer" (without the quotation marks), that modifies the DataAnalyzer.java in Horstmann Section 7.5, pp. 350-351 according to the specifications below. The input file should be called 'data.txt' and should be created according to the highlighted instructions below. Note that even though you know the name of the input file, you should not hard-code this name into your program. Instead, prompt the user for the name of the input file. The input file should contain...

  • create a new Java application called "WeightedAvgWithExceptions" (without the quotation marks), according to the following guidelines...

    create a new Java application called "WeightedAvgWithExceptions" (without the quotation marks), according to the following guidelines and using try-catch-finally blocks in your methods that read from a file and write to a file, as in the examples in the lesson notes for reading and writing text files. Input File The input file - which you need to create and prompt the user for the name of - should be called 'data.txt', and it should be created according to the instructions...

  • create a new Java application called "RecursiveTriangle" (without the quotation marks) according to the following guidelines....

    create a new Java application called "RecursiveTriangle" (without the quotation marks) according to the following guidelines. Modify the example in Horstmann Section 5.9, pp. 228-230 so that the triangle displays “in reverse order” as in the example below, which allows the user to set the number of lines to print and the String used for printing the triangle. Use a method to prompt the user for the number of lines (between 1 and 10) to print. This method should take...

  • QUESTION The ReadFile class opens and reads a text file. The WriteFile class opens and writes...

    QUESTION The ReadFile class opens and reads a text file. The WriteFile class opens and writes to a file. Compile and run these programs. There are several ways to read/write text files. The examples shown here are just one way of achieving this. Look at the API for the BufferedReader class. The readline() method is a simple way to read the text file line by line. It returns null when the end of the file has been reached. https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html Look...

  • Please provide the full code...the skeleton is down below: Note: Each file must contain an int...

    Please provide the full code...the skeleton is down below: Note: Each file must contain an int at the beginning, stating the number of records in the file. Afterwards, the number of records in the file will follow. Each record that follows will consist of a last name (String), and a gpa (double). However, to test the error handling of your program, the number of records will not always match the int value. All possible combinations should be tested. 1.) Prompt...

  • Lab 3 Step One First, create an empty directory for lab3. There is no starter code for this lab. You will be throwing an...

    Lab 3 Step One First, create an empty directory for lab3. There is no starter code for this lab. You will be throwing and catching exceptions in this exercise. Create a file called RuntimeException.h and put the following code in it. #include <string> class RuntimeException { private: string errorMsg; public: RuntimeException(const string& err) { errorMsg = err; } string getMessage() const { return errorMsg; } } Step Two In a new .cpp file in your directory, write a main function...

  • create a new Java application called "Scorer" (without the quotation marks) that declares a two-dimensional array...

    create a new Java application called "Scorer" (without the quotation marks) that declares a two-dimensional array of doubles (call it scores) with three rows and three columns and that uses methods and loops as follows. Use a method containing a nested while loop to get the nine (3 x 3) doubles from the user at the command line. Use a method containing a nested for loop to compute the average of the doubles in each row. Use a method to...

  • 7.2 Write a Java program called to create an Excel spreadsheet Create a class called Food...

    7.2 Write a Java program called to create an Excel spreadsheet Create a class called Food to represent a Lunch food item. Fields include name, calories, carbs In a main method (of a different class), ask the user "How many things are you going to eat for lunch?". Loop through each food item and prompt the user to enter the name, calories, and grams of carbs for that food item. Create a Food object with this data, and store each...

  • Java Framework Collection Assign. Create a class called ArrayListExample Create a ArrayList object called languageList which...

    Java Framework Collection Assign. Create a class called ArrayListExample Create a ArrayList object called languageList which accept type of String Add English, French, Italian and Arabic strings into languageList array object Print languageList using Iterator object Sort ArrayList object alphabetically Print languageList using Iterator object Solution will produce following: ArrayListExample class ArrayList object called languageList ArrayListExampleTest class with main method

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