Difference between revisions of "Esperanto"

From CompSciWiki
Jump to: navigation, search
m (Spelling Updated)
 
(31 intermediate revisions by 3 users not shown)
Line 3: Line 3:
 
|ProblemName=Esperanto
 
|ProblemName=Esperanto
  
|Problem= ENTER PROBLEM HERE
+
|Problem=
  
 +
Esperanto is a language invented in the 1880s by L. L. Zamenhof. It was invented to "create an easy-to-learn and politically neutral language that would serve as a universal second language to foster peace and international understanding."
 +
One of the benefits of designing your own language is that you can impose strict rules on the language. In this question, you will use the rules of Esperanto to identify the parts of speech of different words. The rules for identifying parts of speech in Esperanto are:
  
  
<ul>
+
<table border="1" cellpadding="5" cellspacing="5" width="100%">
<li>Organize the code.</li>
+
<li>Add comments to explain the code.</li>
+
<li>Optimize the code by removing unnecessary variables.</li>
+
<li>Find any errors in the code.</li>
+
<li>Add code to output progress reports as the program executes.</li>
+
</ul>
+
Remember to abide by the company coding standards while repairing the code.
+
  
 +
<tr>
 +
<th>If the word ends in ..</th>
 +
<th>it is a(n)...</th>
 +
</tr>
  
|Solution=
+
<tr>
There are nine steps to improve this messy code so it complies with the company (and coincidentally, comp 1010) coding standards:
+
<td width="50%">a</td><td>adjective</td>
 +
</tr>
  
 +
<tr>
 +
<td width="50%">o or on</td><td>singular noun</td>
 +
</tr>
  
==Organize the Code==
+
<tr>
First, organized code is vital to the readability of the code. The [http://courses.cs.umanitoba.ca/index.asp?sec=3394&too=30&eve=1&ppa=5178 COMP 1010 Coding Standards] give the foundation required to complete the code organization task for this [[Case_Study_I|case study]]. Each of the headings below describe a specific task that helps organize the code.
+
<td width="50%">oj or ojn</td><td>plural noun</td>
 +
</tr>
  
===Separate the Statements===
+
<tr>
The code file contains more than one [[Your First Java Program#Statements|statements]] on each line.
+
<td width="50%">e</td><td>adverb</td>
<pre>
+
</tr>
int digit1 = (isbn % 10);int total = digit1 * 9;isbn = isbn / 10;
+
int digit2 = (isbn % 10);total = total + digit2 * 8;isbn = isbn / 10;
+
</pre>
+
Each of the above lines of code performs a similar function. Each line can be interpretted as a block of code. By placing each [[Your First Java Program#Statements|statements]] on a separate line and grouping the statements into appropriate code blocks, the result should look something like the following:
+
<pre>
+
int digit1 = (isbn % 10);
+
int total = digit1 * 9;
+
isbn = isbn / 10;
+
int digit2 = (isbn % 10);
+
total = total + digit2 * 8;
+
isbn = isbn / 10;
+
</pre>
+
By placing each of the [[Your First Java Program#Statements|statements]] on a separate line, the readability of the code increases dramatically.
+
  
===Separate Statements into Code Blocks===
+
</table>
Once the [[Your First Java Program#Statements|statements]] are readable, the next step would be to organize them into code blocks as stated in [http://courses.cs.umanitoba.ca/index.asp?sec=3394&too=30&eve=1&ppa=5178 COMP 1010 Coding Standards]. Continuing with our previous example, the functionality of the code can be broken into two distinct code blocks.
+
<pre>
+
int digit1 = (isbn % 10);
+
int total = digit1 * 9;
+
isbn = isbn / 10;
+
  
int digit2 = (isbn % 10);
 
total = total + digit2 * 8;
 
isbn = isbn / 10;
 
</pre>
 
Almost each line of code in the messy code file can be considered a separate code block. Take the time to read the code and understand how everything works together before deciding which [[Your First Java Program#Statements|statements]] should be grouped together.
 
  
One of the code blocks that should be added is a variable declaration code block at the beginning of [[Your First Java Program#The Main Method|the main method]]. Throughout the [[Case Study I#Code|messy code]], integers are declared. All of the [[Variables and Literals#Variables|declaration statements]] should be placed at the beginning of [[Your First Java Program#The Main Method|the main method]] to ensure the code stays organized. Going to the previous example, two [[Variables and Literals#Variables|declaration statements]] can be moved to the top as depicted below.
+
This means there are no exceptions in Esperanto, like how in English the plural of goose is geese and while you usually add 'ly' to the end of an adjective to make it an adverb, 'goodly' isn't an adverb.
 +
 
 +
Write a program that accepts words in Esperanto, and identifies whether each is an adjective, singular noun, plural noun or adverb.
 +
 
 +
===Input:===
 +
 
 +
Use Scanner to accept input in this question. Prompt the user to input a word. If the user types in "cesi" ("quit" in Esperanto), the program should quit. Otherwise, it should accept the input and process it as a word in Esperanto.
 +
 
 +
After processing the word, the user should be prompted to enter another word. Assume the user inputs the words entirely in lowercase and that all words are at least three letters long.  
 +
 
 +
===Calculate and Output:===
 +
 
 +
Use System.out. for all output. Use the charAt() and length() methods to find the last (one or possibly two) characters and determine which part of speech (adverb, singular noun, plural noun or adverb) the word is. If the word is in none of the four categories, print out an error message telling the user that the part of speech cannot be identified. An execution of your program would look like this:
 +
 
 
<pre>
 
<pre>
int digit1;
+
Enter a word in Esperanto: komputilo
int digit2;
+
komputilo is a singular noun.
  
digit1 = (isbn % 10);
+
Enter a word in Esperanto: sciencon
int total = digit1 * 9;
+
sciencon is a singular noun.
isbn = isbn / 10;
+
  
digit2 = (isbn % 10);
+
Enter a word in Esperanto: cesi
total = total + digit2 * 8;
+
 
isbn = isbn / 10;
+
Programmed by [your name here].
 +
End of processing.
 
</pre>
 
</pre>
  
===Add Comments to Explain the Code===
 
The [http://courses.cs.umanitoba.ca/index.asp?sec=3394&too=30&eve=1&ppa=5178 COMP 1010 coding standards], or the Funky Books Inc. coding standards, make numerous points concerning [[Comments|comments]] in code. To be specific, statements 1, 2, 4, and 7 can be applied to the code file for this [[Case Study I|case study]]. All major code blocks should be identified by now. Look over each code block and briefly explain what it does in a comment. Since all [[Variables and Literals#Variables|declaration statements]] have been moved to the top of the [[Your First Java Program#The Main Method|the main method]] , make sure to apply coding standard 7 from the [http://courses.cs.umanitoba.ca/index.asp?sec=3394&too=30&eve=1&ppa=5178 COMP 1010 Coding Standards].
 
  
==Optimize the Code by Removing Unnecessary Variables==
+
|Solution=
At the top of [[Your First Java Program#The Main Method|the main method]], there should now be a number of [[Variables and Literals#Variables|variables]]
+
 
declared. Notice that there are nine different "digit" [[Variables and Literals#Variables|variables]] which are only used once to store the same calculation.  
+
Remember to abide by the [http://courses.cs.umanitoba.ca/index.asp?sec=3394&too=30&eve=1&ppa=5178 COMP 1010 coding standards] while writing the code.
 +
 
 +
==Organize the Code==
 +
 
 +
When you begin to write a solution, the best way to approach this is to divide the answer into sections of code. You want to break down the problem into smaller sections or ideas that can be solved as steps.  Begin by creating a new blank solution file using your standard setup. See below:
  
 
<pre>
 
<pre>
int digit1;
 
int digit2;
 
  
digit1 = (isbn % 10);
+
public class A2Q1
int total = digit1 * 9;
+
{
isbn = isbn / 10;
+
public static void main(String[] args)  
 +
{
 +
}
 +
}
  
digit2 = (isbn % 10);
 
total = total + digit2 * 8;
 
isbn = isbn / 10;
 
 
</pre>
 
</pre>
The code sample from above shows two of the nine digit [[Variables and Literals#Variables|variables]]. These two [[Variables and Literals#Variables|variables]] can be replaced with a single one as follows:
+
 
 +
Next begin to write the code for the sections you defined.  For this solution the steps we will use are:
 +
 
 +
* Capture the user's input from the keyboard
 +
* Get the program to loop until some end condition is met - in this case when "cesi" is entered
 +
* Write the compare code to determine what was entered - ie. adjective, adverb, etc
 +
* Write the code to display the output
 +
 
 +
===Step No. 1===
 +
 
 +
Begin by writing the code to get the user's input from the keyboard.  As per the assignment specifications, we will be using Scanner to capture what the user inputs via the keyboard.  In order for you to use scanner, you must first include the "java.util.Scanner" library.  To include this library add the below import statement as first line of your solution file.
 +
 
 
<pre>
 
<pre>
int digit;
 
  
digit = (isbn % 10);
+
import java.util.Scanner;
int total = digit * 9;
+
isbn = isbn / 10;
+
  
digit = (isbn % 10);
 
total = total + digit * 8;
 
isbn = isbn / 10;
 
 
</pre>
 
</pre>
  
==Fix the Errors in the Code==
+
Scanner does exactly what you think it does.  It scans the keybaord logging input until it encounters a new line character. When a new line character is encountered, the Scanner will stop scanning and the keys pressed are now stored.  An example of a new line character is when the "Enter" key is pressed.
The [[Case Study I#Code|messy code]] contained a total of eight different coding errors. Each error presented in this section is ordered as it appears in the [[Case Study I#Code|code]] from the [[Case Study I|case study]].
+
 
===Error One===
+
====Usage:====
 +
 
 +
To use Scanner, as noted above you must first have imported the java.util.Scanner library. Next, you must make a new instance of Scanner.  Do this by declaring a new instance and instantiating it.  You must also allocate space to store what the Scanner captures.  Do this by assigning Scanner's output to a local variable.  See below:
 +
 
 
<pre>
 
<pre>
String temp = JOptionPane.showInputDialog("")
+
 
</pre>
+
Scanner kbd = new Scanner(System.in); //create a new instance of Scanner
Technically, the above code does not break the functionality of the application as the method call still makes the [[Input using JOptionPane#Input Dialog|input dialog]] appear to take input from the user. Although, from a usability standpoint the code does cause an error. The user who is running the application needs to know what to enter as input into the [[Input using JOptionPane#Input Dialog|input dialog]]. Without a proper message, the user cannot be expected to know what the application is expecting as input. An example of a proper message is as follows:
+
String word; // Esperanto word - holds the User's input
<pre>
+
 
temp = JOptionPane.showInputDialog("Enter the first 9 digits of a 10-digit ISBN number.");
+
 
 +
System.out.print("Enter a word in Esperanto: ");//print a message to let the User know what they should do
 +
word = kbd.next(); // get input from User
 +
 
 +
 
</pre>
 
</pre>
  
===Error Two===
+
''CHECK POINT:''
 +
 
 +
At this point you can now compile and run the code you have.  Ensure that your program does compile without any errors.  If your code does not compile, look closely at the error message generated and try to correct the problem.  If you successfully compile your code, try running it.  Running your code should prompt you for input and you should be able to enter it.  At this point, you will only be prompted for input once.
 +
 
 +
===Step No. 2===
 +
 
 +
At this point we have code that can read in input from a user.  However, the current code will only read input in once and then end.  We now want to modify this code so that it will read in input until some "end" condition is met.  For this problem, our end condition will be when the word "cesi" is entered.  Since we know what our end condition is we can test for it.  The best way to carry out this test is through the use of a while loop.  Please see the section on [http://wiki1010.cs.umanitoba.ca/mediawiki/index.php/While_Loops while loops] to familiarize yourself with their workings.
 +
 
 +
====Syntax:====
 +
 
 +
In Java, the general form of a while loop is:
 +
 
 
<pre>
 
<pre>
int isbn = Temp;
+
 
</pre>
+
while(test_condition) //this is where we test for the end condition
There are two problems with the above code sample. The first problem being that the [[Variables and Literals#Variables|variable]] "Temp" is of type [[Strings|string]] and not of the primitive type [[Common Primitive Variables#Primitive Type int|int]]. The second problem is the name of the [[Variables and Literals#Variables|variable]] "Temp". The [[Variables and Literals#Variables|variable]] was originally declared as "temp" and Java is a [[Your First Java Program#Case Sensitivity|case sensitive]] language. Both programs are repaired by replacing the code with the line below.
+
{
<pre>
+
  ...
isbn = Integer.parseInt(temp);
+
  statements;
 +
  ...
 +
}
 +
 
 
</pre>
 
</pre>
  
===Error Three===
+
 
 +
For our program we will insert a while loop statement that looks as follows:
 +
 
 
<pre>
 
<pre>
isbn = isbn // 10;
+
 
</pre>
+
while (!word.equalsIgnoreCase("cesi"))
An extra front slash changes the [[Arithmetic Operators|division operation]] into a comment which also comments out the semi-colon required at the end of every [[Your First Java Program#Statements|statement]]. Remove the extra front slash to correct the error.  
+
{
<pre>
+
...statements....
isbn = isbn / 10;
+
}
 +
 
 
</pre>
 
</pre>
  
===Error Four===
+
The way that this statement will be evaluated is as follows:
 +
* word has already been assigned the input from the user (from the previous step)
 +
* the while loop will take word and apply the method "equalsIgnoreCase"
 +
* if the result of this matches the expression "cesi" then the loop will exit
 +
* if the result does not match the expression "cesi" the loop will continue to run
 +
 
 +
 
 +
''IMPORTANT NOTE:''
 +
 
 +
Note the usage of equalsIgnoreCase() here.  The reason for this is to catch input that matches "cesi" in both upper and lower case.  We are not concerned with the case of the letters, just that "cesi" is entered.  If you choose to use equals() then "cesi" would have to be entered exactly.  "CESI" wound not qualify and the loop would continue to run.
 +
 
 +
 
 +
''CHECK POINT:''
 +
 
 +
At this point your code should look as follows:
 +
 
 
<pre>
 
<pre>
digit = (isbn % 10)  
+
 
</pre>
+
public class A2Q1
The [[Your First Java Program#Statements|statement]] above is missing the semi-colon at the end of the line. Add the semi-colon to fix the error.
+
{
<pre>
+
 
digit = (isbn % 10);
+
public static void main(String[] args)
 +
{
 +
 +
Scanner kbd = new Scanner(System.in);
 +
String word; // Esperanto word
 +
 
 +
 
 +
System.out.print("Enter a word in Esperanto: ");
 +
word = kbd.next();
 +
 
 +
 
 +
// keep going until cesi is typed.
 +
while (!word.equalsIgnoreCase("cesi"))
 +
{
 +
                    word = kbd.next();
 +
}
 +
 
 +
}
 +
 
 +
}
 +
 
 +
 
 
</pre>
 
</pre>
  
===Error Five===
+
Again compile and run your code.  Your code should continue to prompt you for input until "cesi" is entered. If you are not successful in compiling your code, pay close attention to the error message generated and try to correct the problem.
 +
 
 +
===Step No. 3===
 +
 
 +
Now that we have a program that will read in input until the user enters "cesi", we need to write the code that looks at what the user has entered.  We need to define some rules so that we can determine what class the input will be classified as.
 +
 
 +
We know from the problem specs that a word is classified by looking at the last character or the last two characters.  This means that we need a way to grab the last character and the last two characters of the input from the user.  Once we have the last character(s) we then will need to compare them to some test condition to determine what the word will be classified as.  To do this we will make use of the following String methods:
 +
 
 +
*.length()
 +
*.charAt()
 +
 
 +
====Usage:====
 +
 
 +
The .length() method will return the length of a string.  For example, if we have a variable called word which contains "cat", if we call word.length(), the number 3 will be returned.
 +
 
 +
The .charAt() method will return the character at a given location.  For example, if we again use the variable word which contains "cat" and call word.charAt(0), the character 'c' will be returned.  It is important to note that the indexing of the string starts at 0 and NOT 1. This means that word.charAt(1) will return 'a'.
 +
 
 +
Let's begin by declaring some variables that will make it easier to get the last and last two characters of a word that has been captured.  We will also want to define a variable to hold the length of a word entered.
 +
 
 
<pre>
 
<pre>
total = total + digit + 6;
+
 
</pre>
+
wordLength = word.length();
This error is known as a run time error. A run time error does not cause a compilation error, but it causes the program to produce incorrect results. In the explaination of the [[Case Study I#ISBN Check Digit Overview|ISBN check digit]], the sixth ISBN number should be multiplied by six, not added. This error is fixed by changing the second [[Arithmetic Operators|addition]] operation to a [[Arithmetic Operators|multiplication]] operation.
+
lastChar = word.charAt(wordLength-1);
<pre>
+
secondLastChar = word.charAt(wordLength-2);
total = total + digit * 6;
+
 
 
</pre>
 
</pre>
  
===Error Six===
+
Next, let's setup a rough framework of how we will classify a word.  To do this we will be using if-else Statements.  Please see the section on [http://wiki1010.cs.umanitoba.ca/mediawiki/index.php/The_If-Else_Statement if-else statements] to familiarize yourself with their workings.
 +
 
 +
====Syntax:====
 +
 
 +
In Java, the general form of an if-else statement is:
 +
 
 
<pre>
 
<pre>
digit = (isbn / 10);
+
 
</pre>
+
if (condition)
Just like [[#Error Five|error five]], the above [[Your First Java Program#Statements|statement]] causes a run time error. To isolate the last digit in the ISBN number, the ISBN must have the [[Arithmetic Operators|modulus operator]] applied, not the [[Arithmetic Operators|division operator]]. The above statement is fixed by replacing the [[Arithmetic Operators|division operator]] with the [[Arithmetic Operators|modulus operator]].
+
{
<pre>
+
    code to execute if condition == true
digit = (isbn % 10);
+
}
 +
 
 +
else
 +
{
 +
    code to execute if condition == false
 +
}
 +
 
 +
 
 
</pre>
 
</pre>
  
===Error Seven===
+
The framework that we will use to classify the words entered will be based on the table given in the problem section of this document.
 +
We will first look at the last letter of the word then we will move on to the last two letters.  The code for this will be as follows:
 +
 
 
<pre>
 
<pre>
digit = (isbn * 10);
+
 
</pre>
+
if (lastChar=='a')
The above [[Your First Java Program#Statements|statement]] is almost identical to [[#Error Six]]. The [[Arithmetic Operators|multiplication operator]] should be replaced with the [[Arithmetic Operators|modulus operator]].
+
{
<pre>
+
response =  " is an adjective.";
digit = (isbn % 10);
+
} else if (lastChar=='e')
 +
{
 +
response = " is an adverb.";
 +
} else if (lastChar=='o')
 +
{
 +
response = " is a singular noun.";
 +
} else if (lastChar=='j' && secondLastChar=='o')
 +
{
 +
response = " is a plural noun.";
 +
} else if (lastChar=='n')
 +
{
 +
if (secondLastChar=='o')
 +
{
 +
response = " is a singular noun.";
 +
} else if (secondLastChar=='j')
 +
{
 +
response = " is a plural noun.";
 +
}
 +
} else
 +
{
 +
response = " cannot be identified.";
 +
}
 +
 
 
</pre>
 
</pre>
  
===Error Eight===
+
''CHECK POINT:''
 +
 
 +
At this point your code can again be complied and run.  You will have an almost fully functional program now.  Your code at this point should look as follows:
 +
 
 
<pre>
 
<pre>
total = total + digit - 1;
+
 
</pre>
+
public class A2Q1
The error in the code above is [[#Error Five|error five]] almost identical to [[#Error Five]]. Replace the [[Arithmetic Operators|subtraction operator]] with the [[Arithmetic Operators|multiplication operator]] to remedy this error.
+
{
<pre>
+
public static void main(String[] args)
total = total + digit * 1;
+
{
 +
Scanner kbd = new Scanner(System.in);
 +
String word; // Esperanto word
 +
String response = "";  // response to be printed.
 +
int wordLength;
 +
char lastChar, secondLastChar; // the relevant characters.
 +
 
 +
// get first input.
 +
System.out.print("Enter a word in Esperanto: ");
 +
word = kbd.next();
 +
 
 +
// keep going until cesi is typed.
 +
while (!word.equalsIgnoreCase("cesi"))
 +
{
 +
// extract last and 2nd last characters from
 +
// the word.
 +
wordLength = word.length();
 +
lastChar = word.charAt(wordLength-1);
 +
secondLastChar = word.charAt(wordLength-2);
 +
 
 +
// classify the word according to these
 +
// characters.
 +
if (lastChar=='a')
 +
{
 +
response = " is an adjective.";
 +
} else if (lastChar=='e')
 +
{
 +
response = " is an adverb.";
 +
} else if (lastChar=='o')
 +
{
 +
response = " is a singular noun.";
 +
} else if (lastChar=='j' && secondLastChar=='o')
 +
{
 +
response = " is a plural noun.";
 +
} else if (lastChar=='n')
 +
{
 +
if (secondLastChar=='o')
 +
{
 +
response = " is a singular noun.";
 +
} else if (secondLastChar=='j')
 +
{
 +
response = " is a plural noun.";
 +
}
 +
} else
 +
{
 +
response = " cannot be identified.";
 +
}
 +
                        word = kbd.next();
 +
        }
 +
    }
 +
}
 +
 
 
</pre>
 
</pre>
  
==Add Code to Output Progress Reports as the Program Executes==
+
===Step No. 4===
To add progress reports to the program, three things need to be addressed:
+
<ul>
+
<li>Where to place the progress reports</li>
+
<li>What progress should be reported</li>
+
<li>Adding the code to report progress</li>
+
</ul>
+
By adding code to report on the status of the application, the user and yourself know what is happening behind the scenes when the program is executing. For a small application like this [[Case Study I|case study]] it may seem trivial. It is a good practice to get into as in larger programs consisting of many files each with many methods, it can be difficult to locate a run-time error in your code if the program does not explicitly say what it is currently doing.
+
  
===Location===
+
Now that our program reads in words until "cesi" is entered and it capable of classifying the words entered, we need to have some output printed to the screen.  The easiest way of doing this is through the use of print statements. A print statement simply allows us to print text to the screen.
By now the code file should be broken up into multiple code blocks, as done [[#Separate the Statements into Code Blocks|earlier in this solution]]. Each code block should represent a major code segment in the program. Each code block can be considered a potential point for a progress report. Read over the code and decide which are vital points in the execution of the program.
+
  
===Report Content===
+
A print statement in Java looks as follows:
The next step is to decide what should be outputted to describe the progress of the program. This output can be the current value of a [[Variables and Literals|variable]], an output statement saying that the program has reached a certain point in the code, or potentially a combination of both. A progress report should output data on the program that is relevant to its execution. For this [[Case Study I|case study]], each calculation performed on the ISBN is vital to determining the check digit, therefore a progress report should output the value of each calculation.
+
  
===Adding Output Code===
 
The best way to add output to the program is by adding [[Output using System.out|System.out]] statements to the appropriate code blocks. When adding the code, make sure the message that will be outputted is unique in comparison to the other progress report [[Your First Java Program#Statements|statements]]. Each statement should be unique as they are meant to identify the section of code being executed. If the statements are not unique, then there will be no way of telling which progress report has been outputted. Here is an example of the code before adding a [[Output using System.out|System.out]] statement.
 
 
<pre>
 
<pre>
//isolate last digit and multiply by 9
+
 
digit = (isbn % 10);
+
System.out.println("This is an example print statement")
total = digit * 9;
+
 
isbn = isbn / 10;
+
 
</pre>
 
</pre>
After the output [[Your First Java Program#Statements|statement]] is added, the code will look like the following:
+
 
 +
The above code will print to the screen: "This is an example print statement".
 +
 
 +
For our program we want to print out what we have learned about the word entered.  Let's print out the word entered followed by what we learned about the word.  For example, is it an adjective, adverb, etc... Let's add the following lines of code:  
 +
 
 
<pre>
 
<pre>
//isolate last digit and multiply by 9
+
 
digit = (isbn % 10);
+
// print message and get next input
total = digit * 9;
+
System.out.println(word + response);
isbn = isbn / 10;
+
System.out.print("Enter a word in Esperanto: ");
System.out.println (digit + " * " + 9 + " for a running total of " + total);
+
 
 
</pre>
 
</pre>
When the program is executing, the following output will appear in the progress window. The ISBN number used as input for the example below is 1-2345-6789.
 
<pre>
 
9 * 9 for a running total of 81
 
</pre>
 
Now the you will know what part of the code is being executed along with the status of the current calculation.
 
  
Remember that this is not the only "correct" progress report. There can be many different progress reports based on how the vital points of the program were interpreted. Although, in this [[Case Study I|case study]] the calculations are exceptionally important points to the correct execution of the program.
+
===Step No. 5===
  
|SolutionCode=
+
Finally let's put the final touches on our program. We need to add our name to the program and we should also add a line that gets executed on a successful program run. Adding this line will allow us and others to know our program has successfully run and completed. Here is what we will add:
import javax.swing.*;
+
import java.util.Date;
+
  
/**
+
<pre>
* calculate a check digit for ISBNs
+
*
+
* @author:    1010 Instructors
+
* @version:    2007-September
+
*/
+
  
public class CaseStudy1_ISBN_Solution
+
System.out.println("Programmed by [your name here].");
{
+
System.out.println("End of processing.");
    /**
+
    * PURPOSE: inputs a 9-digit ISBN, calculates the check digit and outputs a 10-digit ISBN
+
    */
+
    public static void main (String [] args)  
+
    {
+
  
        //variables declared here
+
</pre>
        String temp;        //temporary input string
+
        int isbn;            //9-digit ISBN
+
        int digit;          //isolated ISBN digit
+
        int total;          //total of isbn number when each digit is multiplied by check value
+
        int checkDigit;      //value of total%11(as per ISBN standard)
+
  
        //get input
+
===COMPLETE!===
        temp = JOptionPane.showInputDialog
+
        ("Enter the first 9 digits of a 10-digit ISBN number.");
+
        isbn = Integer.parseInt(temp);
+
  
        //confirm input
+
Congratulations!  You have now finished your Esperanto program. You can now compile and run your program.  You can also click the Solution button below to see a full solution.
        System.out.println ("You have entered " + temp + ".\n\nThe weighted value of the ISBN is:");
+
  
        //isolate last digit and multiply by 9
 
        digit = (isbn % 10);
 
        total = digit * 9;
 
        isbn = isbn / 10;
 
        System.out.println (digit + " * " + 9 + " for a running total of " + total);
 
  
        //isolate next digit and multiply by 8
+
|SolutionCode=
        digit = (isbn % 10);
+
        total = total + digit * 8;
+
        isbn = isbn / 10;
+
        System.out.println (digit + " * " + 8 + " for a running total of " + total);
+
  
        //isolate next digit and multiply by 7
+
import java.util.Scanner;
        digit = (isbn % 10);
+
 
        total = total + digit * 7;
+
/**
        isbn = isbn / 10;
+
* A2Q1
        System.out.println (digit + " * " + 7 + " for a running total of " + total);
+
*
 +
* COMP 010 Section A00
 +
* INSTRUCTOR
 +
* ASSIGNMENT 2, Question 1
 +
* @author 1010
 +
* @version 2010-Oct-18
 +
*
 +
* PURPOSE: a part-of-speech classifier for Esperanto.
 +
*/
 +
public class A2Q1
 +
{
 +
public static void main(String[] args)
 +
{
 +
Scanner kbd = new Scanner(System.in);
 +
String word; // Esperanto word
 +
String response = "";  // response to be printed.
 +
int wordLength;
 +
char lastChar, secondLastChar; // the relevant characters.
  
        //isolate next digit and multiply by 6
+
// get first input.
        digit = (isbn % 10);
+
System.out.print("Enter a word in Esperanto: ");
        total = total + digit * 6;
+
word = kbd.next();
        isbn = isbn / 10;
+
        System.out.println (digit + " * " + 6 + " for a running total of " + total);
+
  
        //isolate next digit and multiply by 5
+
// keep going until cesi is typed.
        digit = (isbn % 10);
+
while (!word.equalsIgnoreCase("cesi"))
        total = total + digit * 5;
+
{
        isbn = isbn / 10;
+
// extract last and 2nd last characters from
        System.out.println (digit + " * " + 5 + " for a running total of " + total);
+
// the word.
 +
wordLength = word.length();
 +
lastChar = word.charAt(wordLength-1);
 +
secondLastChar = word.charAt(wordLength-2);
  
        //isolate next digit and multiply by 4
+
// classify the word according to these
        digit = (isbn % 10);
+
// characters.
        total = total + digit * 4;
+
if (lastChar=='a')
        isbn = isbn / 10;
+
{
        System.out.println (digit + " * " + 4 + " for a running total of " + total);
+
response = " is an adjective.";
 +
} else if (lastChar=='e')
 +
{
 +
response = " is an adverb.";
 +
} else if (lastChar=='o')
 +
{
 +
response = " is a singular noun.";
 +
} else if (lastChar=='j' && secondLastChar=='o')
 +
{
 +
response = " is a plural noun.";
 +
} else if (lastChar=='n')
 +
{
 +
if (secondLastChar=='o')
 +
{
 +
response = " is a singular noun.";
 +
} else if (secondLastChar=='j')
 +
{
 +
response = " is a plural noun.";
 +
}
 +
} else
 +
{
 +
response = " cannot be identified.";
 +
}
  
        //isolate next digit and multiply by 3
+
// print message and get next input
        digit = (isbn % 10);
+
System.out.println(word + response);
        total = total + digit * 3;
+
System.out.print("Enter a word in Esperanto: ");
        isbn = isbn / 10;
+
word = kbd.next();
        System.out.println (digit + " * " + 3 + " for a running total of " + total);
+
}
 +
System.out.println("Programmed by [your name here].");
 +
System.out.println("End of processing.");
 +
}
  
        //isolate next digit and multiply by 2
+
}
        digit = (isbn % 10);
+
        total = total + digit * 2;
+
        isbn = isbn / 10;
+
        System.out.println (digit + " * " + 2 + " for a running total of " + total);
+
  
        //isolate next digit and multiply by 1
 
        digit = (isbn % 10);
 
        total = total + digit * 1;
 
        isbn = isbn / 10;
 
        System.out.println (digit + " * " + 1 + " for a running total of " + total);
 
  
        //calculate check digit
 
        checkDigit = total % 11;
 
  
        //output weighted total and check digit
 
        System.out.println ("The weighted total is: " + total +
 
                            "\nThe check digit is : " + checkDigit +
 
                            "\n\nThe 10-digit ISBN is: " + temp + checkDigit);
 
  
        System.out.println("\nProgrammed by COMP 1010 Instructors");
 
        System.out.println("Date: " + new Date());
 
        System.out.println ("*** End of Processing ***");
 
  
    }//end main
+
|SideSectionTitle=Esperanto
}//end class
+
|SideSectionTitle=Funky Books
+
 
|SideSection=
 
|SideSection=
[[Image:Wiki_start01.jpg|center]]<BR>
+
[[Image:Esperanto_casestudy.jpg|center]]<BR>
  
 
}}
 
}}

Latest revision as of 11:18, 5 April 2011

Back to the Case Studies homepage

Problem

Esperanto is a language invented in the 1880s by L. L. Zamenhof. It was invented to "create an easy-to-learn and politically neutral language that would serve as a universal second language to foster peace and international understanding." One of the benefits of designing your own language is that you can impose strict rules on the language. In this question, you will use the rules of Esperanto to identify the parts of speech of different words. The rules for identifying parts of speech in Esperanto are:


If the word ends in .. it is a(n)...
aadjective
o or onsingular noun
oj or ojnplural noun
eadverb


This means there are no exceptions in Esperanto, like how in English the plural of goose is geese and while you usually add 'ly' to the end of an adjective to make it an adverb, 'goodly' isn't an adverb.

Write a program that accepts words in Esperanto, and identifies whether each is an adjective, singular noun, plural noun or adverb.

Input:

Use Scanner to accept input in this question. Prompt the user to input a word. If the user types in "cesi" ("quit" in Esperanto), the program should quit. Otherwise, it should accept the input and process it as a word in Esperanto.

After processing the word, the user should be prompted to enter another word. Assume the user inputs the words entirely in lowercase and that all words are at least three letters long.

Calculate and Output:

Use System.out. for all output. Use the charAt() and length() methods to find the last (one or possibly two) characters and determine which part of speech (adverb, singular noun, plural noun or adverb) the word is. If the word is in none of the four categories, print out an error message telling the user that the part of speech cannot be identified. An execution of your program would look like this:

Enter a word in Esperanto: komputilo
komputilo is a singular noun.

Enter a word in Esperanto: sciencon
sciencon is a singular noun.

Enter a word in Esperanto: cesi

Programmed by [your name here].
End of processing.
 

Esperanto

Esperanto casestudy.jpg

Solution

Remember to abide by the COMP 1010 coding standards while writing the code.

Organize the Code

When you begin to write a solution, the best way to approach this is to divide the answer into sections of code. You want to break down the problem into smaller sections or ideas that can be solved as steps. Begin by creating a new blank solution file using your standard setup. See below:


public class A2Q1 
{
	public static void main(String[] args) 
	{
	}
}

Next begin to write the code for the sections you defined. For this solution the steps we will use are:

  • Capture the user's input from the keyboard
  • Get the program to loop until some end condition is met - in this case when "cesi" is entered
  • Write the compare code to determine what was entered - ie. adjective, adverb, etc
  • Write the code to display the output

Step No. 1

Begin by writing the code to get the user's input from the keyboard. As per the assignment specifications, we will be using Scanner to capture what the user inputs via the keyboard. In order for you to use scanner, you must first include the "java.util.Scanner" library. To include this library add the below import statement as first line of your solution file.


import java.util.Scanner;

Scanner does exactly what you think it does. It scans the keybaord logging input until it encounters a new line character. When a new line character is encountered, the Scanner will stop scanning and the keys pressed are now stored. An example of a new line character is when the "Enter" key is pressed.

Usage:

To use Scanner, as noted above you must first have imported the java.util.Scanner library. Next, you must make a new instance of Scanner. Do this by declaring a new instance and instantiating it. You must also allocate space to store what the Scanner captures. Do this by assigning Scanner's output to a local variable. See below:


Scanner kbd = new Scanner(System.in);		//create a new instance of Scanner
String word; 					// Esperanto word - holds the User's input


System.out.print("Enter a word in Esperanto: ");//print a message to let the User know what they should do
word = kbd.next();				// get input from User

			

CHECK POINT:

At this point you can now compile and run the code you have. Ensure that your program does compile without any errors. If your code does not compile, look closely at the error message generated and try to correct the problem. If you successfully compile your code, try running it. Running your code should prompt you for input and you should be able to enter it. At this point, you will only be prompted for input once.

Step No. 2

At this point we have code that can read in input from a user. However, the current code will only read input in once and then end. We now want to modify this code so that it will read in input until some "end" condition is met. For this problem, our end condition will be when the word "cesi" is entered. Since we know what our end condition is we can test for it. The best way to carry out this test is through the use of a while loop. Please see the section on while loops to familiarize yourself with their workings.

Syntax:

In Java, the general form of a while loop is:


while(test_condition)		//this is where we test for the end condition
{
   ...
   statements;
   ...
}


For our program we will insert a while loop statement that looks as follows:


while (!word.equalsIgnoreCase("cesi")) 
{
	...statements....
}

The way that this statement will be evaluated is as follows:

  • word has already been assigned the input from the user (from the previous step)
  • the while loop will take word and apply the method "equalsIgnoreCase"
  • if the result of this matches the expression "cesi" then the loop will exit
  • if the result does not match the expression "cesi" the loop will continue to run


IMPORTANT NOTE:

Note the usage of equalsIgnoreCase() here. The reason for this is to catch input that matches "cesi" in both upper and lower case. We are not concerned with the case of the letters, just that "cesi" is entered. If you choose to use equals() then "cesi" would have to be entered exactly. "CESI" wound not qualify and the loop would continue to run.


CHECK POINT:

At this point your code should look as follows:


public class A2Q1 
{

	public static void main(String[] args) 
	{
	
		Scanner kbd = new Scanner(System.in);
		String word; // Esperanto word


		System.out.print("Enter a word in Esperanto: ");
		word = kbd.next();


		// keep going until cesi is typed.
		while (!word.equalsIgnoreCase("cesi")) 
		{
                    word = kbd.next();
		}

	}

}


Again compile and run your code. Your code should continue to prompt you for input until "cesi" is entered. If you are not successful in compiling your code, pay close attention to the error message generated and try to correct the problem.

Step No. 3

Now that we have a program that will read in input until the user enters "cesi", we need to write the code that looks at what the user has entered. We need to define some rules so that we can determine what class the input will be classified as.

We know from the problem specs that a word is classified by looking at the last character or the last two characters. This means that we need a way to grab the last character and the last two characters of the input from the user. Once we have the last character(s) we then will need to compare them to some test condition to determine what the word will be classified as. To do this we will make use of the following String methods:

  • .length()
  • .charAt()

Usage:

The .length() method will return the length of a string. For example, if we have a variable called word which contains "cat", if we call word.length(), the number 3 will be returned.

The .charAt() method will return the character at a given location. For example, if we again use the variable word which contains "cat" and call word.charAt(0), the character 'c' will be returned. It is important to note that the indexing of the string starts at 0 and NOT 1. This means that word.charAt(1) will return 'a'.

Let's begin by declaring some variables that will make it easier to get the last and last two characters of a word that has been captured. We will also want to define a variable to hold the length of a word entered.


wordLength = word.length();
lastChar = word.charAt(wordLength-1);
secondLastChar = word.charAt(wordLength-2);

Next, let's setup a rough framework of how we will classify a word. To do this we will be using if-else Statements. Please see the section on if-else statements to familiarize yourself with their workings.

Syntax:

In Java, the general form of an if-else statement is:


if (condition)
{
    code to execute if condition == true
}

else
{
    code to execute if condition == false
}


The framework that we will use to classify the words entered will be based on the table given in the problem section of this document. We will first look at the last letter of the word then we will move on to the last two letters. The code for this will be as follows:


if (lastChar=='a')
{
	response =  " is an adjective.";
} else if (lastChar=='e')
{
	response = " is an adverb.";
} else if (lastChar=='o')
{
	response = " is a singular noun.";
} else if (lastChar=='j' && secondLastChar=='o')
{
	response = " is a plural noun.";
} else if (lastChar=='n')
{
if (secondLastChar=='o')
{
	response = " is a singular noun.";
} else if (secondLastChar=='j')
{
	response = " is a plural noun.";
}
} else
{
	response = " cannot be identified.";
}

CHECK POINT:

At this point your code can again be complied and run. You will have an almost fully functional program now. Your code at this point should look as follows:


public class A2Q1
{
	public static void main(String[] args)
	{
		Scanner kbd = new Scanner(System.in);
		String word; 			// Esperanto word
		String response = "";  // response to be printed.
		int wordLength;
		char lastChar, secondLastChar; // the relevant characters.

		// get first input.
		System.out.print("Enter a word in Esperanto: ");
		word = kbd.next();

		// keep going until cesi is typed.
		while (!word.equalsIgnoreCase("cesi"))
		{
			// extract last and 2nd last characters from
			// the word.
			wordLength = word.length();
			lastChar = word.charAt(wordLength-1);
			secondLastChar = word.charAt(wordLength-2);

			// classify the word according to these
			// characters.
			if (lastChar=='a')
			{
				response =  " is an adjective.";
			} else if (lastChar=='e')
			{
				response = " is an adverb.";
			} else if (lastChar=='o')
			{
				response = " is a singular noun.";
			} else if (lastChar=='j' && secondLastChar=='o')
			{
				response = " is a plural noun.";
			} else if (lastChar=='n')
			{
			if (secondLastChar=='o')
			{
				response = " is a singular noun.";
			} else if (secondLastChar=='j')
			{
				response = " is a plural noun.";
			}
			} else
			{
				response = " cannot be identified.";
			}
                        word = kbd.next();
         }
    }
}

Step No. 4

Now that our program reads in words until "cesi" is entered and it capable of classifying the words entered, we need to have some output printed to the screen. The easiest way of doing this is through the use of print statements. A print statement simply allows us to print text to the screen.

A print statement in Java looks as follows:


System.out.println("This is an example print statement")

The above code will print to the screen: "This is an example print statement".

For our program we want to print out what we have learned about the word entered. Let's print out the word entered followed by what we learned about the word. For example, is it an adjective, adverb, etc... Let's add the following lines of code:


// print message and get next input
System.out.println(word + response);
System.out.print("Enter a word in Esperanto: ");

Step No. 5

Finally let's put the final touches on our program. We need to add our name to the program and we should also add a line that gets executed on a successful program run. Adding this line will allow us and others to know our program has successfully run and completed. Here is what we will add:


System.out.println("Programmed by [your name here].");
System.out.println("End of processing.");

COMPLETE!

Congratulations! You have now finished your Esperanto program. You can now compile and run your program. You can also click the Solution button below to see a full solution.

Code

Solution Code

Back to the Case Studies homepage