Hello I am solving this problem given to me where I have to find average salary of a person which has least index id
import java.util.*;
import java.io.*;
public class Main {
public static int processData(ArrayList<String> array) {
for (String elem :array){
System.out.println(elem);
}
return 0;
}
public static void main (String[] args) {
ArrayList<String> inputData = new ArrayList<String>();
try {
Scanner in = new Scanner(new BufferedReader(new FileReader("input.txt")));
while(in.hasNextLine()) {
String line = in.nextLine().trim();
if (!line.isEmpty()) // Ignore blank lines
inputData.add(line);
}
int retVal = processData(inputData);
PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
output.println("" + retVal);
output.close();
} catch (IOException e) {
System.out.println("IO error in input.txt or output.txt");
}
}
}
the program is accepting input from text file as follows
282, ij, 11, 1600000
273, cbg, 12, 800000
567, nj, 11, 800000
539, cb, 11, 600000
So the output will be
11 520000
I am able to print the elements from array list but not been able to access particular elements. Can anyone help me to access particular element which is, in this case, 11,160000 and so on?
Thank you in advance
Hint
You can calculate the AVG of the index 11 like this :
public static int processData(ArrayList<String> array) {
String[] spl;
int avg = 0, nbr = 0;
for (String elem : array) {
//split your String with ", " and space
spl = elem.split(", ");
//the index exist in the 3ed position, so you have to check your index if 11 then you can get its value
if(spl[2].equals("11")){
avg+=Integer.parseInt(spl[3]);
nbr++;
}
System.out.println(elem);
}
System.out.println((avg/nbr));
return avg / nbr;
}
When you print in your code you have to use :
output.println("11 " + retVal);
Hope this can gives you an idea.
You create a List of String to store employee data that contains multiple fields.
You should not as it mixes data employees.
The general idea I propose you :
1) Instead of storing all information in a List of String, use a List of Employee.
replace
ArrayList<String> inputData = new ArrayList<String>();
by
List<Employee> employees = new ArrayList<Employee>();
2)Use each read line that represents a person to create a instance of a custom Object, for example Employee.
So replace
inputData.add(line);
by something like that
String[] token = line.split(",");
Employee employee= new Employee(Integer.valueOf(token[0]),token[1],Integer.valueOf(token[2]),Integer.valueOftoken[3]));
employees.add(employee);
3) During this iteration to read the file, you can store in a variable that is the Employee with the minimum id.
4) After reading the file, you know the Employee with the minimum id. So you can iterate on the List of Employee and sum the salaries of the Employee that has this id and count the number of salary for this Employee.
When the loop is finished compute the avg : float avg = sum / (float)count;
It is not the most optimized way but it makes the job.
The following code will do what you need.
public class MyMain {
private static String inputFilePath = "/path/to/input.txt";
private static String outputFilePath = "/path/to/output.txt";
public static int processData(ArrayList<MyData> array) {
if (array.size() > 0) {
int minId = array.get(0).getData3();
for (MyData elem : array) {
if(elem.getData3() < minId) {
minId = elem.getData3();
}
}
int count = 0;
int total = 0;
for (MyData myData : array) {
if(myData.getData3() == minId) {
count++;
total += myData.getData4();
}
}
System.out.println("Min ID : " + minId + " -- Avg Sal : " + total/count);
}
return 0;
}
public static void main(String[] args) {
ArrayList<MyData> inputData = new ArrayList<>();
try {
Scanner in = new Scanner(new BufferedReader(new FileReader(inputFilePath)));
while (in.hasNextLine()) {
String line = in.nextLine().trim();
if (!line.isEmpty()) // Ignore blank lines
inputData.add(new MyData(line));
}
int retVal = processData(inputData);
PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter(outputFilePath)));
output.println("" + retVal);
output.close();
} catch (IOException e) {
System.out.println("IO error in input.txt or output.txt");
}
}
}
class MyData {
int data1;
String data2;
int data3;
int data4;
public MyData() {
// TODO Auto-generated constructor stub
}
public MyData(String data) {
String dataArr[] = data.split(",");
this.data1 = Integer.parseInt(dataArr[0].trim());
this.data2 = dataArr[1].trim();
this.data3 = Integer.parseInt(dataArr[2].trim());
this.data4 = Integer.parseInt(dataArr[3].trim());
}
public int getData1() {
return data1;
}
public void setData1(int data1) {
this.data1 = data1;
}
public String getData2() {
return data2;
}
public void setData2(String data2) {
this.data2 = data2;
}
public int getData3() {
return data3;
}
public void setData3(int data3) {
this.data3 = data3;
}
public int getData4() {
return data4;
}
public void setData4(int data4) {
this.data4 = data4;
}
}
Related
I am trying to create a program that will read from a .txt file that is formatted as such:
Total number of students
Name
Score1
Score2
Score3
Name
Score1
etc
My current code is this:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.io.*;
public class Project5 {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
System.out.println("Enter file name: ");
String filename = in.nextLine();
File filetest = new File(filename);
Scanner imp = new Scanner(filetest);
List<String> studentList = new ArrayList<String>();
List<Integer> studentScores = new ArrayList<Integer>();
String total = imp.nextLine();
int i = 0;
try {
while (imp.hasNext()) {
if (imp.hasNextInt()) {
studentScores.add(imp.nextInt());
} else {
studentList.add(imp.nextLine());
i++;
}
}
} finally {
System.out.println("Name\t\tScore1\t\tScore2\t\tScore3");
System.out.println("-------------------------------------------------------");
System.out.println(total);
System.out.println(studentList.get(0) + "\t" + studentScores.subList(0, 3));
System.out.println(studentList.get(2) + studentScores.subList(3, 6));
System.out.println(studentList.get(4) + studentScores.subList(6, 9));
System.out.println(studentList.get(6) + studentScores.subList(9, 12));
imp.close();
in.close();
}
}
}
The format I want to display into the console is to list the name, then the three scores that student received, and to repeat it, but right now it is hard-coded just for the amount of students that are currently there, and I need it to be able to create output regardless of how many students there are.
Current output:
Total
Name [score1 score2 score3]
etc
Desired output:
Total
Name score1 score2 score3 (rather than with the [] )
etc
Any help is greatly appreciated.
More structural way to do this :
public class Project5 {
static class Student {
private String name;
private final List<Integer> scores;
private int total;
public Student() {
scores = new ArrayList<>();
total = 0;
}
public void setName(String name) {
this.name = name;
}
public void addScore(int score) {
scores.add(score);
total += score;
}
public String getName() {
return name;
}
public List<Integer> getScores() {
return scores;
}
public int getTotal() {
return total;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder(name).append('\t').append(total);
for (Integer score : scores) {
sb.append('\t').append(score);
}
return sb.toString();
}
}
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
System.out.println("Enter file name: ");
String filename = in.nextLine();
in.close();
File filetest = new File(filename);
Scanner imp = new Scanner(filetest);
int total = Integer.parseInt(imp.nextLine());
System.out.println("Name\tTotal\tScore 1\tScore 2\tScore 3");
for (int i = 0; i < total && imp.hasNextLine(); i++) {
Student student = new Student();
student.setName(imp.nextLine());
while (imp.hasNextInt()) {
student.addScore(imp.nextInt());
}
if (imp.hasNext()) {
imp.nextLine();
}
System.out.println(student);
}
imp.close();
}
}
The toString method of a List will return it in that format. If you want a different format, you can do this with a Stream:
System.out.println(studentList.get(2) + studentScores.subList(3, 6).stream().collect(Collectors.joining(" ");
Health warning: if this is for a school assignment where the use of Streams may get you accused of plagiarism, you will need to concatenate the elements yourself the long way.
This is the efficient solution that uses a StringBuilder and no Lists. A StringBuilder is basically a class that helps you to build string. Pretty straightforward.
// 1024 means that the initial capacity of sb is 1024
StringBuilder sb = new StringBuilder(1024);
try {
while (imp.hasNext()) {
if (imp.hasNextInt()) {
// add the scores and "tab" character to the string
sb.append("\t").append(imp.nextInt());
} else {
// add the name to the string
sb.append("\n").append(imp.nextLine());
i++; // btw.. why are you doing this i++ ??
}
}
} finally {
System.out.println("Name\t\tScore1\t\tScore2\t\tScore3");
System.out.println("-------------------------------------------------------");
System.out.println(total);
System.out.println(sb.toString());
imp.close();
in.close();
}
If you do want to use an arraylist then I suggest iterate through the arraylist like an array and print out the scores.
After reading a text file and printing it out like so:
public static void main(String[] args) {
File file = new File("/Users/Len/Desktop/TextReader/src/example.txt");
ArrayList<String[]> arrayOfPeople = new ArrayList<>();
try {
Scanner input = new Scanner(file);
while (input.hasNext()) {
String num = input.nextLine();
System.out.println(num);
}
} catch (FileNotFoundException e) {
System.err.format("File Does Not Exist\n");
}
}
Print:
First Name, Surname, Age, Weight, Height
First Name, Surname, Age, Weight, Height
With this data, how do I calculate:
Oldest Person
Youngest Person
And print it out programmatically.
New to Java.
As user Bradimus mentioned in the comments, this is perfect for using classes.
If you look at the data in your file they are all the "same" type - every line has a first name, surname, age, weight and height. You can bundle them into an object and make them easier to use in your code.
Example:
public class Person {
public String firstName;
public String surname;
public int age;
public int height;
public int weight;
public Person(String input) {
//You can parse the input here. One 'input' is for example "Gordon, Byron, 37, 82, 178"
String[] splitString = input.split(", ");
this.firstName = splitString[0];
this.surname = splitString[1];
this.age = Integer.parseInt(splitString[2]);
this.height = Integer.parseInt(splitString[3]);
this.weight = Integer.parseInt(splitString[4]);
}
}
Then in your main class, you can just add them to an list like so. I added an example for how to calculate the oldest person, you can copy this logic (iterate over all the persons in the personList, perform check, return desired result) for the other tasks.
// Other code
public static void main(String[] args) {
List<People> peopleList = new ArrayList<>();
File file = new File("/Users/Len/Desktop/TextReader/src/example.txt");
try {
Scanner input = new Scanner(file);
while (input.hasNext()) {
String num = input.nextLine();
System.out.println(num);
peopleList.add(new Person(num));
} catch (FileNotFoundException e) {
System.err.format("File Does Not Exist\n");
}
Person oldestPerson = getOldestPerson(peopleList);
System.out.println("Oldest person: " + oldestPerson.firstName + " " + oldestPerson.surname);
}
public static Person getOldestPerson(List<Person> people) {
Person oldestPerson = null;
for (Person person: people) {
if (oldestPerson == null || person.age > oldestPerson.age) {
oldestPerson = person;
}
}
return oldestPerson;
}
You have an ArrayList called "arrayOfPeople", which you do not use yet. While reading your file line by line store the data in your list "arrayOfPeople" and calculate the needed values.
public static void main(String[] args) {
File file = new File("c:/Users/manna/desktop/example.txt");
ArrayList<String[]> arrayOfPeople = new ArrayList<>();
try {
Scanner input = new Scanner(file);
input.nextLine(); //do this to skip the first line (header)
while (input.hasNext()) {
String num = input.nextLine();
String[] personData = num.split(","); //returns the array of strings computed by splitting this string around matches of the given delimiter
arrayOfPeople.add(personData);
}
int oldest = Integer.parseInt(arrayOfPeople.get(0)[2].trim()); //Integer.parseInt("someString") parses the string argument as a signed decimal integer.
int youngest = Integer.parseInt(arrayOfPeople.get(0)[2].trim()); //String.trim() returns a copy of the string, with leading and trailing whitespace omitted
double totalWeight = 0;
double totalHeight = 0;
double totalAge = 0;
for(int i = 0; i< arrayOfPeople.size(); i++){
String[] personData = arrayOfPeople.get(i);
if(Integer.parseInt(personData[2].trim())>oldest){
oldest = Integer.parseInt(personData[2].trim());
}
if(Integer.parseInt(personData[2].trim())< youngest){
youngest = Integer.parseInt(personData[2].trim());
}
totalWeight = totalWeight + Double.parseDouble(personData[3].trim());
totalHeight = totalHeight + Double.parseDouble(personData[4].trim());
totalAge = totalAge + Double.parseDouble(personData[2].trim());
}
System.out.println("Oldest Person: " + oldest);
System.out.println("Youngest Person: " + youngest);
System.out.println("Average Weight: " + totalWeight/arrayOfPeople.size());
System.out.println("Average Height: " + totalHeight/arrayOfPeople.size());
System.out.println("Average Age: " + totalAge/arrayOfPeople.size());
} catch (FileNotFoundException e) {
System.err.format("File Does Not Exist\n");
}
}
I try use file IO declare obj that I create for baseball team information, but I dont know why the arrayList save the same data again and again, I want each data save once in arraylist. thank you
public static void main(String[] args) throws IOException{
Scanner in = new Scanner(System.in);
String fileName = "abc.txt"; //file name
// System.out.println("Please Enter The Source File Name:: ");
// fileName = in.nextLine();
ArrayList<Team> group = new ArrayList<Team>(); //use arrayList save data from obj
File file = new File(fileName); //open file
Scanner scan = new Scanner(file);
while (scan.hasNext()) { //read file to string and split it
String str = scan.nextLine();
String[] arr = str.split(",");
for (int i = 0; i < file.length(); i++) { //use split part to declear obj"Team"
int n = Integer.parseInt(arr[3]);
int m = Integer.parseInt(arr[4]);
Team tm = new Team(arr[0], arr[1], arr[2], n, m);
group.add(tm);
}
// scan.close();
//try to close but shows error"Scanner closed"
}
for(int i =0; i < group.size(); i++) { //check arrayList work well, but fail
System.out.println(group.get(i).getName());
}
}
In your code, for loop inside while loop seems to make duplicated entries
while (scan.hasNext()) { //read file to string and split it
String str = scan.nextLine();
String[] arr = str.split(",");
int n = Integer.parseInt(arr[3]);
int m = Integer.parseInt(arr[4]);
Team tm = new Team(arr[0], arr[1], arr[2], n, m);
group.add(tm);
}
**try this :**
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class SureshTemp
{
public static void main(String[] args) {
BufferedReader bf=null;
ArrayList al=new ArrayList();
try
{
String currentLine;
bf=new BufferedReader(new FileReader("D:\\abc.txt"));
while((currentLine=bf.readLine())!=null)
{
System.out.println(currentLine);
String str=currentLine;
String[] arr=str.split(",");
int n=Integer.parseInt(arr[3]);
int m=Integer.parseInt(arr[4]);
Team t=new Team(arr[0],arr[1], arr[2], n, m);
al.add(t);
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try {
if (bf != null)bf.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
for(int i =0; i < al.size(); i++){
System.out.println(al.get(i));
}
}
}
class Team
{
private String First;
private String next;
private String third;
private int won;
private int lost;
public Team(String F,String N,String T,int w,int l)
{
First=F;
next=N;
third=T;
won=w;
lost=l;
}
#Override
public String toString() {
return "Team [First=" + First + ", next=" + next + ", third=" + third
+ ", won=" + won + ", lost=" + lost + "]";
}
public String getFirst() {
return First;
}
public void setFirst(String first) {
First = first;
}
public String getNext() {
return next;
}
public void setNext(String next) {
this.next = next;
}
public String getThird() {
return third;
}
public void setThird(String third) {
this.third = third;
}
public int getWon() {
return won;
}
public void setWon(int won) {
this.won = won;
}
public int getLost() {
return lost;
}
public void setLost(int lost) {
this.lost = lost;
}
}
try this :
while (scan.hasNext()) {
String str = scan.nextLine();
String[] arr = str.split(",");
int n = Integer.parseInt(arr[3]);
int m = Integer.parseInt(arr[4].trim()); // Use trim()to avoid NumberFormatException
Team tm = new Team(arr[0], arr[1], arr[2], n, m);
group.add(tm);
}
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;
}
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.