Category Archives: Java

String Lab Assignment

In this lab, you will work with a GUI to validate the input in each text field . Below is a screenshot of the running program.  Download Source File

validate-user-input

Validate that each of the following criteria has been met.

  1. User’s name
    1.  at least 3 characters
    2. only upper and lower case letters allowed
  2. Password
    1. at least 4 characters
    2. cannot contain the user’s name
  3. Email
    1. Must include an “@”
    2. Must include a “.”
    3. the “.” must come after the “@”
  4. Phone
    1. XXX-XXX-XXXX
      1. where each”X” must be an integer value
      2. each “-” must be in the correct location
  5. Date of Birth
    1. Max age is 110
    2. Minimum accepted age is 18
      1. If the user is less than 18, display the message. “Sorry you must at least 18 years of age for this service”
  6. Zip Code
    1. Each character must be an integer
    2. Length between 3 and 5 , inclusive

 

 

screen-shot-code

 

 

A  file that does a few test cases (be careful not to overwrite your work)

String Loop Assignments [Java]

Write the body for the methods described below.

Part I

public int countF(String str)

Description: This method returns the number of times that the letter ‘f’ occurs in str..

Method Call return value/output
countF(“abcdef”) 1
countF(“abcdfef”) 2
countF(“fff”) 3
countF(“xxx”) 0

public boolean has2Fs(String str)

Description: This method returns true if str has exactly two occurrences of the letter ‘f’ in it.

Method Call return value/output
has2Fs(“foo”) false
has2Fs(“fofo”) true
has2Fs(“foffo”) false

public boolean has2Fs3Gs(String str)

Description: This method returns true if str has exactly two occurrences of the letter ‘f’ in it and 3 occurences ‘g’.

Method Call return value/output
has2Fs3Gs(“foog”) false
has2Fs3Gs(“foggfog”) true
has2Fs3Gs(“foffoggg”) false

public int momOrDad(String str)

Description: This method returns the number of times that the String “mom” or the string “dad” occurs in the parameter str .

Method Call return value/output
momOrDad(“foog”) 0
momOrDad(“momf”) 1
momOrDad(“momdadmo”) 2
momOrDad(“momdadmom”) 3

public String threeTimes(String str)

Description: This method returns the String str concatenated with itself three times

Method Call return value/output
threeTimes(“foog”) “foogfoogfoog”
threeTimes(“abc”) “abcabcabc”
threeTimes(“zt”) “ztztzt”
threeTimes(“”) “”

public String nTimes(String str, int n)

Description: This method returns the String str concatenated with itself n times

Method Call return value/output
nTimes(“fg” , 2 ) “fgfg”
nTimes(“abc” , 0 ) “”
nTimes(“zt” , 3 ) “ztztzt”
nTimes(“uiz” , 4 ) “uizuizuizuiz”

public int countMiddleChar(String str)

Precondition: str.length() ≥ 3.

Description: This method returns the number of times the middle letter of str appears in str.

Method Call return value/output
countMiddleChar(“acbcb” ) 2
countMiddleChar(“acbcx” ) 1
countMiddleChar(“bbbbb” ) 5
countMiddleChar(“xytbtzy”) 1

public int indexOf(String haystack, String needle)

Description: Write your own indexOf() method. Obviously, you cannot make use of the String’s build in indexOf() method. This method returns the index of the first occurrence of needle in haystack . (Full credit if you can get this to work with Strings whose length is greater than 1).

Method Call return value/output
indexOf(“acxb”, “x” ) 2
indexOf(“zazt”, “z” ) 0
indexOf(“tayv”, “g” ) -1
indexOf(“hijklj”, “j” ) 2

If you want the extra credit, then it must also be able to complete the following example calls

Method Call return value/output
indexOf(“acxb”, “cx” ) 1
indexOf(“acxb”, “cxb” ) 1
indexOf(“acxb”, “cxbt” ) -1

public int countChars(String str, String chars)

Precondition:The length of chars is less than or equal to the length of str

Description: This method returns the number of times that charsoccurs in String str.

Method Call return value/output
countChars(“momdadmom” , “dad” ) 1
countChars(“foobofoo” , “foo”) 2
countChars(“foobofoofoo” , “foo”) 3
countChars(“foobofoofoo” , “xy” ) 0

Part II

public  String[] toArray(String str)

Description: This method returns an array comprised of the individual characters of str

Method Call return value/output
toArray(“abc”  ) { “a”, “b”, “c”}
toArray(“xyz”  ) {“x”, “y”, “z”}

 

 

**

public boolean isPalindrome(String str)

Description: This method returns true if str is a palindrome.

Method Call return value/output
isPalindrome(“abc”  ) false
isPalindrome(“aba”  ) true
 isPalindrome(“abba”  )  true

 

 

Java Stack Assignment

A Stack is a “LIFO” data structure (last in first out).

Here’ s an animation of how stacks are used in an RPN calculator.

More RPN practice

 

Create a stack Class that is based off of your linkedList code.

 

A stack has the following 3 methods

 

 

 

Create an RPN calculator Class

 

 

 

String Assignments SUPA 2015-16

Unit 3 Strings

substrings1

Bank Account Inheritance Assignment

Person Class

This page is an edited version of this (old) assignment

Constructor

  • public Person( String _name, int _age)

instance Variables

  • private String name
  • private int age

 Methods

  • public String  getName()
  • public boolean equals(Person  other) // assume that two objects with same age and name are equal

Account – Super Class

Static Variable(s)

  • static private  int nextAccountNum

Constructor

  • public Account( double_balance, Person _owner)

instance Variables

  • private int  accountNumber
  • protected  double  balance
  • protected  Person[] owners

 Methods

  • public int getAccountNumber()
  • public void deposit(double amount)
  • public double getCurrentBalance()
  • public  boolean withdraw(double amount); // returns  false if  amount > this.balance
  • public boolean equals(Account other)
  • public String toString()
  • public void addOwner(Person p)
  • public void removeOwner( Person p)
  • public Person[] getOwners()

CheckingAccount extends Account

  • instance Variables
    • private int checksWritten
  • Acessors and Mutators
    • void writeCheck( double amount) –> tries to call super.withDraw() as long as the balance is enough and records a new check number

SavingsAccount extends Account

  • instance variables
    • private double interestRate
    • double[]  dailyBalances

    static variables

    • public static final int MINIMUM_BALANCE=100; // this is the absolute minimum amount of money that must always be in the account
  • methods
    • public boolean withdraw(double amount) //@override the withdraw() method to ensure that currentBalance the never gets below MINIMUM_BALANCE
    • public void recordDailyBalance() // @ record current day’s balance by storing it in   dailyBalances

 

After you have completed this, work on the Bank runner class.

Class Roster Array Version [Java] Assignment

Class Roster: This class will implement the functionality of all roster for school. It will , in essence, manage an Array of Student objects. Each roster will store a default of 10 Students

  • “global” Instance Variables
    • private Student myStudents   : an array storing Student Objects
    • private String className  (a name to represent a given roster like “Ap CS”)
    • public int period //during which period of the day does this roster meet
  • a default constructor should initialize the Array to store 20 strings
    a single parameter constructor that takes an Array <String>
    Both constructors should initialize the instance variables
  • Methods
    • Accessors
      • private int indexOf(Student st) //@returns index of Student St or -1
      • public boolean containsStudent(Student studentName )/ /@returns true if studentName is in roster .
      • public boolean equals(ClassRoster other) //@ returns whether or not rosters are equal. Rosters are equal if identical students are in identical order in the lists
    • Mutators:

public void addStudent(String studentName, int age) ;// adds student name and age to end of roster

. Hint: Make user of the containsStudent() method
public boolean removeStudent(int ssnId ) // removes student from roster based on id. Make sure that you maintain the integrity of the parallel ArrayLists.

public boolean removeStudent(String name) //removes student based on name. Make sure that you maintain the integrity of the parallel ArrayLists.

public  boolean removeStudent( Student st) //removes student st. Make sure that you maintain the integrity of the parallel ArrayLists.

Student Runner Part 2

1) Construct the Java statement to create the Student object called aStudent  in the

StudentsRunner

 

2)

Back to the Student Class


 

Student Object (OOP Java)

Student Class

A school district decided to write a program to help keep track of various parts of the school.

It has been decided to store relevant information about Students in a Student class. Each Student will have an array of Strings to store the names of his or her teachers.

private instance variables

 

Part 1

* Construct the Java statement to declare the array called

teachersNames to store the String names of the student’s teachers

Part 2

  • write a default constructor
  • construct a method called  addTeacher( String name) that adds String name to the  teachersNames  array
    • to do this let’s create a private method  private String[] addStr( String[] input, String val) that adds value to the end of the array and returns it. [redact]Solution[/redact]
  • construct hasTeacher(String name)  that returns true if name is in the teachersName array
  • construct a method removeTeacher(String name) that removes the   String name from the  teachersNames  array.
  • construct a method the line of code needed in the setGpa(double to) method of the Student Class.
  • construct a method boolean setTeacher (String name, int index) .   This method should return true if index is valid in the array and false if  index >= teachersName.length

 

Next: The runner class