KSU CS3401 Assignment 1 Part 1

/*Course: CS3401
 * Section: 01
 * Name: Dalibor Labudovic
 * Professor: Alan Shaw
 * Assignment: Assignment 1 Part 1
*/

package assigment1;
import java.util.Random;
 import java.util.Scanner;

 public abstract class CountChars {

 public static void main(String[] args) {
 //string with alphabet upper case and lower case
 final String characterSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
 //size of the array
 int length = 30;
 //object for user input
 Scanner input = new Scanner(System.in);
 //initiate an array for 30 random characters
 char[] charArray = new char[length];
 //object for random number generator
 Random NumGenerator = new Random();
 int randNumber;
//print out the 30 random characters via loop
 System.out.println("30 random characters: ");
 for(int i=0;i<length;i++){
 randNumber = NumGenerator.nextInt(characterSet.length()-1)+1;
 charArray[i] = (char)characterSet.charAt(randNumber);
 System.out.print(charArray[i]);
 }

 System.out.println();
 char charToCount;
 //ask user to select a character
 System.out.print("Enter a character: ");
 //get input from user and to go the first index in the char array
 charToCount = input.next().charAt(0);
// display the results
 System.out.print("Your character: " + charToCount + " occured " + countTheChar(charArray,charToCount,0) + " time(s)" );
 }
 //Non recursive method
 public static int countTheChar(char[] chars, char ch){
 int counter = 0;
 //loop to check if the user input character matches any of the characters in
 //the random character array and if so increase the counter, the method will then return
 //that counter integer
 for(int i=0;i<chars.length;i++){
 if(chars[i] == ch)
 counter ++;
 }
 return counter;
 }
//Recursive method
 public static int countTheChar(char[] chars,char ch,int high){
//condition to stop the recursion once reached the the end of the character array
 if(high>=30)
 return 0;
 //condition to loop until the recursion is met
 else{
 if(chars[high] == ch)
//recursion method will return a integer value as the number of occurances matches the character input
 return 1 + countTheChar(chars,ch,high+1);
 return countTheChar(chars,ch,high+1);
 }
 }
 }

Comments

Popular posts from this blog

How to clear & format SD card

Sharepoint List: Days Elapsed or Countdown

CS4500 Test 4 Study Guide