My program is working fine on all parts except one. I am attempting to post as little code as possible. Please let me know if more is needed.
How do I find the name that occurs the most in a String, or StringBuilder? The "getWinner" method is where I am having trouble. I want to find the name (or winner) that occurs the most in a string. If their is a tie, the name that appears first is sufficient. Thanks in advance!
import java.util.ArrayList;
public class BallotBox
{
private ArrayList<String> ballots;
public BallotBox()
{
ballots = new ArrayList<String>();
}
public void addVote(String candidate)
{
ballots.add(candidate);
}
//****below is the method that's presenting a problem.****
public String getWinner()
{
StringBuilder candidates = new StringBuilder();
String winner = "";
for(int i = 0; i < ballots.size(); i++)
{
}
return winner;
}
public int getVoteCount(String candidate)
{
int count = 0;
for(int i = 0; i < ballots.size(); i++)
{
if(ballots.get(i).equals(candidate))
{
count++;
}
}
return count;
}
public String getResults()
{
StringBuilder resultTable = new StringBuilder();
ArrayList<String> printed = new ArrayList<String>();
for (String candidate : ballots)
{
if (!printed.contains(candidate))
{
resultTable.append(String.format("%s (%d)\n", candidate, getVoteCount(candidate)));
printed.add(candidate);
}
}
return resultTable.toString();
}
}
You can try to convert the list to a Set and use the Collections.frequency method.
Set<String> uniqueSet = new HashSet<String>(list);
for (String temp : uniqueSet)
{
System.out.println(temp + ": " + Collections.frequency(list, temp));
}
You'll get the output as shown below.
d: 1
b: 2
c: 2
a: 4
Check the link for more details
http://www.mkyong.com/java/how-to-count-duplicated-items-in-java-list/
You can use a HashMap to keep the votes for every candidate, and update the winner as soon as you find a new winner (more votes than the current winner):
public String getWinner()
{
final Map<String, Integer> votesCount = new HashMap<String, Integer>();
String winner = ballots.get(0);
int winnerVotes = 1;
for(final String ballot : ballots)
{
if (!votesCount.containsKey(ballot))
votesCount.put(ballot, 0);
votesCount.put(ballot, votesCount.get(ballot)+1);
if (votesCount.get(ballot)>winnerVotes)
{
winner = ballot;
winnerVotes = votesCount.get(ballot);
}
}
return winner;
}
Here is a working example. Hope this explains how the above code can be used in your application.
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class BallotBox
{
private ArrayList<String> ballots;
public BallotBox()
{
ballots = new ArrayList<String>();
ballots.add("John");
ballots.add("Eric");
ballots.add("Mary");
ballots.add("Eric");
ballots.add("Mary");
ballots.add("Mary");
ballots.add("John");
ballots.add("Mary");
}
public void addVote(String candidate)
{
ballots.add(candidate);
}
// ****below is the method that's presenting a problem.****
public String getWinner()
{
String winner = "";
// To check who has the highest votes.
int highestVotes = 0;
Set<String> uniqueSet = new HashSet<String>(ballots);
for (String temp : uniqueSet)
{
// The count of each Candidate's votes.
int count = Collections.frequency(ballots, temp);
// The winner is the one with the highest votes.
if(count > highestVotes)
{
highestVotes = count;
winner = temp;
}
}
return winner;
}
public static void main(String[] args)
{
BallotBox ballotBox = new BallotBox();
System.out.println(ballotBox.getWinner());
}
}
Related
I have a text file and need to build a concordance out of it. I believe I need a method to update my line number and word count in my WordCount class, but I have trouble on how to do it. I know the method should be of type void since it just updates, and doesn't return any value. But I'm stuck on what to write. I've put a comment in the tester class on where I think this method should go. provided below are my tester, circularlist, and wordcount class. I appreciate any help on this, thanks.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Tester
{
public static final int WordsPerLine = 10;
public static void main() throws FileNotFoundException
{
//build then output hash table
HashTable ht = new HashTable();
System.out.println(ht.toString());
String word; //read from input file
WordCount wordToFind; //search for this in the bst
WordCount wordInTree; //found in the bst
//create generic BST, of WordCount here
BSTree<WordCount> t = new BSTree<WordCount>();
//want to read word at a time from input file
Scanner wordsIn = new Scanner(new File("Hamlet.txt"));
wordsIn.useDelimiter("[^A-Za-z']+");
int wordCount = 0;
int lineNum = 1;
System.out.printf("%3d: ", lineNum);
while (wordsIn.hasNext()) {
word = wordsIn.next();
++wordCount;
System.out.print(word + " ");
word = word.toLowerCase();
if(t.find(new WordCount(word)) != null){
wordToFind= new WordCount(word);
wordInTree= t.find(wordToFind);
//I need to have a method here that update word count and line number
}
if (wordCount % WordsPerLine == 0) {
++lineNum;
System.out.printf("\n%3d: ", lineNum);
}
}
//EOF
System.out.println();
//print bst in alpha order
System.out.println(t.toString());
}
}
public class WordCount implements Comparable<WordCount>
{
protected String word;
protected int count;
protected CircularList lineNums;
//required for class to compile
public int compareTo(WordCount other)
{
return word.compareTo(other.word);
}
{
word = "";
count = 0;
lineNums= new CircularList();
}
public WordCount(String w)
{
word = w;
count = 0;
lineNums= new CircularList();
}
public String toString()
{
return String.format("%-12s %3d %3d", word, count, lineNums);
}
}
public class CircularList
{
private Item list;
public CircularList()
{
list = null;
}
public Boolean isEmpty()
{
return list == null;
}
public void append(int x)
{
Item r = new Item(x);
if (isEmpty()) {
r.next = r;
}
else {
r.next = list.next;
list.next = r;
}
list = r;
}
public int nextLine(int x)
{
Item r= new Item(x);
if (!isEmpty()) {
r = list.next;
while (r != list) {
r = r.next;
}
//append last item
}
return r.info;
}
public String toString()
{
StringBuilder s = new StringBuilder("");
if (!isEmpty()) {
Item r = list.next;
while (r != list) {
s.append(r.info + ", ");
r = r.next;
}
//append last item
s.append(r.info);
}
return s.toString();
}
}
Instead, I suggest you focus now on putting WordCount objects into the bst. Than you'll have something that will print out.
So, to put WordCount objects into the bst, in pseudocode, I suggest doing:
create a new WordCount object to find. Set this to the word, count of 1, for lineNums create a new circular list object and use CL::append() to add the lineNum to it
try to find this in the tree
if word is found in the tree
//I need to have a method here that update word count and line number <- don't worry about this bit until you've got words into the tree
else // word is not found in bst, so insert it
use insertBST() to insert the new WordCount object into the tree
Once you get some data into the tree, then it will print out after the wordsIn.hasNext() while loop, at the t.toString().
I have written this code but it shows Time Limit Exceeded. How can I make this fast?
import java.util.*;
public class Palin{
public static void main(String ar[]){
Scanner input = new Scanner(System.in);
String s = input.next();
for(int i = 1 ;i < s.length() ; i++){
if(!(s.substring(0,i).equals(new StringBuilder(s.substring(0,i)).reverse().toString()))){
System.out.print(s.substring(0,i).length());
}
}
}
}
See this code
It has methods to find
All possible substrings of various lengths
Longest Non Palindrome substring
Longest Palindrome substring (using lambdas)
The third one was provided to show how to solve the problem using lambdas
Junit test cases follow at the bottom
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collector;
import java.util.stream.Collectors;
public class MyStrings {
private String s;
public MyStrings(String s) {
super();
if(s==null||s.trim().length()==0) s="";
this.s = s;
}
public Set<String> getAllSubStrings() {
Set<String> list=new HashSet();
for (int i=0, m=s.length()-1,n=m+1 ;i<=m;i++) {
for (int j=i+1;j<=n;j++)
list.add(s.substring(i, j));
}
return list;
}
public String getLongestPalindromeSubstr(boolean excludeOriginal) {
Set<String> subs = this.getAllSubStrings();
//if original string to be not considered then remove it from the set
if (excludeOriginal)
subs.remove(s);
if(s.isEmpty())
return "";
return subs.stream()
.filter(s-> new StringBuilder(s).reverse().toString().equals(s))
.sorted((s1,s2)-> {//sorted in descending order of string length
if (s1.length()<s2.length()) return 1;
if (s1.length()==s2.length()) return 0;
return -1;
})
.findFirst()
.get(); //return the biggest palindrome substring
/*
Set<String> subs =this.getAllSubStrings();
System.out.println(subs);
List<String> palindromSubStrings = subs.stream()
.filter(s-> new StringBuilder(s).reverse().toString().equals(s))
.sorted((s1,s2)-> {
//System.out.println("comparing ["+s1+"],["+s2+"]");
if (s1.length()<s2.length()) return 1;
if (s1.length()==s2.length()) return 0;
return -1;
}) //sorted in descending order
.collect(Collectors.toList());
System.out.println("palindromSubStrings"+palindromSubStrings);
return palindromSubStrings.stream().
findFirst().get();
*/
}
public String getLongestNonPalindromeSubstr(boolean excludeOriginal) {
Set<String> subs =this.getAllSubStrings();
Set<String> nonPalindromes = new HashSet();
for (String str:subs) {
if (! new StringBuilder(str).reverse().toString().equals(str))
nonPalindromes.add(str); //remove
}
//if original string to be not considered then remove it from the set
if (excludeOriginal)
nonPalindromes.remove(s);
System.out.println("Non Palindromes with parent excluded="+excludeOriginal+" is "+nonPalindromes);
if (nonPalindromes.isEmpty())return "";
String longest="";
for (String str:nonPalindromes)
if(str.length()>=longest.length()) longest=str;
return longest;//one of the longest if the set has abc, def, ghi then any one will be returned
}
}
------JUnit test case methods---------
#Test
public void testAllPossibleSubStrings () {
Map<String,String[]> d = new LinkedHashMap(); //data
d.put("a", new String[]{"a"});
d.put("aa", new String[]{"a","aa"});
d.put("ab", new String[]{"a","b","ab"});
d.put("abc", new String[]{"a","ab","abc","b","bc"});
d.put("abcd", new String[]{"a","ab","abc","abcd","b","bc","bcd","c","cd"});
d.keySet().forEach(k-> {
MyStrings s = new MyStrings(k);
Set<String> allSubStrings = s.getAllSubStrings();
//System.out.println(k+"->"+allSubStrings);
assertTrue(allSubStrings.containsAll(Arrays.asList(d.get(k))));
});
}
#Test
public void longestPalindromeSubstring() {
System.out.println("largestPalindromeSubstring");
Map<String,Integer> d = new LinkedHashMap(); //data
d.put("a", 1);
d.put("ab", 1);
d.put("abc", 1);
d.put("abcc", 2);
d.put("abcdcb", 5);//"bcdcb");
d.put("abcbabcd",5);
d.put("abc-cbad-dabc-aa",11);
d.keySet().forEach(k-> {
System.out.println("==========="+k+"===================");
MyStrings s = new MyStrings(k);
boolean excludeOriginal = false;
String longestPalin = s.getLongestPalindromeSubstr(excludeOriginal);
System.out.println("biggestPalinSubstr("+k+")="+longestPalin);
assertEquals(longestPalin.length(),(int)d.get(k));
});
}
#Test
public void longestNonPalindromeSubString() {
System.out.println("getLongestNonPalindromeSubString");
Map<String,Integer> d = new LinkedHashMap(); //data
d.put("a", 0);
d.put("ab", 2);
d.put("abc", 3);
d.put("abcc", 4);
d.put("abcdcb", 6);//"bcdcb");
d.put("abcbabcd",8);
d.put("abc-cbad-dabc-aa",16);
d.keySet().forEach(k-> {
System.out.println("==========="+k+"===================");
MyStrings s = new MyStrings(k);
boolean excludeOriginal = false;
String longestNonPalin = s.getLongestNonPalindromeSubstr(excludeOriginal);
System.out.println("longestNonPalin ("+k+")="+longestNonPalin );
assertEquals(longestNonPalin.length(),(int)d.get(k));
});
}
#Test
public void longestNonPalindromeSubString2() {
System.out.println("getLongestNonPalindromeSubString");
Map<String,Integer> d = new LinkedHashMap(); //data
d.put("a", 0);
d.put("ab", 0); //a,b are palindromes ab is excluded return
d.put("abc", 2); //a,b,c,abc are excluded
d.put("abcc", 3);
d.put("abcdcb", 5);//"bcdcb");
d.put("abcbabcd",7);
d.put("abc-cbad-dabc-aa",15);
d.keySet().forEach(k-> {
System.out.println("==========="+k+"===================");
MyStrings s = new MyStrings(k);
boolean excludeOriginal = true;
String longestNonPalin = s.getLongestNonPalindromeSubstr(excludeOriginal);
System.out.println("longestNonPalin2 ("+k+")="+longestNonPalin );
assertEquals((int)d.get(k),longestNonPalin.length());
});
}
This looks fine to me.
import java.util.*;
public class StackOverFlow{
public static void main(String ar[]){
Scanner input = new Scanner(System.in);
String s = input.next();
int length = 0;
for(int i = 1 ;i <= s.length() ; i++){
if(!(s.substring(0,i).equals(new StringBuilder(s.substring(0,i)).reverse().toString()))){
length = s.substring(0,i).length();
}
}
System.out.println(length);
}
}
import java.util.HashMap;
public class StudentDatabase {
private HashMap<String, int[]> quizmarks;
public static final int NUM_QUIZZES = 10;
public static final int MIN_GRADE = 0;
public static final int MAX_GRADE = 100;
public StudentDatabase(){
quizmarks = new HashMap<String, int[]>();
}
public String formatName(String name){
String caps = "";
String lowercase = "";
if(name != null && name.length() > 0){
caps = name.substring(0,1).toUpperCase();
}
if(name.length() > 1){
lowercase = name.substring(1).toLowerCase();
}
return caps + lowercase;
}
public void addStudent(String studentName){
if(studentName != null){
int[] marks = new int[NUM_QUIZZES];
quizmarks.put(formatName(studentName), marks);
}
}
public int[] getQuizzes(String student){
if(student != null){
System.out.println(quizmarks.get(student));
}
return null;
}
public void changeQuizMark
(String studentName, int whichQuiz, int newMark){
if(studentName!= null){
quizmarks.get(studentName);
}
if(whichQuiz <= NUM_QUIZZES){
quizmarks.get(whichQuiz);
}
if(newMark > MIN_GRADE && newMark < MAX_GRADE){
}
quizmarks.put(studentName, new int[]{newMark});
}
}
For some reason Arrays were not fully taught to us and we have been encouraged to go online to get help with it so i'm trying to figure out first of all why its saying in the addStudents method that it "cannot convert an int to an int[]" when i'm pretty sure both sides are int[] arrays when i'm trying to assign "marks".
I'm also unsure, because I can't get past this error, how my changeQuiz, and newMarks fields are actually going to assign to the right part of the array. Each student should have an array of ten quizmarks basically. And i'm insanely stuck.
I apologize i'm trying to work on the formatting but its only my second time here and I completely forget how to format, its giving me major issues and i'm trying to follow the instructions as best as I can.
Your main mistake is here:
quizmarks.put(studentName, new int[]{newMark})
You don't add new mark to already existed array of marks but create a new array with only new mark therefore deleting an old marks array. All you need is to get array you need and modify its element by index. Also made few minor improvements:
import java.util.Arrays;
import java.util.HashMap;
public class StudentDatabase {
private HashMap<String, int[]> quizmarks;
public static final int NUM_QUIZZES = 10;
public static final int MIN_GRADE = 0;
public static final int MAX_GRADE = 100;
public StudentDatabase() {
quizmarks = new HashMap<>();
}
private String formatName(String name) {
String caps = "";
String lowercase = "";
if (name != null && name.length() > 0) {
caps = name.substring(0, 1).toUpperCase();
}
if (name.length() > 1) {
lowercase = name.substring(1).toLowerCase();
}
return caps + lowercase;
}
public void addStudent(String studentName) {
if (studentName != null) {
int[] marks = new int[NUM_QUIZZES];
quizmarks.put(formatName(studentName), marks);
}
}
public void showQuizzes(String student) {
System.out.println(Arrays.toString(quizmarks.get(student)));
}
public void changeQuizMark(String studentName, int whichQuiz, int newMark) {
if (whichQuiz < NUM_QUIZZES && newMark >= MIN_GRADE && newMark =< MAX_GRADE) {
quizmarks.get(studentName)[whichQuiz] = newMark;
}
}
}
My code is:
public class Main{
public static void main(String[] args){
WordGroup wordgroupOne= new WordGroup ("You can discover more about a person in an hour of play than in a year of conversation");
WordGroup wordgroupTwo= new WordGroup ( "When you play play hard when you work dont play at all");
String[] quoteOne = wordgroupOne.getWordArray();
String[] quoteTwo = wordgroupTwo.getWordArray();
for (String words : quoteOne){
System.out.println(words);
}
for (String words : quoteTwo){
System.out.println(words);
}
}
}
WordGroup class:
import java.util.HashSet;
import java.util.HashMap;
public class WordGroup {
public String words;
public WordGroup (String getWords){
words = getWords.toLowerCase();
}
public String[] getWordArray(){
return words.split(" ");
}
public HashSet<String> getWordSet(){
HashSet<String> set = new HashSet<String>();
String[] p = getWordArray();
for (String items : p){
set.add(items);
}
System.out.println(set);
return set;
}
public HashMap<String, Integer> getWordCounts() {
HashMap<String, Integer> map = new HashMap<String, Integer>();
String[] q = getWordArray();
for (String stuff : q) {
Integer oldVal = map.get(stuff);
if (oldVal == null){
oldVal = 0;
}
map.put(stuff, oldVal+1);
}
System.out.println(map);
return map;
}
}
What I am trying to do is use the getWordSet() method using the two WordGroups and
iterate or loop over the HashSet returned and print the words from it.
Call getWordCounts() on the two WordGroups. Use keySet() to retrieve the set of keys. Loop over this set and print out the word and its count for both WordGroups.
Use the getWordSet() method to make complete set of all the words from both WordGroups.
Loop over the new HashSet to print a complete list of all words with the sum counts from each of the hashmaps.
I am struggling with all of these. Any help is much appreciated!!
If you want to create a combined list or set, you will have to merge the lists together and the maps together. I leave that exercise to you.
public static void main(String[] args)
{
WordGroup wg1 = new WordGroup(
"You can discover more about a person in an hour of play than in a year of conversation");
WordGroup wg2 = new WordGroup(
"When you play play hard when you work dont play at all");
wg1.processWord();
// iterate through all the distinct words
Set<String> dw1 = wg1.getDistinctWords();
for (String s : dw1)
{
System.out.println(s);
}
// use map entry to iterate through the entry set
Map<String, Integer> wc1 = wg1.getWordCounts();
for (Map.Entry<String, Integer> entry : wc1.entrySet())
{
if (entry != null)
{
// use stringbuilder to build a temp string
// instead of using +
StringBuilder sb = new StringBuilder();
sb.append(entry.getKey());
sb.append(": ");
sb.append(entry.getValue());
System.out.println(sb);
}
}
}
public class WordGroup
{
// as a class, made the results of the process private
private String originalWord;
// we declare generic versions of the Collections, instead of the specific
// implementation
private Set<String> distinctWords;
private Map<String, Integer> wordCounts;
public WordGroup(String s)
{
this.originalWord = s;
// here we declare and initialize the specific implementation
this.distinctWords = new HashSet<String>();
this.wordCounts = new HashMap<String, Integer>();
}
public void processWord()
{
List<String> toProcess = getWordList();
if (toProcess != null && !toProcess.isEmpty())
{
for (String s : toProcess)
{
// the set will automatically figure out if it should be in the
// set or not.
this.distinctWords.add(s);
// call the update or insert method
upsertString(s);
}
}
}
// this splits the string into a list
// you could probably use a utility class from guava or something to do this
// but i have coded a naive version
private List<String> getWordList()
{
List<String> splitList = new ArrayList<String>();
// check to see if there is anything there
if (this.originalWord != null && !this.originalWord.isEmpty())
{
String lowered = this.originalWord.toLowerCase();
String[] splits = lowered.split(" ");
if (splits != null)
{
int iSize = splits.length;
if (iSize > 0)
{
// basically create a string
for (int i = 0; i < iSize; i++)
{
splitList.add(splits[i]);
}
}
}
}
return splitList;
}
// helper method to see if we need to add to the count
private void upsertString(String s)
{
if (s != null && !s.isEmpty())
{
if (this.wordCounts != null)
{
// default to 1, if its an insert
Integer newCount = 1;
// if it already exists we want to update
if (this.wordCounts.containsKey(s))
{
Integer currentCount = this.wordCounts.get(s);
if (currentCount != null)
{
// update the count by 1
newCount += currentCount;
}
}
// insert the new item
// or overwrite, because it is the same key to the new count
this.wordCounts.put(s, newCount);
}
}
}
public String getOriginalWord()
{
return this.originalWord;
}
public void setOriginalWord(String originalWord)
{
this.originalWord = originalWord;
}
public Set<String> getDistinctWords()
{
return this.distinctWords;
}
public void setDistinctWords(Set<String> distinctWords)
{
this.distinctWords = distinctWords;
}
public Map<String, Integer> getWordCounts()
{
return this.wordCounts;
}
public void setWordCounts(Map<String, Integer> wordCounts)
{
this.wordCounts = wordCounts;
}
}
I am stuck on this part where it does not write to an output file
the first class is contact I had to modify this is not my class is the authors class
I just had to use it
//********************************************************************
// Contact.java Author: Lewis/Loftus
//
// Represents a phone contact.
//********************************************************************
public class Contact implements Comparable
{
private String firstName, lastName, phone;
//-----------------------------------------------------------------
// Constructor: Sets up this contact with the specified data.
//-----------------------------------------------------------------
public Contact (String first, String last, String telephone)
{
firstName = first;
lastName = last;
phone = telephone;
}
//-----------------------------------------------------------------
// Returns a description of this contact as a string.
//-----------------------------------------------------------------
public String toString ()
{
return lastName + ", " + firstName + "\t" + phone;
}
//-----------------------------------------------------------------
// Returns true if the first and last names of this contact match
// those of the parameter.
//-----------------------------------------------------------------
public boolean equals (Object other)
{
return (lastName.equals(((Contact)other).getLastName()) &&
firstName.equals(((Contact)other).getFirstName()));
}
//-----------------------------------------------------------------
// Uses both last and first names to determine ordering.
//-----------------------------------------------------------------
public int compareTo (Object other)
{
int result;
String otherFirst = ((Contact)other).getFirstName();
String otherLast = ((Contact)other).getLastName();
if (lastName.equals(otherLast))
result = firstName.compareTo(otherFirst);
else
result = lastName.compareTo(otherLast);
return result;
}
//-----------------------------------------------------------------
// First name accessor.
//-----------------------------------------------------------------
public String getFirstName ()
{
return firstName;
}
//-----------------------------------------------------------------
// Last name accessor.
//-----------------------------------------------------------------
public String getLastName ()
{
return lastName;
}
}
this class oes the sorting this is fine. it does the sorting no prblem
public class Sorting {
public static void bubbleSortRecursive(Comparable[] data, int n)
{
if (n < 2)
{
return;
}
else
{
int lastIndex = n - 1;
for (int i = 0; i < lastIndex; i++)
{
if (data[i].compareTo(data[i + 1]) > 0)
{ //swap check
Comparable tmp = data[i];
data[i] = data[i + 1];
data[i + 1] = tmp;
}
}
bubbleSortRecursive(data, lastIndex);
}
}
public static void selectionSortRecursive(Comparable[] data, int n)
{
if (n < 2)
{
return;
}
else
{
int lastIndex = n - 1;
int largestIndex = lastIndex;
for (int i = 0; i < lastIndex; i++)
{
if (data[i].compareTo(data[largestIndex]) > 0)
{
largestIndex = i;
}
}
if (largestIndex != lastIndex)
{ //swap check
Comparable tmp = data[lastIndex];
data[lastIndex] = data[largestIndex];
data[largestIndex] = tmp;
}
selectionSortRecursive(data, n - 1);
}
}
}
this is the part I need help with. It is not outputing to he p4output.txt, i dont know what the problem is.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class TestProject4 {
public static void main(String[] args)
{
doBubbleSortRecursive();
System.out.println();
System.out.println();
doSelectionSortRecursive();
}
private static void doBubbleSortRecursive()
{
Contact[] contacts = createContacts();
System.out.println("Before bubbleSortRecursive(): ");
for (int i=0; i<contacts.length; i++)
System.out.println(contacts[i].toString());
Sorting.bubbleSortRecursive(contacts, contacts.length);
System.out.println("\nAfter bubbleSortRecursive(): ");
for (int i=0; i<contacts.length; i++)
System.out.println(contacts[i].toString());
}
private static void doSelectionSortRecursive()
{
Contact[] contacts = createContacts();
System.out.println("Before selectionSortRecursive(): ");
for (int i=0; i<contacts.length; i++)
System.out.println(contacts[i].toString());
Sorting.selectionSortRecursive(contacts, contacts.length);
System.out.println("\nAfter selectionSortRecursive(): ");
for (int i=0; i<contacts.length; i++)
System.out.println(contacts[i].toString());
}
private static void printContacts(Contact[] contacts)
{
try
{
// this part I need help with it is not outputing in the text file
File file = new File("p4output.txt");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
for (Contact contact : contacts)
{
bw.write(contact.toString());
}
bw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println("\t" + contacts);
}
public static Contact[] createContacts()
{
return new Contact[]
{
new Contact("John" , "Smith" , "610-555-7384"),
new Contact("Sarah" , "Barnes" , "215-555-3827"),
new Contact("Mark" , "Riley", "333-333-3333"),
new Contact("Laura" , "Getz" ,"663-555-3984"),
new Contact("Larry" , "Smith" , "464-555-3489"),
new Contact("Frank" , "Phelps" , "322-555-2284"),
new Contact("Mario" , "Guzman" , "804-555-9066"),
new Contact("Marsha" , "Grant" , "243-555-2837"),
};
}
}
According to Eclipse, you never call/use printContacts(Contact[] contacts); method
Your printContacts(Contact[] contacts); contains the statements to write a file.
You don't appear to call the function printContacts() in your program. Try calling it after you do your contact creation and sorting.
It might look like this:
public static void main(String[] args)
{
doBubbleSortRecursive();
System.out.println();
System.out.println();
doSelectionSortRecursive();
printContacts(contactArray);//inserted code
}
Also, when you call your sorting methods, doSelectionSortRecursive(), you don't return the list of contacts. Make a return statement for it and then put the contact array into your printContacts function.
Here's an example:
public static void main(String[] args)
{
doBubbleSortRecursive();
System.out.println();
System.out.println();
Contact[] contacts = doSelectionSortRecursive();
printContacts(contacts);
}
public static Contact[] doSelectionSortRecursive(){
Contact[] contacts = createContacts();
//your sorting code
return contacts;
}
Using this method allows you to get the array of contacts from the method once it has been sorted.