Writing on an output file - java

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.

Related

How to fix a loop for a heap structure

The code compiles but when you run it an error message occurs that gives a null pointer exception. As SEEN in the bottom. the code is supposed to read text from a txt file that is inputted in the program and then create a new txt file with the content of the first txt file sorted by years of service. However, i keep receiving that error message. Any help would be greatly appreciated. I added the error message at the bottom thank you to everyone who is helping your time and effort is greatly appreciated :)
(25 points)Define a Java class called Employee. The class has data members
and accompanying accessor and mutator methods for each of the following six data items. (This involves creating the file Employee.java.)
id (string)
name (string)
salary (double)
department (string)
position (string)
years of service (integer)
(25 points)Create a text (data) file containing data for at least five different
employees (objects). Let each data item sit on its own line in
the text file. For example, the first six lines of the file might look like:
086244
Sally L. Smith
100000.00
Accounting
Manager
7
(50 points)‘Heap’ is a tree-based data-structure that satisfies the heap property. A max-heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node.
By having a heap (or an array that satisfies the heap property), it would be more efficient (generally faster) to perform important tasks on the array such as finding the maximum element in the array (and removing it) and sorting the array.
In this assignment, you will have to write a program that reads a list of employees from a file. The name of the file will be ‘Employee.txt’. The program should output the sorted array to a file called “SortedEmployee.txt”
Heapsort code:
public class HeapSort
{
//heap sort method
public static <Employee extends Comparable<Employee>> void heapSort(Employee[] list)
{
//create a Heap of integers
Heap<Employee> heap = new Heap<>();
//add elements to the heap
for (int i = 0; i< list.length; i++)
heap.add(list[i]);
//remove elements from the heap
for(int i = list.length - 1; i >= 0; i--)
list[i] = heap.remove();
}
}
Heap code:
import java.util.ArrayList;
public class Heap<Employee extends Comparable<Employee>>
{
private ArrayList<Employee> list = new ArrayList<>();
public Heap(){}
public Heap(Employee[] objects)
{
for(int i = 0; i < objects.length; i++)
add(objects[i]);
}
public void add(Employee newObject)
{
list.add(newObject);
int currentIndex = list.size() - 1;
while(currentIndex > 0)
{
int parentIndex = (currentIndex -1)/2;
if(list.get(currentIndex).compareTo(list.get(parentIndex)) > 0)
{
Employee temp = list.get(currentIndex);
list.set(currentIndex, list.get(parentIndex));
list.set(parentIndex, temp);
}
else
break;
currentIndex = parentIndex;
}
}
public Employee remove()
{
if(list.size() == 0) return null;
Employee removeObject = list.get(0);
list.set(0, list.get(list.size() -1));
list.remove(list.size() -1);
int currentIndex = 0;
while(currentIndex < list.size())
{
int leftChildIndex = 2 * currentIndex + 1;
int rightChildIndex = 2 * currentIndex + 2;
if(leftChildIndex >= list.size()) break;
int maxIndex = leftChildIndex;
if(rightChildIndex < list.size())
{
if(list.get(maxIndex).compareTo(list.get(rightChildIndex)) < 0)
maxIndex = rightChildIndex;
}
if(list.get(currentIndex).compareTo(list.get(maxIndex)) < 0)
{
Employee temp = list.get(maxIndex);
list.set(maxIndex, list.get(currentIndex));
list.set(currentIndex, temp);
currentIndex = maxIndex;
}
else
break;
}
return removeObject;
}
public int getSize()
{
return list.size();
}
public void print()
{
for (int i = 0; i <= getSize()-1; i++)
{
System.out.print("Index: " + i + " Data: " + list.get(i));
System.out.println();
}
}
}
Employee Object Class:
public class Employee implements Comparable<Employee>
{
private String id;
private String name;
private double salary;
private String department;
private String position;
private int yos;
public Employee(String id, String name, double salary,String department,String position,int yos)
{
this.id = id;
this.name = name;
this.salary = salary;
this.department = department;
this.position = position;
this.yos = yos;
}
public void setid(String id)
{
this.id = id;
}
public void setname(String name)
{
this.name = name;
}
public void setsalary(double salary)
{
this.salary = salary;
}
public void setdepartment(String department)
{
this.department = department;
}
public void setposition(String position)
{
this.position = position;
}
public void setyos(int yos)
{
this.yos = yos;
}
public String getid()
{
return id;
}
public String getname()
{
return name;
}
public double getsalary()
{
return salary;
}
public String getdepartment()
{
return department;
}
public String getposition()
{
return position;
}
public int getyos()
{
return yos;
}
public int compareTo(Employee emp)
{
return (this.yos - emp.yos);
}
public String toString()
{
return "ID=" + this.id+ ", name=" + this.name+ ", salary= $" + this.salary+ ", department:" + this.department+ ", postion:" + this.position+ ",yos= $" + this.yos + "]\n";
}
}
Demo code:
import java.util.*;
import java.io.*;
public class EmployeeDemo
{
public static void main(String[] args)throws IOException
{
Employee[] list = new Employee[5];
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the text file: ");
String fileName = keyboard.nextLine();
File myFile = new File(fileName);
Scanner inputFile = new Scanner(myFile);
//Read all of the values from the file
//and calculate their total
//Read a value from the file
String id = inputFile.nextLine();
String name = inputFile.nextLine();
double salary = inputFile.nextDouble();
String clear = inputFile.nextLine();
String department = inputFile.nextLine();
String position = inputFile.nextLine();
int yrService = inputFile.nextInt();
String llear = inputFile.nextLine();
list[0] = new Employee(id,name,salary,department,position,yrService);
//close the file
// File o = new File("SortedEmployee.txt");
//o.createNewFile();
System.out.println("Enter the file name to be transfered to: ");
String filename = keyboard.nextLine();
PrintWriter outputFile = new PrintWriter(filename);//dont need the top
//HeapSort<Employee> h = new heapSort<Employee>(Employee);
HeapSort.heapSort(list);
//Display the sum of the numbers
while(inputFile.hasNext())//this loop is wrong too
{
outputFile.println(list[0].toString());
}
outputFile.close();
inputFile.close();
System.out.print("File Sorted and Transferred");
}
}
here is the error message i am receiving:
Please enter the text file:
C:\Users\jose385\Desktop\Employee.txt
Enter the file name to be transfered to:
green
Exception in thread "main" java.lang.NullPointerException
at Heap.add(Heap.java:22)
at HeapSort.heapSort(HeapSort.java:13)
at EmployeeDemo.main(EmployeeDemo.java:50)
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
You make the List have a size of 5
Employee[] list = new Employee[5];
but only add one element
list[0] = new Employee(id,name,salary,department,position,yrService);
Actually what is the point of only sorting one element
Also try to follow a tutorial on the correct way to implement Comparable

Use File IO and make data shows in clear way

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);
}

ArrayList-"for-loop" exits code at .size() call, what's wrong?

As part of the login method for my fictive bank, i have a Luhn algorithm set up to validate the users ID.
It seems to check through and comes back valid, but when i list the ArrayList (with the for-loop) to see if there's a corresponding match or not, the code seems to breaks out when it hits kList.size()
See this :
public void logIn() {
System.out.print("Please enter your ID (10 numbers):");
String x = s.nextLine();
if (luhnCheck(x)) {
for (i = 0; i < k.kList.size(); i++) { //<-----ISSUE!
if (k.kList.get(i).getPnr().equals(x)) {
tempKund = k.kList.get(i);
}
}
} else {
System.out.println("You are not a customer, please register!");
System.out.print("Enter name:");
String n = s.nextLine();
k.createKund(x, n); //sends values to create customer method
kundMeny1(); // customer menu...
}
}
public boolean luhnCheck(String v) {
int sum = 0;
boolean alternate = false;
for (int i = v.length() - 1; i >= 0; i--) {
int n = Integer.parseInt(v.substring(i, i + 1));
if (alternate) {
n *= 2;
if (n > 9) {
n = (n % 10) + 1;
}
}
sum += n;
alternate = !alternate;
}
return (sum % 10 == 0);
}
Update: So apparently the problem doesn't seem to in the loop, but when the .size() tries to get the needed information. I'll paste some more of my code:
public class Bank {
Scanner s = new Scanner(System.in);
Kund k = new Kund(); //Used for communicating with the Kund(customer class)
Konto t = new Konto(); //Used for communicating with the Konto(account class)
Kund tempKund; //Temporary customer used to keep track of who's logged in
int i;
public static void main(String[] args) {
Bank b = new Bank();
b.mainMenu();
}
public void mainMenu() {
k.createKund("8908041207", "Adam Sears"); //Creates a customer
t.createKonto("1234567891", "3000"); //Creates a bank account
int user_choice = 3;
do { // Goes on to a Switch Case menu for the user...
Kund(Customer class)
public class Kund {
ArrayList<Kund> kList = new ArrayList<Kund>();
Kund knd;
String pnr; //Customer ID, used in validation
String name; //Customer name
public void kund() {
}
public String getPnr() {
return pnr;
}
public void setPnr(String x) {
this.pnr = x;
}
public String getName() {
return name;
}
public void setName(String z) {
this.name = z;
}
public void createKund(String p, String n) { //Creates the new customer
knd = new Kund();
knd.setPnr(p);
knd.setName(n);
addKund(knd);
}
public ArrayList<Kund> addKund(Kund s) { //Adds said customer to ArrayList
kList.add(s);
return kList;
}
This part of your code :
if (luhnCheck(x)) {
if (true) {
// Code
} else if (false) {
// Code
}
}
Should be replaced by this :
if (luhnCheck(x)) {
// Code
} else {
// Code
}
For the rest of the problem. I should know where you instantiate your k object.
We need more inforation on how k is instantiate, try to organize you snippet code, and try to debug at the
for (i = 0; i < k.kList.size(); i++) { //<-----ISSUE!
to see what kist contains?

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;
}

trouble with array lists

I am doing a project and instead of using an array, I figured an array list would be better. I know I need to declare the array list and its methods, but I am not too sure where to go from there. Any suggestions? Here's code...
public class Student {
private String name;
private int[] tests;
public Student() {
this("");
}
public Student(String nm) {
this(nm, 3);
}
public Student(String nm, int n) {
name = nm;
tests = new int[n];
for (int i = 0; i < tests.length; i++) {
tests[i] = 0;
}
}
public Student(String nm, int[] t) {
tests = new int[t.length];
}
public Student(Student s) {
this(s.name, s.tests);
}
public int getNumberOfTests() {
return tests.length;
}
public void setName(String nm) {
name = nm;
}
public String getName() {
return name;
}
public void setScore(int i, int score) {
tests[i - 1] = score;
}
public int getScore(int i) {
return tests[i - 1];
}
public int getAverage() {
int sum = 0;
for (int score : tests) {
sum += score;
}
return sum / tests.length;
}
public int getHighScore() {
int highScore = 0;
for (int score : tests) {
highScore = Math.max(highScore, score);
}
return highScore;
}
public String toString() {
String str = "Name: " + name + "\n";
for (int i = 0; i < tests.length; i++) {
str += "test " + (i + 1) + ": " + tests[i] + "\n";
}
str += "Average: " + getAverage();
return str;
}
public String validateData() {
if (name.equals("")) {
return "SORRY: name required";
}
for (int score : tests) {
if (score < 0 || score > 100) {
String str = "SORRY: must have " + 0 + " <= test score <= " + 100;
return str;
}
}
return null;
}
}
I figured an array list would be better
Maybe. Maybe not. It depends. Does it look like you would get a benefit in using one based on the ArrayList API?
If your "list" never changes size, and you don't need to find things in it, then an array is just as good.
I know I need to declare the array list and its methods, but I am not
too sure where to go from there
You need to create a reference to an instance of an ArrayList. That's as simple as
List<Integer> myList = new ArrayList<Integer>();
in your class declaration. You don't need to "declare its methods". When you have a reference to an object, you can invoke its methods.
To use an ArrayList, you just need to declare and instantiate it:
// <SomeObject> tells Java what kind of things go in the ArrayList
ArrayList<SomeObject> aDescriptiveNameHere = new ArrayList<SomeObject>();
// This is also valid, since an ArrayList is also a List
List<SomeObject> list = new ArrayList<SomeObject>();
Then you can add things with the add() method:
// Please don't name your list "list"
list.add(new Thing(1));
list.add(new Thing(2));
You can get something by index (like you would with someArray[index]) as:
list.get(index);
// For example
Thing t = list.get(5);
You probably also need the size().
See the JavaDocs for more info.
All of the operations you're using are mirrored in the ArrayList API. One thing that's worth noting is that you cannot declare an ArrayList of primitive types, but for each of the primitive types there exists an Object that is the boxed version of the primative.
The boxed version of int is Integer, so you have
ArrayList<Integer> myList = new ArrayList<Integer>();
From there, you need to look up the methods you would need to use in order to manipulate the array. For example, if you want to add the number 42 to the end of the array, you would say
myList.add(42);
The ArrayList API is located here.
I think it could be better to use the stl vector instead make your own arrays
I tried to change the array to arraylist.
Reply if this doesn't compile correctly.
import java.util.ArrayList;
public class Student {
private String name;
// private int[] tests;
private ArrayList<Integer> tests;
public Student() {
this("");
}
public Student(String nm) {
// this(nm, 3);
name = nm;
}
/*
* public Student(String nm, int n) { name = nm; tests = new int[n]; for
* (int i = 0; i < tests.length; i++) { tests[i] = 0; } }
*/
/*
* public Student(String nm, int[] t) { tests = new int[t.length]; }
*/
public Student(Student s) {
this(s.name, s.tests);
}
public Student(String name2, ArrayList<Integer> tests2) {
name = name2;
tests = tests2;
}
public int getNumberOfTests() {
return tests.size();
}
public void setName(String nm) {
name = nm;
}
public String getName() {
return name;
}
// public void setScore(int i, int score) {
// tests[i - 1] = score;
public void setScore(int score) {
tests.add(score);
}
public int getScore(int i) {
// return tests[i - 1];
return tests.get(i - 1);
}
public int getAverage() {
int sum = 0;
for (int score : tests) {
sum += score;
}
// return sum / tests.length;
return sum / tests.size();
}
public int getHighScore() {
int highScore = 0;
for (int score : tests) {
highScore = Math.max(highScore, score);
}
return highScore;
}
public String toString() {
String str = "Name: " + name + "\n";
for (int i = 0; i < tests.size(); i++) {
str += "test " + (i + 1) + ": " + tests.get(i) + "\n";
}
str += "Average: " + getAverage();
return str;
}
public String validateData() {
if (name.equals("")) {
return "SORRY: name required";
}
for (int score : tests) {
if (score < 0 || score > 100) {
String str = "SORRY: must have " + 0 + " <= test score <= "
+ 100;
return str;
}
}
return null;
}
public ArrayList<Integer> getTests() {
return tests;
}
public void setTests(ArrayList<Integer> tests) {
this.tests = tests;
}
}

Categories