Questions
Consider the relational schemas given below and the respective sets of functional dependencies valid in the...

Consider the relational schemas given below and the respective sets of functional dependencies valid in the schemas. For each one of the relational schemas identify its highest normal form. Remember that the identification of a normal form requires analysis of the valid functional dependencies and the minimal keys. Provide justification of each answer. A solution with no comprehensive justification scores no marks.

(iv) When a staff is required to undertake an inspection of properties, the staff is allocated a company car for the day. A staff may inspect several properties on a given date, and a property is only inspected once on a given date. These information of the inspection are stored in the following relational table:
PropertyInspection(PropertyNum, IDate, ITime, Comments, StaffNum, CarRegNum)

(vi) Each student is assigned with a counselor who will act as an advisor to the students. The student is given the counselor email address so that the student can contact the counselor for advice. The information on the student and counselor are stored in the following relational table.
STUDENTCOUNSELOR (StdNum, StdName, CounselorName, CounselorEmail)

In: Computer Science

Write a function in Python to take in a piece of sample text via a long...

Write a function in Python to take in a piece of sample text via a long string (you pick the string) and to output a dictionary with each word as a key and it’s frequency (the number of times it occurred in the original string) as the value. Show an example of your function in use. Be sure to strip out any punctuation.

In: Computer Science

Write a Java program to encrypt and decrypt a phrase using two similar approaches, each insecure...

Write a Java program to encrypt and decrypt a phrase using two similar approaches, each insecure by modern standards.

The first approach is called the Caesar Cipher, and is a simple “substitution cipher” where characters in a message are replaced by a substitute character.

The second approach, due to Giovan Battista Bellaso (b 1505, d 1581), uses a key word, where each character in the word specifies the offset for the corresponding character in the message, with the key word wrapping around as needed.


⦁   Using loops
⦁   String and character processing
⦁   ASCII codes


⦁   Data Manager class – CryptoManager.java
⦁   Implement each of the methods specified in this file. This version as provided will print error messages in the console, because they are just the skeletons.
⦁   Each of the methods are static, so there is no need to create an instance of the Data Manager.
⦁   Document each of your methods with a simple description and document the class with a simple description and your name using in-line comments (//…). (Just a short sentence fragment will suffice for each documentation string.)
⦁   The methods are described below.
⦁   public static boolean stringInBounds (String plainText);
   This method determines if a string is within the allowable bounds of ASCII codes according to the LOWER_BOUND and UPPER_BOUND characters. The parameter plainText is the string to be encrypted. The method returns true if all characters are within the allowable bounds, false if any character is outside.
⦁   public static String encryptCaesar(String plainText, int key);
This method encrypts a string according to the Caesar Cipher. The integer key specifies an offset and each character in plainText is replaced by the character the specified distance away from it. The parameter plainText is an uppercase string to be encrypted. The parameter key is an integer that specifies the offset of each character. The method returns the encrypted string.
⦁   public static String decryptCaesar(String encryptedText, int key);
This method decrypts a string according to the Caesar Cipher. The integer key specifies an offset and each character in encryptedText is replaced by the character "offset" characters before it. This is the inverse of the encryptCaesar method. The parameter encryptedText is the encrypted string to be decrypted, and key is the integer used to encrypt the original text. The method returns the original plain text string.
⦁   public static String encryptBellaso(String plainText, String bellasoStr);
This method encrypts a string according to the Bellaso Cipher. Each character in plainText is offset according to the ASCII value of the corresponding character in bellasoStr, which is repeated to correspond to the length of plaintext. The method returns the encrypted string.
⦁   public static String decryptBellaso(String encryptedText, String bellasoStr);
This method decrypts a string according to the Bellaso Cipher. Each character in encryptedText is replaced by the character corresponding to the character in bellasoStr, which is repeated to correspond to the length of plainText. This is the inverse of the encryptBellaso method. The parameter encryptedText is the encrypted string to be decrypted, and bellasoStr is the string used to encrypt the original text. The method returns the original plain text string.
⦁   Add additional methods if you wish to make your logic easier to follow.
⦁  
⦁   GUI Driver class – (provided)
⦁   A Graphical User Interface (GUI) is provided. Be sure that the GUI will compile and run with your methods. The GUI will not compile if your method headers in CryptoManager.java are not exactly in the format specified. When you first run the application, your methods will all throw exceptions, which will be caught by the GUI and printed out in the console.
⦁   Do not modify the GUI.
⦁   The GUI takes care of capitalizing your input strings.
⦁  
⦁   JUnit Test/Test Driver
⦁   Once your methods are implemented, run the test driver. Ensure that the driver file results in the following output, as shown in RED (of course the output will not be in red when you run the test driver):
⦁   "THIS TEST SHOULD SUCCEED" Is it in bounds? true
⦁   "THIS TEST THAT SHOULD FAIL BECAUSE { IS OUTSIDE THE RANGE" Is it in bounds? false
⦁   "This test should fail because of lowercase letters" Is it in bounds? false
⦁   Caesar cipher of "THIS IS ANOTHER TEST" should return "WKLV#LV#DQRWKHU#WHVW": WKLV#LV#DQRWKHU#WHVW
⦁   Bellaso cipher of "THIS IS ANOTHER TEST" should return "WU\VR9F#N!RF88U-'HED": WU\VR9F#N!RF88U-'HED
⦁   Caesar decryption of "WKLV#LV#DQRWKHU#WHVW" should return "THIS IS ANOTHER TEST": THIS IS ANOTHER TEST
⦁   Bellaso decryption of "WU\VR9F#N!RF88U-'HED" should return "THIS IS ANOTHER TEST": THIS IS ANOTHER TEST
⦁   Run the JUnit test file (provided). Ensure that the JUnit tests all succeed.
⦁   Include CryptoGFATest.java and CryptoManagerTest.java with the rest of your submission.

The first approach is called the Caesar Cipher, and is a simple “substitution cipher” where characters in a message are replaced by a substitute character. The substitution is done according to an integer key which specifies the offset of the substituting characters. For example, the string ABC with a key of 3 would be replaced by DEF.
If the key is greater than the range of characters we want to consider, we “wrap around” by subtracting the range from the key until the key is within the desired range. For example, if we have a range from space (‘ ‘) to ‘_’ (i.e., ASCII 32 to ASCII 95), and the key is 120, we note that 120 is outside the range. So we subtract 95-32+1=64 from 120, giving 56, which in ASCII is the character ‘8’. If the key is even higher, we can subtract the range from the key over and over until the key is within the desired range.
Since our specified range does not include lower-case letters, the GUI (provided) will change strings to upper case. You can find the ASCII table at http://www.asciitable.com/, or many other places on the Internet.
The second approach, due to Giovan Battista Bellaso (b 1505, d 1581), uses a key word, where each character in the word specifies the offset for the corresponding character in the message, with the key word wrapping around as needed.
So for the string ABCDEFG and the key word CMSC, the key word is first extended to the length of the string, i.e., CMSCCMS. Then A is replaced by ‘A’ offset by ’C’, i.e., ASCII 65+67=132. The range of the characters is also specified, and again we’ll say ‘ ‘ to ‘_’ (i.e., ASCII 32 to ASCII 95). The range is then 95-32+1=64. In our example, the offset is “wrapped” by reducing 132 by the range until it is the allowable range. 132 is adjusted to 132-64=68, or character ‘D’ in the encrypted phase. Then the same logic is applied to the second letter of the plain text ‘B’ shifted by the second letter of the key word ‘M’. This results in the character ‘O’ as the second letter in the encrypted phase, and so on. In each approach, if the resulting integer is greater than 95 (the top of our range), the integer is “wrapped around” so that it stays within the specified range. The result is “DOVGHSZ”.
Your program will implement several methods that are specified in the file “CryptoManager.java”. A Graphical User Interface is provided, as well as a test file, that you should use to make sure your methods work correctly. Be sure to follow the naming exactly, as the tests will not work otherwise.
There are several features of Java that we have not yet covered in class. Just follow the syntax specified in this document and in the file CryptoManager.java. First, the required methods are “static”, which just means that they are available from the class even if an instance has not been created. To call a static method, for example, “public static void myMethod();” the syntax is CryptoManager.myMethod();. Another feature that may be useful in this project is the method charAt(i) on a string, which returns a character at position i of a string (zero-based). So “thisString”.charAt(3); would return the char ‘s’.
Notes:
⦁   Proper naming conventions: All constants, except 0 and 1, should be named. Constant names should be all upper-case, variable names should begin in lower case, but subsequent words should be in title case. Variable and method names should be descriptive of the role of the variable or method. Single letter names should be avoided.
Indentation: It must be consistent throughout the program and must reflect the control structure

In: Computer Science

Convert Octal A09sixteen

Convert Octal A09sixteen

In: Computer Science

1- Write a Java program called ArabicMonth that randomly generates an integer between 1 and 12...

1- Write a Java program called ArabicMonth that randomly generates an integer between 1 and 12 and displays the month name Jan, Feb, …, December for
the number 1, 2, …, 12, accordingly..

Sample Run:
9 Oct











2- Write a program that prompts the user to enter the exchange rate from currency in U.S. dollars to Saudi Riyals. Prompt the user to enter 0 to convert from U.S. dollars to Saudi Riyals and 1 to convert from Saudi Riyal and U.S. dollars. Prompt the user to enter the amount in U.S. dollars or Saudi Riyal to convert it to Saudi Riyal or U.S. dollars, respectively.

Here are the sample runs:
Enter the exchange rate from dollars to SR: 3.75
Enter 0 to convert dollars to SR and 1 vice versa: 0
Enter the dollar amount: 100
$100.0 is 375.0 SR

In: Computer Science

Convert to binary 73

Convert to binary 73

In: Computer Science

THIS IS FOR DEVC++. I use the 5.11 version Write a program to take input of...

THIS IS FOR DEVC++. I use the 5.11 version

Write a program to take input of scores for Chemistry, Biology and English for a student and display the average with 2 decimal places if all of the three scores are in the range between 1 and 100 inclusive. Program should also display the course name for which scores are entered out of range telling Average couldn't be calculated.

Following is a sample run:

Enter scores for Chemistry, Biology and English between 1 and 100:
45
89
96
Avg score is 76.67

Following is another sample run:

Enter scores for Chemistry, Biology and English between 1 and 100:
900
78
89
Average cannot be calculated because Chemistry Scores were not in range.

Following is another sample run:

Enter scores for Chemistry, Biology and English between 1 and 100:
89
767
8787
Average cannot be calculated because Biology Scores were not in range.
Average cannot be calculated because English Scores were not in range.

Following is another sample run:

Enter scores for Chemistry, Biology and English between 1 and 100:
87
90
-1
Average cannot be calculated because English Scores were not in range.

In: Computer Science

Convert "hello world" into hex "hello world" in hex = 68656c6c6f20776f726c64 encrypt the above binary content...

Convert "hello world" into hex "hello world" in hex = 68656c6c6f20776f726c64

encrypt the above binary content with a 4 bit block cipher whose codebook consists of 6, 0, 13, 4, 3, 1, 14, 8, 7, 12, 9, 15, 5, 2, 11, 10 (The codebook is simply the output blocks in the order of the integers corresponding to the 16 possible input blocks).

What will the encrypted output be for this text?

In: Computer Science

Write a function in Python which removes a set of common words from a long piece...

  1. Write a function in Python which removes a set of common words from a long piece of text. Be sure to strip out any punctuation. The common words to be removed are:

a, an, as, at, by, for, in, is, it, of, that, this, to, was, will, the

These are typical words that are considered to have low semantic value.

Process each paragraph provided below individually. Your end result for each paragraph should be a string or list containing the processed paragraph with the common words and punctuation removed. It is not required to put the text samples into a file (you can simply copy and paste into a string variable inside your Python script).

For the text samples to process, use the following (taken from the official Python tutorial):

If you do much work on computers, eventually you find that there’s some task you’d like to automate. For example, you may wish to perform a search-and-replace over a large number of text files, or rename and rearrange a bunch of photo files in a complicated way. Perhaps you’d like to write a small custom database, or a specialized GUI application, or a simple game.

If you’re a professional software developer, you may have to work with several C/C++/Java libraries but find the usual write/compile/test/re-compile cycle is too slow. Perhaps you’re writing a test suite for such a library and find writing the testing code a tedious task. Or maybe you’ve written a program that could use an extension language, and you don’t want to design and implement a whole new language for your application.

In: Computer Science

Could I please get explainations and working out as to how to get to the answers....

Could I please get explainations and working out as to how to get to the answers.

Note that  is where part of the answer goes.

1.

Consider the following ArrayList list:

ArrayList list = new ArrayList(Arrays.asList(10,70,20,90));

//list = [10, 70, 20, 90]

Complete the following statements so that list contains the items [50, 70, 20]

Do NOT include spaces in your answers.

list.remove(  ); list.  (  , 50);

2.

Assume there exists an ArrayList list that contains the items

[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, ....]

(So, we know the first item is 10, second item is 20, but we don't know how many items it contains. You may assume it contains at least 10 items)

Complete the following code that displays every other item starting at the fifth item (so, the pattern 50 70 90 ...)

Do NOT include spaces in your answer.

for(int i=  ; i <  ;  ) {

System.out.println(  +" ");

}

3.

Complete the following function that returns the number of negative (less than 0) items in ArrayList list.

public static int countNegatives(ArrayList list) {

int result =  ;

for(int i=0; i < list.size(); i++) {

if(    ) {  ; }

} return result; }

In: Computer Science

You will be creating a JUnit Test Class for Gradebook.java, (listing 1.1) and you can download...

You will be creating a JUnit Test Class for Gradebook.java, (listing 1.1) and you can download it from blackboard.

Gradebook has two attributes: an array of int called scores to hold scores and scoreSize that indicates how many scores are currently held in the array. This field is initially set to 0.

Task #1:
Add a getScoreSize() method to the Gradebook class which returns scoresSize;
Add a toString() method to the Gradebook class that returns a string with each score in scores field of the Gradebook separated by a space.

.
Task #2: Create the Test Class GradebookTester by right clicking on the GradeBook.java, select New, Junit Test Case.
Using the wizard:
Select the setUp and tearDown method check boxes and click Next.
Select all of the methods of Gradebook, except for the constructor to create tests for. Then click finish.

.
Task #3:
In the setUp method of GradebookTester, create at least two objects of Gradebook to hold 5 scores. Then call the addScore method for each of the Gradebook objects at least twice (but no more than 5 times) to add some random scores of your choice to the GradeBook objects
In the teardown method of GradebookTester, set the two objects of Gradebook to null.

Task #4: Create test for the methods of Gradebook:
addScore
Use the toString method to compare the contents of what is in the scores array vs. what is expected to be in the scores array assertTrue( . . .)
Compare the scoreSize to the expected number of scores entered, using assertEquals(. . .)
sum
Compare what is returned by sum() to the expected sum of the scores entered.
minimum
Compare what is returned by minimum() to the expected minimum of the scores entered.
finalScore
Compare what is returned by finalScore() to the expected finalScore of the scores entered. The finalScore is the sum of the scores, with the lowest score dropped if there are at least two scores, or 0 if there are no scores.

Task #5: Upload both files to GitHub in a directory named CMSC203_Lab6.


Example:

As a private attribute (member) of GradeBookTest:
   GradeBook g1;

In setup:
g1 = new GradeBook(5);
g1.addScore(50);
g1.addScore(75);

In teardown:
   g1 = null;

in testSum():
assertEquals(125, g1.sum(), .0001);

in testMinimum():
   assertEquals(50, g1.minimum(), .001);

in addScoreTest();
   assertTrue(g1.toString().equals(“50.0 75.0 ”);

Listing 1.1 – GradeBook.java

import java.util.ArrayList;

public class GradeBook
{
private double[] scores;
private int scoresSize;

/**
Constructs a gradebook with no scores and a given capacity.
@capacity the maximum number of scores in this gradebook
*/
public GradeBook(int capacity)
{
scores = new double[capacity];
scoresSize = 0;
}

/**
Adds a score to this gradebook.
@param score the score to add
@return true if the score was added, false if the gradebook is full
*/
public boolean addScore(double score)
{
if (scoresSize < scores.length)
{
scores[scoresSize] = score;
scoresSize++;
return true;
}
else
return false;
}

/**
Computes the sum of the scores in this gradebook.
@return the sum of the scores
*/
public double sum()
{
double total = 0;
for (int i = 0; i < scoresSize; i++)
{
total = total + scores[i];
}
return total;
}
  
/**
Gets the minimum score in this gradebook.
@return the minimum score, or 0 if there are no scores.
*/
public double minimum()
{
if (scoresSize == 0) return 0;
double smallest = scores[0];
for (int i = 1; i < scoresSize; i++)
{
if (scores[i] < smallest)
{
smallest = scores[i];
}
}
return smallest;
}

/**
Gets the final score for this gradebook.
@return the sum of the scores, with the lowest score dropped if
there are at least two scores, or 0 if there are no scores.
*/
public double finalScore()
{
if (scoresSize == 0)
return 0;
else if (scoresSize == 1)
return scores[0];
else
return sum() - minimum();
}
}

In: Computer Science

----------------------------------------------------------------------------------------------------------------IN PYTHON-----------------------------------------------------------------------------------------------------------------------------write a Q

----------------------------------------------------------------------------------------------------------------IN PYTHON-----------------------------------------------------------------------------------------------------------------------------write a Quiz Generator. This program is expected to generate questions for a student, record student answers, displays the answers correctly entered and reports the total time taken by the student to finish the quiz.
a) The program should initialize three variables, one called correct that starts with an int of 0, second called count that also starts with an int of 0 and third called totalquestions that starts with an int of 5 (Hint: Typecast all the initialized variables to int values). The variable correct stores the correct answers entered by the student, count variable counts the number of questions and totalquestions is a constant value for total number of questions that equals 5.


b) Using the python time library, start the timer for the student. Store the value in a variable startTime. (Hint: Use time() method). Display the message “The quiz has started” using a print statement.


c) Using randint() method, generate two single digit integers for each question and store them in num1 and num2 variables. (Hint: use while to loop through totalquestions, generating two random integers (between 0-9) for each question)


d) Ask the student to input the answer to "What is num1 ** num2?" using input() function and save this value in a variable answer. Grade the answer by comparing its value to the actual operation between the two numbers and display the correct answers if the answer entered is wrong. (Hint: The student must enter the answer for num1 raise to the power num2. Then, after grading, using print statements, display the message “You are correct!” for correct answers entered by the student or “You are wrong! Correct answer is…” for wrong answers entered by the student).

e) End the timer for the student. Store the value in a variable endTime. Use totalTime variable to store the total time taken by the student. (Hint: totalTime is the difference value of endTime and startTime).


f) Print the number of points received based on the number of answers correctly entered by the student (Hint: You can display something like this “The number of points received are 3 out of 5”). Also, print the total test time taken by the student in seconds.


g) Ask input from the user if he wants to retake the test or exit. Depending upon the option selected by the user, restart the program again or end it. You can ask the user for input "Do you want to retake the quiz? Type Y/N: ". If the user enters N or stop or exit, end the program using ‘break’. If the user types Y, restart the quiz again. (Hint: use infinite while loop to restart the quiz again).


h) Use the same variable names and print statement examples as given in the question.

In: Computer Science

1/ Suppose you are responsible for the IT infrastructure of an organization, which has about 15desktop...

1/ Suppose you are responsible for the IT infrastructure of an organization, which has about 15desktop computers. You are advised that automation for uniformity is a good solution. What does it mean by “automation for uniformity”? Why is it a good solution in principle? Will you implement a fully automatic system in this case of yours? Why or why not.

In: Computer Science

In Java please. I put down my code and what I was able to achieve so...

In Java please. I put down my code and what I was able to achieve so far:

public class Animal {

  private String gender; //stores the gender of the animal
   private String type; //stores the type of the animal(bear of fish)
   private int strength; //stores the strength of the animal

   public Animal() {
       gender = "none";
       type = "none";
       strength = 0;
   }
  
    public Animal (String g, String t, int s) {
       g = gender;
       t = type;
       s = strength;      
   }

   public boolean setGender() {
       Random ranGen = new Random();
      
       boolean g = ranGen.nextBoolean();

  
       if (g == true)
           gender = "Male";
       else
           gender = "Female";
       return g;
   }
  
   public String getGender() {
       return gender;
   }

   public boolean setType() {
       Random ranGen = new Random();
      
       boolean t = ranGen.nextBoolean();
      
       if (t == true)
           type = "Bear";
       else
           type = "Fish";
       return t;      
   }
  

   public String getType() {
       return type;
   }


   public void setStrength(int strength) {
       this.strength = strength;
   }


   public int getStrength() {
       return strength;
   }

  
   public boolean compareGender(Animal animal) {

       if(this.getGender().equals(animal.getGender()))
       {
           return true;
       }
       else {
           return false;

       }
   }

  
   public boolean compareType(Animal animal) {
  
       if(this.getClass().equals(animal.getClass())){
           return true;   
       }
       else{
           return false;

       }

   }


   public boolean compareStrength(Animal animal) {
  
       if(this.getStrength() == (animal.getStrength())){
           return true;   
       }
       else{
           return false;

       }
   }
  
   public void increaseStrength() {
  
       this.setStrength(this.getStrength() + 4);
   }
  

   public String toString() {
       String str = new String ("The animal:  " + type + " + gender + strength);
       return str;

   }

}

public class River {
   private Animal[] river;
   private int numAnimals;
      

   public River() throws NumberFormatException{
   numAnimals = 0;
   Random randNum = new Random();
   int num = randNum.nextInt(20);
   river = new Animal[num];
   while(numAnimals < river.length/2)
   {
       int place = randNum.nextInt(river.length);
       if(river[place] == null)
       {
           river[place] = new Animal();

numAnimals++;


       }
   }
  
   }
  
   public River(Animal[] size) throws NumberFormatException{
       setRiver(size);
      
   }
  

   public void setRiver(Animal[] s) throws NumberFormatException
   {
       river= s;
           if (s.length >= 10 && s.length <= 20)
               river = s;
           else
       throw new NumberFormatException("Invalid Number: number out of range");
   }
  

   public Animal[] getRiver() {
       return river;      
   }
  
   public void play() {
       Random randNum = new Random();
       int moviment;
       for(int i=0; i<river.length; i++) {
           if(river[i] != null) {
               moviment = randNum.nextInt();
               if(moviment == 1) {
                  
               }
              
           }
       }
  

So my problem is on the play method. I need to iterate through the array.

If I find an animal I need to randomly decide if the animal id going to move back, forward or stay in place.

If the animal is moving back I need to make sure that he is not at the beginning of the array.

If the animal is moving forward I need to make sure that he is not at the last position of the array.

If the animal stays in place nothing needs to be done.

If the animal moves back/forward the index position needs to be checked if to see if its empty.

If is empty the animal can just move there. If is not the animal type needs to be checked.

If they are of the same type its gender needs to be checked. Same gender produces a baby, different gender they fight and the weaker animal dies (meaning it will be erased from the array).

If the animals are from different types one of the animals is going to be eaten.

**I really do not know how to do this method, I tried to start but I do not know how to move forward, so I would really appreciate if you put comments through the code. Also, can you please check if the parameterized constructor is right?

Thank you so much
  

In: Computer Science

Java programmers!!!! Complete the definition of the Tavunu class according to the specifications below and the...

Java programmers!!!!

Complete the definition of the Tavunu class according to the specifications below and the JUnit4 test file given

Background

A tavunu is an imaginary Earth-dwelling being that looks a bit like a Patagonian Mara and lives in a non-gendered but hierarchical society. Most interactions among tavunu are negotiated with pava --- items of status used for bargaining. Pava is always traded whole; you can't trade half a pava.

public class Tavunu {

// See what to do

}

what to do

Develop some code

Complete the definition of the Tavunu class so it represents tavuni (that's plural for tavunu) according to the specifications below and the JUnit4 test file here( see below).

A Tavunu instance should have a name of the tuvunu, the amount of pava the tavunu holds, and their year of birth.

A Tavunu instance should also have the following methods:

  • setName(name): gives the tavunu a new name. All tavunu names begin with the letters 'T' or 'D'. If the desired new name does not meet this criterion, the method does not change the name and returns false. Otherwise it changes the tavunu's name and returns true.
  • getName(): returns the tavunu's name.
  • spendPava(amount): decreases the amount of pava held by the tavunu. If the amount is zero or less the method does not change the pava and returns false. Otherwise it subtracts the amount from the tavunu's pava and returns true.
  • receivePava(amount): increases the amount of pava held by the tavunu. If the amount is zero or less it does not change the pava and it returns false. Otherwise it adds the amount to the tavunu's pava and returns true.
  • getPava(): returns the amount of pava held by this tavunu.
  • Accessor and mutator for the year of their birth. Negative values are OK --- they correspond to BCE dates.
  • An appropriate toString() method.
  • No-argument (default) and parameterized constructors.
import org.junit.Test;
import static org.junit.Assert.*;

/**
 * Tests the Tavunu class w/ JUnit 4.
 *
 */
public class TavunuTest {

    /**
     * Also tests accessors.
     */
    @Test
    public void testCtorNoArg() {
        var tv = new Tavunu();
        assertEquals(tv.getName(), "");
        assertEquals(tv.getPava(), 0);
        assertEquals(tv.getBirthYear(), Integer.MIN_VALUE);
    }

    /**
     * Also tests accessors.
     */
    @Test
    public void testCtorParams() {
        var tv = new Tavunu("Dease", 1944, 42);
        assertEquals(tv.getName(), "Dease");
        assertEquals(tv.getPava(), 42);
        assertEquals(tv.getBirthYear(), 1944);
    }

    @Test
    public void testToString() {
        var tv = new Tavunu("Dease", 1944, 42);
        
        assertEquals("" + tv, "Dease born in 1944 has 42 pava.");
    }
    
    @Test
    public void testSetName() {
        var tv = new Tavunu();

        tv.setName("");
        assertEquals(tv.getName(), "");

        tv.setName("T");
        assertEquals(tv.getName(), "T");

        tv.setName("D");
        assertEquals(tv.getName(), "D");

        tv.setName("Trelling");
        assertEquals(tv.getName(), "Trelling");

        tv.setName("Dint");
        assertEquals(tv.getName(), "Dint");

        tv.setName("tranque");
        assertEquals(tv.getName(), "Dint");

        tv.setName("demary");
        assertEquals(tv.getName(), "Dint");

        tv.setName("Hint");
        assertEquals(tv.getName(), "Dint");
    }

    @Test
    public void testSetYear() {
        var tv = new Tavunu("Dease", 1944, 42);

        tv.setBirthYear(-2001);
        assertEquals(tv.getBirthYear(), -2001);

        tv.setBirthYear(0);
        assertEquals(tv.getBirthYear(), 0);

        tv.setBirthYear(2001);
        assertEquals(tv.getBirthYear(), 2001);
    }

    @Test
    public void testReceivePava() {
        var tv = new Tavunu("Dease", 1944, 42);

        boolean rv = tv.receivePava(-2001);
        assertEquals(tv.getPava(), 42);
        assertEquals(rv, false);

        rv = tv.receivePava(-1);
        assertEquals(tv.getPava(), 42);
        assertEquals(rv, false);

        rv = tv.receivePava(0);
        assertEquals(tv.getPava(), 42);
        assertEquals(rv, true);

        rv = tv.receivePava(1);
        assertEquals(tv.getPava(), 43);
        assertEquals(rv, true);

        rv = tv.receivePava(10);
        assertEquals(tv.getPava(), 53);
        assertEquals(rv, true);
    }

    @Test
    public void testSpendPava() {
        var tv = new Tavunu("Dease", 1944, 42);

        boolean rv = tv.spendPava(-2001);
        assertEquals(tv.getPava(), 42);
        assertEquals(rv, false);

        rv = tv.spendPava(-1);
        assertEquals(tv.getPava(), 42);
        assertEquals(rv, false);

        rv = tv.spendPava(0);
        assertEquals(tv.getPava(), 42);
        assertEquals(rv, true);

        rv = tv.spendPava(1);
        assertEquals(tv.getPava(), 41);
        assertEquals(rv, true);

        rv = tv.spendPava(10);
        assertEquals(tv.getPava(), 31);
        assertEquals(rv, true);
    }

}

In: Computer Science