How can I make array of bowlers? - java

Following is the question which I am trying to solve-
In a one day international, the bowling figures of all the bowlers have been provided. The objective is to create an array of Bowler and return it. Note that the objects should appear in the same order in the array as they appear in the input.
The input is provided a string. The string has space demarcated details of each bowler provided as Name-Overs-Maiden-Runs-Wickets, like , “Zaheer-10-1-55-0 Harbhajan-8.4-0-44-2 Ishant-10-0-71-1″.Define a function that takes and prints the array of Bowler returned.
There is some error in the code but I am unable to detect it.
public class MakeArrayOfBowlers{
String name;
double over;
int maiden;
int runs;
int wickets;
public MakeArrayOfBowlers(String input){
String[] str=input.split("-");
this.name=str[0];
this.over=Double.parseDouble(str[1]);
this.maiden=Integer.parseInt(str[2]);
this.runs=Integer.parseInt(str[3]);
this.wickets=Integer.parseInt(str[4]);
}
public MakeArrayOfBowlers[] makeBowlers (String input){
MakeArrayOfBowlers str= (MakeArrayOfBowlers) new MakeArrayOfBowlers("Zaheer-10-1-55-0 Harbhajan-8.4-0-44-2 Ishant-10-0-71-1");
String[] str1 = input.split(" ");
MakeArrayOfBowlers bowler[]= new MakeArrayOfBowlers[str1.length];
for(int i = 0; i < str1.length; i++){
bowler = new MakeArrayOfBowlers[str1.length];
MakeArrayOfBowlers obj = new MakeArrayOfBowlers(str1[i]);
bowler[i] = obj;
}
return bowler;
}
}

You should make a own class bowler (constructor should be better but its your example ;)):
public class Bowler {
private String name;
private double over;
private int maiden;
private int runs;
private int wickets;
public Bowler(String input){
String[] str=input.split("-");
this.name=str[0];
this.over=Double.parseDouble(str[1]);
this.maiden=Integer.parseInt(str[2]);
this.runs=Integer.parseInt(str[3]);
this.wickets=Integer.parseInt(str[4]);
}
public String getName() {
return name;
}
public double getOver() {
return over;
}
public int getMaiden() {
return maiden;
}
public int getRuns() {
return runs;
}
public int getWickets() {
return wickets;
}
}
Than split your string and add it for every bowler:
public class MakeArrayOfBowlers {
public static Bowler[] makeBowlers(String input) {
String[] splitArray = input.split(" ");
Bowler[] bowler = new Bowler[splitArray.length];
for (int i = 0; i < splitArray.length; i++) {
bowler[i] = new Bowler(splitArray[i]);
}
return bowler;
}
public static void main(String[] args) {
Bowler[] bowlers = makeBowlers("Zaheer-10-1-55-0 Harbhajan-8.4-0-44-2 Ishant-10-0-71-1");
for (Bowler bowler : bowlers) {
System.out.println(bowler.getName()+"-"+bowler.getOver()+"-"+bowler.getMaiden()+"-"+bowler.getRuns()+"-"+bowler.getWickets());
}
}
}

You're re-initializing the bowler array inside the for-loop. Try removing that line (the first line inside your loop).

public MakeArrayOfBowlers[] makeBowlers (String input){
String[] str1 = input.split(" ");
MakeArrayOfBowlers bowlers[]= new MakeArrayOfBowlers[str1.length];
for(int i = 0; i < str1.length; i++){
MakeArrayOfBowler bowler = new MakeArrayOfBowlers(str1[i]);
bowlers[i] = obj;
}
return bowlers;
}
From your main function call
MakeArrayOfBowlers o = new MakeArrayOfBowlers();
MakeArrayOfBowlers[] b = o.makeBowlers("Zaheer-10-1-55-0 Harbhajan-8.4-0-44-2 Ishant-10-0-71-1");

Related

ArrayIndexOutOfBoundsException when repeatedly removing and creating objects [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
I am building the object with the classical Nim game, and there are some methods dealing with the player data. I bumped into this problem when testing my code, and couldn't figure it out.
This problem appeared when I add a player in an array, removing it after. Then, adding a player again. It showed: Index 1 out of bounds for length 1. What I've tried is to filter the null position when I remove the player data.
Any help is highly appreciated. And thank you all for the patience and time solving it!
The code is a little bit longer, but related.
Here is the related code from class Nimsys, main method.
public static void addPlayer(String [] name) {
if (name != null && name.length == 3) {
for (int i = 0; i < NimPlayer.getCounter(); i++) {
String userCheck = NimPlayer.getPlayer()[i].getUserName();
if (userCheck.contains(name[0])) {
System.out.println("The player already exists.\n");// Test if player has been created
return;
}
}
NimPlayer.createPlayer(name[0], name[1], name[2]);
System.out.println("The player has been created.");
return;
}
System.out.println("Not Valid! Please enter again!");
}
public static void searchAndRemovePlayer(String user) {
NimPlayer [] playerList = NimPlayer.getPlayer();
for (int i = 0; i < playerList.length; i++) {
String userName =playerList[i].getUserName().trim();
if (userName.equals(user)) {
playerList[i] = null;
System.out.println("Remove successfully!");
NimPlayer.setPlayerList(playerList);
return;
}
}
System.out.println("The player does not exist.\n");
}
public static void main(String[] args) {
System.out.println("Welcome to Nim\n");
//Scanner in = new Scanner(System.in);
while (true) {
System.out.print('$');
String commandin = in.next();
if (commandin.equals("addplayer")) {
String inputName = in.nextLine();
String[] name = splitName(inputName);
addPlayer(name);
}
if (commandin.equals("removeplayer")) {
String user = in.nextLine().trim();
if (user.equals("")) {
System.out.println("Are you sure you want to remove all players? (y/n)");
commandin = in.next();
if (commandin.equals("y")) {
NimPlayer [] playerList = NimPlayer.getPlayer();
for (int i = 0; i < playerList.length; i++) {
playerList[i] = null;
NimPlayer.setPlayerList(playerList);
}
System.out.println("Remove all the players\n");
Arrays.stream(NimPlayer.getPlayer()).filter(Objects::nonNull).toArray();
}
}
if (!user.equals("")) {
searchAndRemovePlayer(user);
Arrays.stream(NimPlayer.getPlayer()).filter(Objects::nonNull).toArray();
}
}
Here is part of my NimPlayer class:
public class NimPlayer {
private String userName;
private String familyName;
private String givenName;
private int score;
private int gamePlayed;
private static int counter;
private static final int SIZE = 10;
private static NimPlayer[] playerList = new NimPlayer[SIZE]; // set an array here
//define NimPlayer data type
public NimPlayer(String userName, String surName, String givenName) {
this.userName = userName;
this.familyName = surName;
this.givenName = givenName;
}
// create new data using NimPlayer data type
public static void createPlayer(String userName, String familyName, String givenName) {
if (counter < SIZE) {
playerList[counter++] = new NimPlayer(userName, familyName, givenName);
} else {
System.out.println("Cannot add more players.");
}
}
public static int getCounter() {
return counter;
}
public static NimPlayer [] getPlayer() {
NimPlayer[] nimPlayers = Arrays.stream(playerList).filter(Objects::nonNull).toArray(NimPlayer[]::new);
counter = nimPlayers.length; //update the counter
return nimPlayers;
}
public static void setPlayerList(NimPlayer [] newplayerList) {
NimPlayer.playerList = newplayerList;
1. Replace
if (commandin.equals("removeplayer")) {
String user = in.nextLine().trim();
if (user.equals("")) {
System.out.println("Are you sure you want to remove all players? (y/n)");
commandin = in.next();
if (commandin.equals("y")) {
NimPlayer [] playerList = NimPlayer.getPlayer();
for (int i = 0; i < playerList.length; i++) {
playerList[i] = null;
NimPlayer.setPlayerList(playerList);
}
System.out.println("Remove all the players\n");
Arrays.stream(NimPlayer.getPlayer()).filter(Objects::nonNull).toArray();
}
}
if (!user.equals("")) {
searchAndRemovePlayer(user);
Arrays.stream(NimPlayer.getPlayer()).filter(Objects::nonNull).toArray();
}
}
with
if (commandin.equals("removeplayer")) {
String user = in.nextLine().trim();
if (user.isEmpty()) {
System.out.println("Are you sure you want to remove all players? (y/n)");
commandin = in.nextLine();
if (commandin.equalsIgnoreCase("y")) {
NimPlayer [] playerList = NimPlayer.getPlayer();
for (int i = 0; i < playerList.length; i++) {
NimPlayer.removePlayer(playerList[i]);
}
System.out.println("Removed all the players\n");
}
} else {
searchAndRemovePlayer(user);
}
}
2. Change the following methods as given below:
public static void searchAndRemovePlayer(String user) {
NimPlayer[] playerList = NimPlayer.getPlayerList();
for (int i = 0; i < playerList.length; i++) {
String userName = playerList[i].getUserName().trim();
if (userName.equals(user)) {
NimPlayer.removePlayer(playerList[i]);
System.out.println("The player, " + user + " removed successfully!");
return;
}
}
System.out.println("The player, " + user + " does not exist.\n");
}
public static NimPlayer [] getPlayer() {
return Arrays.stream(playerList).filter(Objects::nonNull).toArray(NimPlayer[]::new);
}
2. Instead of exposing the playerList to be set from outside, you should remove its public setter and create public static void removePlayer similar to public static void createPlayer as follows:
public static void removePlayer(NimPlayer player) {
int i;
for (i = 0; i < playerList.length; i++) {
if (playerList[i] != null && playerList[i].getUserName().equals(player.getUserName())) {
break;
}
}
for (int j = i; j < playerList.length - 1; j++) {
playerList[j] = playerList[j + 1];
}
counter--;
}
Important note: Never put setting operation within getter, the way you have done in your method, getPlayer().
You need to use Iterator and call remove() on iterator instead of assigning to null.
Duplicate from: Removing items from a list
You shouldn't do a "playerList[i] = null;" for removing a player. Use an ArrayList instead and use the ArrayList's .remove method to remove a player. don't keep track of counter variables.

How to split a string sequence and convert each element to a double

I am stuck on a problem for my programming class. We need to separate the argument String at the commas to produce an array of Strings, then it needs to parse each individual String to get a double, storing these doubles in sequence. We are also given some test code, with input arguments like ("1,5").
Here is my current code
public class Sequence
{
private double[] sequence;
public Sequence(String s)
{
String[] res = s.split(",");
int length = res.length;
double[] result = new double[length];
for ( int i =0; i<length; i++) {
result[i] = Double.parseDouble(res[i])
}
}
Im not sure where to go from here because when i test my code, it dosent give the expected result. What does it mean by store in sequence ?
I have updated my answer, this might be what you are looking for:
import java.util.Arrays;
public class Four {
public static void main(String[] args) {
String string = "1,2,10,4,9";
System.out.println(string);
double[] ds = getDouble(string);
for (int i = 0; i < ds.length; i++) {
System.out.println(ds[i]);
}
}
private static double[] getDouble(String string) {
double[] _double;
String[] _Strings = string.split(",");
_double = new double[_Strings.length];
for (int i = 0; i < _Strings.length; i++) {
_double[i] = Double.parseDouble(_Strings[i]);
}
Arrays.sort(_double);
return _double;
}
}
out put
I would do it this way:
public class Sequence {
private double[] sequence;
public void createSequence(int sequenceLength) {
sequence = new double[sequenceLength];
}
public void addToSequence(int index, double value) {
sequence[index] = value;
}
public double parseDouble(String s) {
return Double.parseDouble(s);
}
public String[] splitString(String s) {
return s.split(",");
}
#Override
public String toString() {
return Arrays.toString(sequence);
}
public static void main(String[] args) {
String str = "10.10,20.20,30.30";
Sequence sequence = new Sequence();
String[] splitted = sequence.splitString(str);
sequence.createSequence(splitted.length);
for (int i = 0; i < splitted.length; i++) {
double doubleValue = sequence.parseDouble(splitted[i]);
sequence.addToSequence(i, doubleValue);
}
System.out.println(sequence);
}
}
change private double[] sequence; to private Double[] sequence;
and use below code
public class Sequence {
private Double[] sequence;
public Sequence(String s) {
String separated[] = s.replace(" ", "").split(",");
ArrayList<Double> list = new ArrayList<>();
for (String num : separated) {
list.add(Double.parseDouble(num));
}
this.sequence = list.toArray(new Double[separated.length]);
}
}

How to print the first 10 lines from an enhanced for loop

I have a file with over 1000 names it also include the sex and how many people have the name.
example
Sarah F 2000
I am trying to print the first 10 lines that was created from my for loop, but for some reason what i tried is only printing the last line 10 times.
import java.util.*;
import java.io.*;
import java.util.Collections;
public class NameYear
{
private String year;
ArrayList<OneName> oneName = new ArrayList<OneName>();
public NameYear(String year)
{
String line = "";
String Top = "";
Scanner sc = null;
try
{
sc = new Scanner(new File
("/home/mathcs/courses/cs225/koch/names/yob"+year+".txt"));
}
catch (Exception e)
{
System.out.println("Error Year should be between 1880 and 2013 not "+ year);
System.exit(1);
}
while(sc.hasNextLine())
{
// read a line from the input file via sc into line
line = sc.nextLine();
StringTokenizer stk = new StringTokenizer(line, ",");
String name = stk.nextToken();
char sex = stk.nextToken().charAt(0);
int count = Integer.parseInt(stk.nextToken());
OneName list = new OneName(name, sex, count);
oneName.add(list);
}
for (int i = 0 ; i < 10; i++)
{
System.out.println(descending());
}
public String descending()
{
String x = "";
Collections.sort(oneName, new OneNameCountCompare());
for(OneName b: oneName)
{
x = b.toString();
}
return x;
OneName file
public class OneName
{
private String Name;
private char Sex;
private int Count;
public OneName(String name, char sex, int count)
{
Name = name;
Sex = sex;
Count = count;
}
public String getName()
{
return Name;
}
public char getSex()
{
return Sex;
}
public int getCount()
{
return Count;
}
public void setName(String name)
{
if (name.length() < 1)
{
throw new NullPointerException("Baby name is missing");
}
Name = name;
}
private char M;
private char F;
public void setSex(char sex)
{
if( sex != M)
{
if(sex != F)
{
throw new IllegalArgumentException("Sex has to be M or F");
}
}
Sex = sex;
}
public void setCount(int count)
{
if(count < 0)
{
throw new IllegalArgumentException("Count cant be negative");
}
Count = count;
}
public String toString()
{
return String.format("%s %c %d", Name, Sex, Count);
}
}
OneNameCount
import java.util.Comparator;
import java.util.Collections;
public class OneNameCountCompare implements Comparator<OneName>
{
public int compare(OneName b1, OneName b2)
{
if(b1.getCount() <b2.getCount())
{
return 1;
}
else
{
return -1;
}
}
}
Main Program
import java.io.*;
import java.util.*;
public class TopNames
{
public static void main(String args[])
{
String line = ""; // string var to hold entire line
if (args.length < 1)
{
System.out.println("\nYou forgot to put a Year on the command line.");
System.exit(1);
};
String inFile = args[0]; // file name off command line
String year = inFile;
NameYear list = new NameYear(year);
}
}
Your descending function returns one string, and always the same string (the last one in the order after sorting the collection). It doesn't matter how often you call it, if the data doesn't change, you'll always get back that same, last, string.
If you want the first 10 after sorting, descending would need to return a List<String> containing those 10:
public List<String> descending()
{
List<String> x = new ArrayList<String>(10);
Collections.sort(oneName, new OneNameCountCompare());
for(OneName b: oneName)
{
x.add(b.toString());
if (x.size() == 10) // Or don't use enhanced for, use an index instead
{
break;
}
}
return x;
}
Then when printing it, replace your for (int i = 0 ; i < 10; i++) loop with:
for (String s : descending())
{
System.out.println(s);
}
Your error is here:
for (int i = 0 ; i < 10; i++) {
System.out.println(descending());
}
public String descending() {
String x = "";
Collections.sort(oneName, new OneNameCountCompare());
for(OneName b: oneName) {
x = b.toString();
}
return x;
}
First of all in your for loop you are not using the i variable that is your count indicator. This means that the descending() method has no any awareness of i, how he could return something different?
Try to modify descending() in something like this:
public String descending(int i) {
String x = "";
Collections.sort(oneName, new OneNameCountCompare());
OneName b = oneName.get(i);
x = b.toString();
return x;
}

How to add items to arraylist and modify a feature

I am trying to add items to my array list with an action listener on a pop up window. You can see the action listener here. The problem that I am now having is I do not know how to add the inputs to my array list. Part of this problem is that I need to set my item number to 1 higher than the highest in my list. My array list is named as such:
private static ArrayList<InventoryItem> inventory = new ArrayList<>();
and the class for InventoryItem looks like this:
public class InventoryItem { //Delcare variables below
DecimalFormat formatted = new DecimalFormat("#,###.00");//set up decimal format for displaying 12.34 type values
String itemName;
int itemNumber;
public String getItemName() {
return itemName;
}
public int getItemNumber(){
return itemNumber;
}
int inStock;
double unitPrice;
double value;
double restockingFee;
double inventoryValue;
public InventoryItem(String itemName, int itemNumber, int inStock, double unitPrice) { //declare variables for this class
this.itemName = itemName;
this.itemNumber = itemNumber;
this.inStock = inStock;
this.unitPrice = unitPrice;
stockValue(); //call stock value
}
}
So my question is two parts. The first is how do I get my itemNumber to increment to 1 higher than the highest? Do I simply do a bubble sort to find the highest? And the second part is how do I get it to add all items, including this incremented itemNumber, into my original arraylist?
Note
If needed I can paste my code in it's entirety on pastebin as it is somewhat large.
EDIT: Per #Prabhakaran I have added some code and I am almost there. I have almost gotten this to work, however when I start to look through my list I do not see the added feature so how can I be sure that I am actually adding it?
String newItemName = String.valueOf(xField);
String text1 = yField.getText();
String newInventoryAmount = String.valueOf(text1);
int newNumber = Integer.parseInt(newInventoryAmount);
String text2 = zField.getText();
String newUnitPrice = String.valueOf(text2);
double newPrice = Double.parseDouble(newUnitPrice);
for (int i = 0; i >= inventory.size(); i++) {
inventory.get(inventory.size() ).getItemNumber();
int newItemNumber;
newItemNumber = i + 1;
InventoryItem item = new InventoryItem(newItemName, newItemNumber, newNumber, newPrice);
inventory.add(item);
What am I missing here? Shouldn't this simply add an item to my arraylist? I know it must be something really easy, I just can't seem to figure it out.
Here is my sort by ItemName:
static ArrayList sortInventory(ArrayList<InventoryItem> unsorted) {
ArrayList<InventoryItem> sorted = new ArrayList<>(); //create new array list to sort
InventoryItem alpha = null;
int lowestIndex = **-1**;
while (unsorted.size() > 0) { //while my unsorted array is less than 0 do the following
for (int i = 0; i < unsorted.size(); i++) { //increment through
if (alpha == null) {
alpha = unsorted.get(i); //get the next line in the inventoryItem array
lowestIndex = i;
} else if (unsorted.get(i).itemName.compareToIgnoreCase(alpha.itemName) < 0) { //compare items to determine which has a higher value
alpha = unsorted.get(i);
lowestIndex = i;
}
}
sorted.add(alpha); //reset the index so it will loop until there are no more items in the unsorted array
unsorted.remove(lowestIndex);
alpha = null;
lowestIndex = **0**;
}
return sorted; //return the sorted arraylist
}
EDIT: Corrected the lowestIndex and it goes good as gold.
Do like this
private static ArrayList<InventoryItem> inventory = new ArrayList<>();
String newItemName = String.valueOf(xField);
String newInventoryNumber = String.valueOf(yField);
int newNumber = Integer.parseInt(newInventoryNumber);
String newUnitPrice = String.valueOf(zField);
double newPrice = Double.parseDouble(newUnitPrice);
InventoryItem item =new InventoryItem(newItemName , newInventoryNumber , newNumber , newUnitPrice ) ;
inventory.add(item);
update
class SimpleComparator implements Comparator<InventoryItem> {
#Override
public int compare(InventoryItem o1, InventoryItem o2) {
return new Integer(o1.getItemNumber()).compareTo(o2.getItemNumber());
}
}
//Sorting based on the itemNumber.
Collections.sort(inventory,new SimpleComparator());
int newItemNumber = inventory.get(inventory.size() - 1).getItemNumber();
newItemNumber ++;
You could create your own ArrayList with Observer support:
public class InventoryItemArrayList extends ArrayList {
private static final long serialVersionUID = 4550719458611714650L;
private List listeners = new ArrayList();
public void addInventoryItemAddedListener(InventoryItemAddedListener listener) {
this.listeners.add(listener);
}
#Override
public boolean add(InventoryItem e) {
boolean add = super.add(e);
fireInventoryItemAdded(e);
return add;
}
private void fireInventoryItemAdded(InventoryItem e) {
for (InventoryItemAddedListener element : listeners) {
element.inventoryItemAdd(e);
}
}
#Override
public void add(int index, InventoryItem element) {
super.add(index, element);
fireInventoryItemAdded(element);
}
#Override
public boolean addAll(Collection c) {
boolean addAll = super.addAll(c);
fireInventoryItemAdded(c);
return addAll;
}
private void fireInventoryItemAdded(Collection c) {
for (InventoryItem inventoryItem : c) {
fireInventoryItemAdded(inventoryItem);
}
}
#Override
public boolean addAll(int index, Collection c) {
boolean addAll = super.addAll(index, c);
fireInventoryItemAdded(c);
return addAll;
}
}

Writing on an output file

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.

Categories