I have to write two methods for a Fruit program that involves arrays. One of them is public void addFruit(String other) and the other is public void deleteFruit(String del). I have already done the deleteFruit.
How do I do the addFruit?
I don't what the code is or how to code it.
public class Fruit {
private String[] bowl;
public Fruit()
{
bowl = new String[10];
bowl[0] = "apple";
bowl[1] = "banana";
bowl[2] = "kiwi";
bowl[3] = "lemon";
bowl[4] = "lime";
bowl[5] = "mango";
bowl[6] = "orange";
bowl[7] = "pear";
bowl[8] = "pineapple";
bowl[9] = "plum";
}
public Fruit(int x)
{
bowl = new String[] {"apple", "banana", "lemon", "lime", "mango"};
}
public void display()
{
for (int x = 0; x < bowl.length; x++)
System.out.println(bowl[x]);
}
public void deleteFruit(String del)
{
int index = -1;
for(int i=0; i< bowl.length; i++)
if (bowl[i].equals(del))
index = i;
if (index ==-1)
System.out.println("Not in the list");
else
{
for (int i = index; i< bowl.length -1; i++)
bowl[i] = bowl [i+1];
String[] temp = new String[bowl.length-1];
for (int i = 0; i < temp.length; i++)
temp[i]= bowl [i];
bowl = temp;
System.out.println("item deleted");
}
public void addFruit(String other)
{
}
}
This is not the most effective solution, but it works.
public void addFruit(String other) {
String[] res = new String[bowl.length + 1];
for(int i = 0; i < bowl.length; i++) {
res[i] = bowl[i];
}
res[res.length - 1] = other;
bowl = res;
}
Related
In the code below I have a double for loop resulting in a time complexity of O^2 in method getResponse(). This code prompts the user for a 10 integer sequence string and an uppercase sensitive pin. It then converts the pin to numbers on a phone pad ie. [ABC] --> 2, [DEF] --> 3. Lastly a response array is generated with each digit of the new phone pin corresponding to indexes of sequence. So input "0123456789","HAM", response = "426"
import java.util.Scanner;
public class Test {
public static final int SEQ_DIGITS = 10;
public static final String ERR_SEQ = "Invalid sequence";
public static final String ERR_PIN = "Invalid PIN";
public static int letterToPhone(char c) {
int phoneNumber = 0;
if (Character.toString(c).matches("[ABC]")) {
phoneNumber = 2;
} else if (Character.toString(c).matches("[DEF]")) {
phoneNumber = 3;
} else if (Character.toString(c).matches("[GHI]")) {
phoneNumber = 4;
} else if (Character.toString(c).matches("[JKL]")) {
phoneNumber = 5;
} else if (Character.toString(c).matches("[MNO]")) {
phoneNumber = 6;
} else if (Character.toString(c).matches("[PQRS]")) {
phoneNumber = 7;
} else if (Character.toString(c).matches("[TUV]")) {
phoneNumber = 8;
} else if (Character.toString(c).matches("[WXYZ]")) {
phoneNumber = 9;
}
return phoneNumber;
}
public static int[] getResponse(String pin, int[] values) {
int[] response = new int[pin.length()];
for(int i = 0; i < pin.length(); i++) {
for (int j = 0; j < values.length; j++) {
int x = letterToPhone(pin.charAt(i));
if(x == j) {
response[i] = values[j];
}
}
}
return response;
}
public static boolean stringIsLengthK(String s, int k) {
boolean isLength = false;
if (s.length() == k) {
isLength = true;
}
return isLength;
}
public static boolean allDigits(String s) {
boolean isDigit = true;
for (int i = 0; i < s.length(); i++) {
if (!(Character.isDigit(s.charAt(i)))) {
isDigit = false;
break;
}
}
return isDigit;
}
public static boolean allUppercaseLetters(String s) {
boolean isUpper = true;
for (int i = 0; i < s.length(); i++) {
if (!(Character.isUpperCase(s.charAt(i)))) {
isUpper = false;
break;
}
}
return isUpper;
}
public static int[] digitStringToIntArray(String s) {
int[] arrayS = new int[s.length()];
for(int i = 0; i < arrayS.length; i++) {
for(int j = 0; j < SEQ_DIGITS; j++) {
if (((int) s.charAt(i) - 48) == j) {
arrayS[i] = j;
}
}
}
return arrayS;
}
public static int countValues(int value, int[] values) {
int count = 0;
for(int i = 0; i < values.length; i++) {
if(value == values[i]) {
count++;
}
}
return count;
}
public static int numPossible(int[] response, int[] values) {
int product = 1;
int[] count = new int[response.length];
for (int i = 0; i < count.length; i++) {
count[i] = countValues(response[i], values);
}
for(int i=0; i<response.length; i++){
product = product * count[i];
}
return product;
}
public static void main(String[] args) {
try (Scanner in = new Scanner(System.in)) {
System.out.printf("Enter value sequence: ");
final String seq = in.nextLine();
System.out.printf("Enter PIN: ");
final String pin = in.nextLine();
if (!(allUppercaseLetters(pin))) {
throw new AssertionError(ERR_PIN);
} else if (!(allDigits(seq)) || !(stringIsLengthK(seq, SEQ_DIGITS))) {
throw new AssertionError(ERR_SEQ);
}
int[] seqArray = new int[SEQ_DIGITS];
seqArray = digitStringToIntArray(seq);
int[] response = new int[SEQ_DIGITS];
response = getResponse(pin, seqArray);
System.out.printf("Response: ");
for (int i = 0; i < response.length; i++) {
System.out.printf("%d", response[i]);
}
System.out.printf("%n");
numPossible(response, seqArray);
} catch (Error e) {
System.out.println(e.getMessage());
}
}
}
I want to be to able to accommodate larger sequence numbers without a scaling of n^2. Is there a way to change the for loop to instead compare the int x = letterToPhone(pin.charAt(i)); value in getResponse() to a range of integers such as "[0-9]"
One easy optimization of constant factors is to move the call to letterToPhone() out of the inner loop.
And yes, you can compare the x value to a range, eliminating the need for the inner loop.
for(int i = 0; i < pin.length(); i++) {
int x = letterToPhone(pin.charAt(i));
if ( (0 <= x) && (x < values.length)) {
response[i] = values[x];
}
}
Another optimization of constant factors would be to replace all the function calls in letterToPhone() with a switch statement. The compiler may choose to optimize that into a table lookup.
I am receiving this error when I submit my code. This only happens when I submit my code on an online compiler necessary for my course, however, when I run my code via InteliJ it compiles properly.
Main.java:335: error: cannot find symbol
while (!(TeamMember.contains("Stop"))){
^
symbol: method contains(String)
location: class TeamMember
1 error
<
My classes are as follows:
Main:
package com.company;
import java.util.Scanner;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
String name = "";
String id = "";
ArrayList<TeamMember> list = new ArrayList<>();
while (!(TeamMember.contains("Stop"))) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the name: ");
name = scan.nextLine();
System.out.println("Please enter the id: ");
id = scan.nextLine();
list.add(new TeamMember(name.toLowerCase(), id));
System.out.println(Main.selectionSort(list));
}
int size = list.size();
for (int j = size; j > (list.size() + 2); j--) {
list.remove(j);
}
}
public static ArrayList<TeamMember> selectionSort(ArrayList<TeamMember> list) {
TeamMember[] teamArray = new TeamMember[list.size()];
for (int i = 0; i < list.size(); i++) {
teamArray[i] = list.get(i);
}
for (int i = 0; i < teamArray.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < teamArray.length; j++) {
if (teamArray[j].compareTo(teamArray[minIndex]) < 0) {
minIndex = j;
}
}
TeamMember holder = teamArray[i];
teamArray[i] = teamArray[minIndex];
teamArray[minIndex] = holder;
}
for (int i = 0; i < list.size(); i++) {
list.set(i, teamArray[i]);
}
return list;
}
}
TeamMember:
package com.company;
import java.util.ArrayList;
class TeamMember{
private String fullName;
private String idString;
public TeamMember(String name, String id){
fullName = "";
name = name.toLowerCase();
String [] charName = new String[name.length()];
for(int i = 0; i < charName.length; i++){
charName[i] = Character.toString(name.charAt(i));
if(i == 0){
charName[0] = charName[0].toUpperCase();
}
}
for(int i = 0; i < charName.length - 1; i++){
if(charName[i].equals(" ") && !charName[i + 1].equals(" ")){
charName[i + 1] = charName[i + 1].toUpperCase();
}
}
for(int i = 0; i < charName.length; i++){
fullName = fullName + charName[i];
}
idString = id;
}
public static boolean contains(String stop) {
return false;
}
public String getID(){
return idString;
}
public String toString(){
return fullName;
}
public int compareTo(TeamMember other){
if(idString.compareTo(other.getID()) < 0){
return -1;
}
else if(idString.compareTo(other.getID()) > 0){
return 1;
}
else{
return 0;
}
}
}
It looks like class TeamMember is not accessible from your Main class. Try this code as it should work having the classes in the same file.
import java.util.Scanner;
import java.util.ArrayList;
public class Main
{
public static void main(String[] args) {
String name = "";
String id = "";
ArrayList<TeamMember> list = new ArrayList<>();
while (!(TeamMember.contains("Stop"))) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the name: ");
name = scan.nextLine();
System.out.println("Please enter the id: ");
id = scan.nextLine();
list.add(new TeamMember(name.toLowerCase(), id));
System.out.println(Main.selectionSort(list));
}
int size = list.size();
for (int j = size; j > (list.size() + 2); j--) {
list.remove(j);
}
}
public static ArrayList<TeamMember> selectionSort(ArrayList<TeamMember> list) {
TeamMember[] teamArray = new TeamMember[list.size()];
for (int i = 0; i < list.size(); i++) {
teamArray[i] = list.get(i);
}
for (int i = 0; i < teamArray.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < teamArray.length; j++) {
if (teamArray[j].compareTo(teamArray[minIndex]) < 0) {
minIndex = j;
}
}
TeamMember holder = teamArray[i];
teamArray[i] = teamArray[minIndex];
teamArray[minIndex] = holder;
}
for (int i = 0; i < list.size(); i++) {
list.set(i, teamArray[i]);
}
return list;
}
}
class TeamMember{
private String fullName;
private String idString;
public TeamMember(String name, String id){
fullName = "";
name = name.toLowerCase();
String [] charName = new String[name.length()];
for(int i = 0; i < charName.length; i++){
charName[i] = Character.toString(name.charAt(i));
if(i == 0){
charName[0] = charName[0].toUpperCase();
}
}
for(int i = 0; i < charName.length - 1; i++){
if(charName[i].equals(" ") && !charName[i + 1].equals(" ")){
charName[i + 1] = charName[i + 1].toUpperCase();
}
}
for(int i = 0; i < charName.length; i++){
fullName = fullName + charName[i];
}
idString = id;
}
public static boolean contains(String stop) {
return false;
}
public String getID(){
return idString;
}
public String toString(){
return fullName;
}
public int compareTo(TeamMember other){
if(idString.compareTo(other.getID()) < 0){
return -1;
}
else if(idString.compareTo(other.getID()) > 0){
return 1;
}
else{
return 0;
}
}
}
I am trying to extract similar strings from 2 arrays, and I have managed to do so, except they are duplicating. i.e. array 1 {"arrow", "arrow", "sycophant"} and array 2 ("arrow", "sycophant", "bulbasaur"} will give me the output of {"arrow", "arrow" ,"sycophant"}, while I am only trying to get arrow once. Any suggestions?
public static void main(String[] args) {
String[] words1 = { "sycophant", "rattle", "zinc", "alloy", "tunnel", "arrow" };
String[] words2 = { "sycophant", "arrow", "arrow" };
// String prefix = "a";
// String substring = "at";
// char[] letters = { 'a', 'b' };
// String[] output = wordsStartingWith(words1, prefix);
// String[] output = wordsContainingPhrase(words1, substring);
// String[] output = wordsContainingAll(words1, letters);
String[] output = wordsInBoth(words1, words2);
for (int i = 0; i < output.length; i++) {
System.out.println("Words: " + i + " " + output[i]);
}
}
public static String[] wordsInBoth(String[] words1, String[] words2) {
// method that finds and returns common words in two arrays
String[] returnWords;
int countWords = 0;
for (int i = 0; i < words1.length; i++) {
for (int j = 0; j < words2.length; j++) {
if (words1[i].equalsIgnoreCase(words2[j])) {
countWords++;
}
}
}
returnWords = new String[countWords];
countWords = 0;
for (int i = 0; i < words1.length; i++) {
for (int j = 0; j < words2.length; j++) {
if (words1[i].equalsIgnoreCase(words2[j])
&& !words1[i].equalsIgnoreCase(returnWords[countWords])) {
returnWords[countWords] = words1[i];
countWords++;
}
}
}
return returnWords;
}
One possibility is to store the words that are found in a HashSet, which won't add duplicates.
// method that finds and returns common words in two arrays
public static String[] wordsInBoth(String[] words1, String[] words2) {
Set<String> returnWords = new HashSet<String>();
for (int i = 0; i < words1.length; i++) {
for (int j = 0; j < words2.length; j++) {
if (words1[i].equalsIgnoreCase(words2[j]))
returnWords.add(words1[i]);
}
}
return returnWords.toArray(new String[returnWords.size()]);
}
You want to get the intersection between two lists. The answer to Intersection and union of ArrayLists in Java should point you in the right direction:
public class Test {
public static void main(String... args) throws Exception {
List<String> list1 = new ArrayList<String>(Arrays.asList("A", "B", "C"));
List<String> list2 = new ArrayList<String>(Arrays.asList("B", "C", "D", "E", "F"));
System.out.println(new Test().intersection(list1, list2));
}
public <T> List<T> intersection(List<T> list1, List<T> list2) {
List<T> list = new ArrayList<T>();
for (T t : list1) {
if(list2.contains(t)) {
list.add(t);
}
}
return list;
}
}
In case you wonder why this
for (int i = 0; i < words1.length; i++)
for (int j = 0; j < words2.length; j++)
if (words1[i].equalsIgnoreCase(words2[j]) &&
!words1[i].equalsIgnoreCase(returnWords[countWords])
)
returnWords[countWords++] = words1[i];
doesn't work: it only a) attempts to check if words1[i] isn't the b) last word in returnWords.
a)
!words1[i].equalsIgnoreCase( returnWords[countWords] )
is always true, because returnWords[countWords] is always null. When countWords is 0 there are no words added to it yet, and when it is 1, the added word is at returnWords[0]. So you'll need something like this instead:
countWords == 0 || !words1[i].equalsIgnoreCase( returnWords[countWords-1] )
Now it works fine for your input (removed unique words):
String[] words1 = { "arrow", "sycophant" };
String[] words2 = { "arrow", "sycophant", "arrow" };
it outputs
Words: 0 arrow
Words: 1 sycophant
Words: 2 null
b)
For
String[] words1 = { "arrow", "sycophant", "arrow" };
String[] words2 = { "arrow", "sycophant" };
it outputs
Words: 0 arrow
Words: 1 sycophant
Words: 2 arrow
To prevent this, you would have to check whether the word about to be added isn't any of the already-added words:
!contains( returnWords, words1[j] )
This is a simple for-loop, which you know how to do - and there are plenty of examples on this page, so I'll leave that out.
Maybe this will help you. I have changed your algorithm a bit and now it looks like this.
import java.util.Arrays;
public class Distinct {
public static void main(String[] args) {
String[] words1 = { "sycophant", "rattle", "zinc", "alloy", "tunnel",
"arrow" };
String[] words2 = { "sycophant", "arrow", "alloy", "arrow" };
// String prefix = "a";
// String substring = "at";
// char[] letters = { 'a', 'b' };
// String[] output = wordsStartingWith(words1, prefix);
// String[] output = wordsContainingPhrase(words1, substring);
// String[] output = wordsContainingAll(words1, letters);
String[] output = wordsInBoth(words1, words2);
for (int i = 0; i < output.length; i++) {
System.out.println("Words: " + i + " " + output[i]);
}
}
public static String[] wordsInBoth(String[] words1, String[] words2) {
String[] returnWords;
int countWords = 0;
for (int i = 0; i < words1.length; i++) {
for (int j = 0; j < words2.length; j++) {
if (words1[i].equalsIgnoreCase(words2[j])) {
countWords++;
}
}
}
returnWords = new String[countWords];
countWords = 0;
for (int i = 0; i < words1.length; i++) {
for (int j = 0; j < words2.length; j++) {
if (words1[i].equalsIgnoreCase(words2[j]) && !exists(returnWords, words1[i])) {
returnWords[countWords] = words1[i];
countWords++;
}
}
}
return Arrays.copyOfRange(returnWords, 0, countWords);
}
public static boolean exists(String[] array, String value)
{
if (array.length == 0)
return false;
for(int i = 0; i < array.length; i++){
if (array[i]!= null && array[i].equalsIgnoreCase(value) )
return true;
}
return false;
}
}
Try this.
public static String[] wordsInBoth(String[] words1, String[] words2) {
return Stream.of(words1)
.filter(w -> Stream.of(words2).anyMatch(w::equalsIgnoreCase))
.toArray(String[]::new);
}
After a bit of fiddling around with the (primitive, slow and downright beginner :P) code I found a (messy) solution to my problems. XD
public static String[] wordsInBoth(String[] words1, String[] words2) {
// method that finds and returns common words in two arrays
String[] returnWords = new String[words1.length];
String compare = "";
int countWords = 0;
for (int i = 0; i < words1.length; i++) {
for (int j = 0; j < words2.length; j++) {
if (words1[i].equalsIgnoreCase(words2[j]) && words1[i] != compare) {
returnWords[countWords] = words1[i];
compare = returnWords[countWords];
countWords++;
}
}
}
returnWords = new String[countWords];
countWords = 0;
for (int i = 0; i < words1.length; i++) {
for (int j = 0; j < words2.length; j++) {
if (words1[i].equalsIgnoreCase(words2[j]) && words1[i] != compare) {
returnWords[countWords] = words1[i];
compare = returnWords[countWords];
countWords++;
}
}
}
return returnWords;
}
(also, I don't know why, but my method line is not included in the code snippet when I post to Stack)
I have to write a program that sorts names alphabetically while removing duplicates and counting the amount of times the names appear and capitalizes all of it. My partner and I have been working on this and have found no way to have the sorting method work properly and have the program find and count the times the names appear. We have to use certain methods to do this...which I linked the pdf down at the bottom. I really want to understand what's wrong and why the output is not coming out right.
public class Names {
/**
* #param args the command line arguments
*/
static ArrayList<String> fnArray = new ArrayList<String>();
static ArrayList<String> lnArray = new ArrayList<String>();
public static void main(String[] args) throws IOException {
// TODO code application logic here
getNames(fnArray, lnArray);
sort(lnArray);
find(fnArray,1);
capitalize(fnArray,lnArray);
}
public static void getNames(ArrayList<String> fn, ArrayList<String> ln) throws IOException {
Scanner kb = new Scanner(System.in);
System.out.println("What file would you like to read from ?: ");
String n = kb.next();
File inputFile = new File(n);
Scanner in = new Scanner(inputFile);
while (in.hasNext()) {
String firstName = in.next();
fn.add(firstName);
String lastName = in.next();
ln.add(lastName);
}
for (int i = 0; i < fnArray.size(); i++) {
System.out.println(lnArray.get(i) + " " + fnArray.get(i));
}
}
public static void capitalize(ArrayList<String> fnArray, ArrayList<String> lnArray) {
String capfn = " ";
String capln = " ";
int i = 0;
int j = 0;
System.out.println("****************Names***************");
while (i < fnArray.size() && j < lnArray.size()) {
capfn = fnArray.get(i);
capln = lnArray.get(j);
String capFname = capfn.substring(0, 1).toUpperCase() + capfn.substring(1).toLowerCase();
String capLname = capln.substring(0, 1).toUpperCase() + capln.substring(1).toLowerCase();
fnArray.set(i, capFname);
lnArray.set(i, capLname);
System.out.println(lnArray.get(j) + ", " + fnArray.get(i));
i++;
j++;
}
}
public static void display(ArrayList<String> names) {
for (int i = 0; i < names.size(); i++) {
System.out.println(names.get(i));
}
}
public static int find(String s, ArrayList<String> a) {
int count = 0;
for (String str : a) {
if (str.equalsIgnoreCase(s))
count++;
}
return count; }
public static void removeDuplicates(ArrayList<String> s) {
for (int j = 0; j < s.size(); j++) {
int i = -1;
while ((i = find(s, j)) >= 0) {
s.remove(i);
}
}
}
public static void backwards(ArrayList<String> names) {
for (int i = names.size() - 1; i > 0; i--) {
names.get(i);
for (int j = 0; j < names.size(); i++) {
if ((names.get(i).equals(names.get(j)))) {
names.remove(i);
}
}
}
}
public static void sort(ArrayList<String> array) {
for (int i = 1; i < array.size(); i++) {
// find the index of the ith smallest value
int s = i - 1;
for (int j = i; j < array.size(); j++) {
if (array.get(j).compareTo(array.get(s)) < 0) {
s = j;
}
}
// swap the ith smallest value into entry i-1
String temp = array.get(i - 1);
array.set(i - 1, array.get(s));
array.set(s, temp);
}
}
public static void showUnique(ArrayList<String> names){
System.out.println("Unique name list contains:");
for(int i=0 ;i< names.size() ;i++){
System.out.println(lnArray.get(i) + " " + fnArray.get(i));
}
}}
You can use the Collections.sort() method to sort an array list; once it is sorted, you will have entries like this:
ArrayList = { "Alpha", "Beta", "Beta", "Gamma", "Theta", "Theta" ... }
The important point to note, however, is that the duplicates will be next to each other in the sorted array.
Finally, if you want to remove duplicates, you can put all the elements of the ArrayList into a Set: set is a data-structure which removes duplicates.
Example:
Set<String> foo = new HashSet<String>( yourArrayList );
EDIT: Use this approach which is both: easy and simple-to-comprehend.
for( int i = 0; i < array.size() - 1; i++ )
{
for( int j = i + 1; j < array.size(); j++ )
{
if( array[i] > array[j] )
{
// Swap the contents of array[i] and array[j].
}
}
}
I have an input file called input.txt with a list of names. I have no problem displaying all the names and putting them in alphabetical order with both display and sort methods. But what I am currently struggling to do is create a method where I can count the recurrence of each name in the file. I would grealty appreciate if anyone could help me with this, and find a way to create this method.
public class Names {
public static void display(ArrayList<String> names) {
for (int i = 0; i < names.size(); i = i + 1) {
System.out.println(names.get(i));
}
}
public static int find(String s, ArrayList<String> a) {
for (int i = 0; i < a.size(); i = i + 1) {
String str = a.get(i);
if (str.equals(s)) {
return i;
}
}
return -1;
}
public static void capitalize(ArrayList<String> names) {
for (int i = 0; i < names.size(); i = i + 1) {
String name = names.get(i);
if (!name.isEmpty()) {
String firstLetter = "" + name.charAt(0);
names.set(i, firstLetter.toUpperCase() + name.substring(1).toLowerCase());
}
}
}
public static void sort(ArrayList<String> names) {
for (int i = 0; i < names.size() - 1; i = i + 1) {
int Min = i;
for (int j = i + 1; j < names.size(); j = j + 1) {
if (names.get(j).compareTo(names.get(Min)) < 0) {
Min = j;
}
}
String tmp = names.get(i);
names.set(i, names.get(Min));
names.set(Min, tmp);
}
}
public static void getNames(ArrayList<String> fn, ArrayList<String> ln) throws IOException {
Scanner kb = new Scanner(System.in);
System.out.println("What is the input flie?");
String names = kb.next();
File inpFile = new File(names);
Scanner in = new Scanner(inpFile);
while (in.hasNext()) {
String firstName = in.next();
String lastName = in.next();
fn.add(firstName);
ln.add(lastName);
}
}
private int countOccurence(String name, ArrayList<String> names){
int count = 0;
for(int i =0; i <= names.size; i++){
if(name.equalsIgnoreCase(names.get(i))){
count++;
}
}
return count;
}
public static void main(String[] args) throws IOException {
ArrayList<String> first = new ArrayList<>();
ArrayList<String> last = new ArrayList<>();
getNames(first, last);
capitalize(first);
capitalize(last);
ArrayList<String> allNames = new ArrayList<>();
for (int i = 0; i < first.size(); i++) {
allNames.add(last.get(i) + ", " + first.get(i));
}
System.out.println("*******All Names******");
sort(allNames);
display(allNames);
System.out.println("*****First Name Count***");
for(int i =0; i <= first.size; i++){
int count = countOccurence(first.get(i), first);
System.out.println(first.get(i) + " occured " + count + " times.");
}
System.out.println("****Last Name Count****");
sort(last);
display(last);
}
}
Use Map structure for those case:
Map<String, Integer> recurence = new HashMap<>();
int count;
for (String name : names) {
if (recurence.containsKey(name)) {
count = recurence.get(name) + 1;
} else {
count = 1;
}
recurence.put(name, count);
}
create a method that counts the occurences:
public static int countOccurence(String name, ArrayList<String> names){
int count = 0;
for(int i =0; i <= names.size(); i++){
if(name.equalsIgnoreCase(names.get(i))){
count++;
}
}
return count;
}
To use it, go through the loop in you Main ( or you can create another method)
for(int i =0; i <= first.size; i++){
int count = countOccurence(first.get(i), first);
System.out.println(first.get(i) + " occured " + count + " times.");
}