Array Fun 2 [2023]

Complete all the methods below. When you are done, copy and paste the    testmethods.v5.1  into your class and run it to see if you have any obvious errors.  The above code does not guarantee you a 100 but will help catch most of the common errors that students make.

Note: You may not use any external libraries (like Java.Arrays etc )or import any code. Everything can be done with just loops and variables.

int sumEveryN(int[] nums, int n)

Description:This method returns the sum of every  n  elements of nums ..

 Method Call return value/output sumEveryN( {1 , 2 , 3 , 4 }, 2 ) 4( ie 1 +3) sumEveryN( {13 , 42, 15, 33 , 44 , 16 , 52} ,3) 98 ( ie 13 + 33+ 52)

String[] doubleArr(String[] strs)

Description: This method returns a new version of strs  in which each element now appears twice. This can be done with a for-each loop, which I believe is easier and more intuitive.

 Method Call return value/output doubleArr( {“a”,”b”,”c”} ) {“a”,”a”,”b”,”b”, “c” , “c”} doubleArr( {“math”,”ware”,”house”,”.com” }) {“math”,”math”,”ware”,”ware”,”house”,”house”,”.com”, “.com”}

int  indexOf5(int[] nums )

Description:This returns the index of the first occurrence element 5  or -1 if 5 does not appear anywhere in the array.

 Method Call return value/output indexOf5( { 2 , 3 , 5 , 4 } ) 2 indexOf5( { 2 , 3 , 5 , 4, 5  } ) 2 indexOf5( { 2 , 3 ,7  , 4, 3,   } ) -1

More Sample calls and return vals

int indexOf(int[] nums, int num)

Description: This method returns the index value of the first appearance of num  or -1 if num  is not an element of nums  .

 Method Call return value/output indexOf( {6,4 ,7,3, 4 }, 4) 1 indexOf( {6,4 7 ,3,2,7}, 7) 2 indexOf( {6,4 ,2,3}, 22) -1

int[] randos(int start, int end, int howMany)

Description:  This method returns an array of random numbers between [start,end] . Note make sure that each element in the new array attempts to make a new random int.  Use Math.random() , do not use any other mechanism for finding a random number.

More example calls and returns :

double meanBetween(int[] nums, int min, int max)

Description:  This method returns the mean of nums ; however, this method only counts values within the range (min,max) as shown in the examples below:

(Not inclusive, so do not count min or max )

int secondSmallest(int[] nums )

Description: This method returns the element of nums  with the second smallest value.

Note: You may not modify the input array. For instance, you may not put nums in order,  which would be bad because you were not asked to modify the array.

@precondition: nums.length >= 2

Note: You will lose credit if you use a constant to represent the smallest or second smallest number. See pseudocode

 Method Call return value/output secondSmallest( { 2 , 18 , 22, 4 , 6 } ) 4 secondSmallest( { 3 , 7 , 15 , 1 ,101} ) 3

boolean isPalindromic(int[] nums)

Description:This method returns true if the elements of nums  are a palindrome.

 Method Call return value/output isPalindromic(( { 5 , 2, 7 , 2 , 5} ) true isPalindromic( { 5 , 2, 7 , 3 , 5} )) false isPalindromic(( { 1 , 2, 1} ) true

Old versions:

Array Fun 1

Array F un 2 (v 1)

Array Fun 3 (resizing included)

String Lab Assignment [loops]

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.

2.  If you’re using bluej, you want to run “main” as shown here
3. Find the code section shown below. This is the one and only 1 area that you should be editing
4. Validate the user input as described below:
1. Name
1. length of 3 >=
2. only letters (spaces is ok)
2.  Email
1. Must include an “@”
2. Must include a “.”
3. the “.” must come after the “@”
3. Phone
1. XXX-XXX-XXXX
1. where each”X” must be an integer value
2. each “-” must be in the correct location
4. Date of Birth
1. To convert a String to an integer use Integer.valueOf(String str)
2. Max age is 110
3. 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”
1. Length must be at least 5
2. cannot include the name anywhere inside the password
6. Zip Code
1. Each character must be an integer
2. Length between 3 and 5 , inclusive

If the user has no errors, then please show the message “Thanks for submitting your information ” , as shown below

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.

Tester File here  (This one does not yet test the newest method)

As always, do not import any external libraries. All of the coding can be accomplished by using just  loops, arrays, strings and variables. Using anything else will lead to total loss of credit on associated methods.

Once you have completed each method, copy and paste the code in this file into your class. Then run the test() method and you will get feedback on your code. Note: This does not test all the methods. I have added new methods since writing that tester file. Also, please make sure that:

• variables are camelcase and have meaningful names
• for i  loops use i as a variable
• for-each  loops do not use i  as the variable

Part I

New Method 11.16 – Tester file updated 11.17

boolean isAfterN(String str, String chrs, int index)

DescriptionThis method returns true if chrs  appears in  str  after index .

int countF(String str)

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

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

boolean hasN_Fs(String str, int n )

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

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(“”) “”

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”

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

int indexOf(String haystack, String needle)

Description: Write your own indexOf() method.  Just to avoid any confusion – you cannot make use of the String’s built in indexOf() method. Our method returns the index of the 1st occurrence of needle in haystack . (Full credit if you can get this to work with Strings whose length is greater than 1).

int countChars(String str, String chars)

@precondtion : chars.length() <= str.lenght()

Description: This method returns the number of times that chars  occurs 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

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”}

String[] toArraySansChar(String str, char ch)

DescriptionThis method returns an array of Strings comprised of  single letter strings extracted from the input String str ; however, we will always skip the char ch :

String[] reversedBy2s(String str)

DescriptionThis method returns an array of Strings comprised of pairs of characters from the input, — in reverse order as shown below:

String reverseBy3s(String str)

DescriptionThis is like the prior method, except you are going by 3’s and returning a String , not an array of Strings.

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

Person Class

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 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

Students Runner Class

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

StudentsRunner

Next to Student Runner Part 2

Back to the Student Class