Unable to remove data from array in java - java

I am attempting to remove data from an array that I have added and want to specifically remove this data based on one variable to bring all the data from the array and then remove it.
Getting an error that says:
bad operand types for binary operator'-'
on line arr[j] = new Studnet(arr{j+i].Getid.........."
private void removeStudent() {
if(count == 0){
System.out.println("No Records");
} else {
Scanner intput = new Scanner(System.in);
System.out.println("Enter an ID: ");
String id = intput.next();
int res = 0;
int loc = 0;
Student[] temp = new Student[10];
for(int i = 0; i < count; i++) {
if(arr[i].getId().equals(id)){
for(int j = i; i < arr.length - 1; j++) {
arr[j] = new Student(arr[j+1].getId() - 1, arr[j+1].getFname(), arr[j+1].getLname(), arr[j+1].getAge());
}
loc = i;
res = 1;
}
}
temp = null;
count--;
arr = temp;
Scanner scanner = new Scanner(System.in);
System.out.println("Removed Record");
scanner.nextLine();
if(res == 1) {
} else
System.out.println("No Result");
}
}
This is my code on the separate file that has all the get functions
public class Student {
private String id;
private String fname;
private String lname;
private int age;
private int count;
Student(String id, String fname, String lname, int age, int count) {
this.id = id;
this.fname = fname;
this.lname = lname;
this.age = age;
this.count = count;
}
public String getId() {
return id;
}
public String getFname() {
return fname;
}
public String getLname() {
return lname;
}
public double getAge() {
return age;
}
public int getCount() {
return count;
}
}

You are trying to minus 1 on a string. That is why you got the error.
Do you want to try to get the ID in intger form, and then minus 1 so you can assign the previous ID to that student object?
If yes, try the below in order to convert it to integer and then minus 1:
Integer.parseInt(arr[j+1].getId())-1

Id is a string you cant calculate with it. (Like getId()- 1)
Edit:
This is a really simple example to show you, how it CAN work... but there different ways (maybe better ways) to solve your root problem. (See my first comment)
for(int j = i; i < arr.length - 1; j++){
int newId = Integer.parseInt(arr[j+1].getId()) -1;
arr[j] = new Student(Integer.toString(newId), arr[j+1].getFname(), arr[j+1].getLname(), arr[j+1].getAge());
}

Related

The for loop in the method gets skipped when 3rd entry goes in. JAVA

When I run this code, for some reason when it hits test10 to be added into the Array sort, the addListing method ignores the for loop and just skips to the bottom. I am curious why the for loop runs for test2.addListing(test); and test2.addListing(test9); but not for the one after.
import java.util.Scanner;
public class TestListings {
public static void main(String[] args) {
StudentListings test = new StudentListings();
StudentListings test9 = new StudentListings();
StudentListings test10 = new StudentListings();
test.input();
test9.input();
test10.input();
Scanner sc = new Scanner(System.in);
int aSize = 0;
System.out.print("Enter Array Size: ");
aSize = Integer.parseInt(sc.nextLine());
ArraySort test2 = new ArraySort(aSize);
test2.addListing(test);
test2.addListing(test9);
test2.addListing(test10);
test2.showAllListings();
}
}
This is the method written, and it runs for the first run through, next = 0; intially, but the 3rd time (in test10) it just looks at the line and skips it.
public class ArraySort
{
private StudentListings[] data;
private int size = 0;
private int next = 0;
public ArraySort()
{
data = new StudentListings[size];
size = 0;
next = 0;
}
public ArraySort(int ArraySize)
{
size = ArraySize;
data = new StudentListings[size];
next = 0;
}
public void addListing(StudentListings newListing)
{
System.out.print(next);
for(i = next - 1; i <= 0; i--)
{
try {
if (newListing.compareTo(data[i].getLName()) < 0)
{
data[i+1] = data[i].deepCopy();
}
else
{
data[i+1] = newListing;
next++;
break;
}
}
catch(ArrayIndexOutOfBoundsException | NullPointerException exception)
{
int x = i + 1;
data[x] = newListing;
next++;
break;
}
}
System.out.print(next);
}
public void showAllListings()
{
for(int i = 0; i < next; i++)
{
System.out.println((i + 1) + ". " + data[i]);
}
}
}
This is the class that is getting created to be inserted into the array.
import java.util.Scanner;
public class StudentListings {
private String firstName;
private String lastName;
private int id;
private double gpa;
public StudentListings()
{
firstName = "";
lastName = "";
id = 0;
gpa = 0.0;
}
public StudentListings(String firstName, String lastName, int id,
double gpa)
{
this.firstName = firstName;
this.lastName = lastName;
this.id = id;
this.gpa = gpa;
}
public void setName(String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public String getName()
{
return firstName + " " + lastName;
}
public void setId(int id)
{
this.id = id;
}
public int getId()
{
return id;
}
public void setGpa(double gpa)
{
this.gpa = gpa;
}
public double getGpa()
{
return gpa;
}
public String getLName()
{
return lastName;
}
public void input()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter First Name: ");
this.firstName = sc.nextLine();
System.out.print("Enter Last Name: ");
this.lastName = sc.nextLine();
System.out.print("Enter Student ID: ");
this.id = sc.nextInt();
System.out.print("Enter Student GPA: ");
this.gpa = Double.parseDouble(sc.next());
}
public String toString()
{
return "Last Name: " + lastName + " First Name: " + firstName + " ID:
" + id + " GPA: " + gpa;
}
public StudentListings deepCopy()
{
StudentListings clone = new StudentListings(firstName, lastName, id,
gpa);
return clone;
}
public int compareTo(String targetKey)
{
return(lastName.compareTo(targetKey));
}
}
If next is 0 the first time then it’s 2 the third time and i starts at 1 so the condition i <= 0 is false from the start
I'm not solving that problem, because in my opinion you're trying to do (intricately) something already defined in Java. When you create a class, and have to manage an array of object of that class, Java offers a very simple way to do that, I'll explain what I would do in your position step by step:
1 - The first thing to do is to define the comparison between the object belonging to that class, you can achieve that by overriding the method compareTo of that class (the class has to implement Comparable <YourObject>); in your case i guess it schould be something like:
public class StudentListings implements Comparable<StudentListings>{
...
#Override
public int compareTo(StudentListings element){
return ...;
}
}
In which you define when a StudentListing object is bigger than another.
2 - The second thing to do is to define an ArrayList<StudentListings> in your main, and initialize it:
ArrayList<StudentListings> yourArray = new ArrayList<>();
3 - Then you have to add the elements to that array (obviously after you initialized them):
yourArray.add(test);
yourArray.add(test9);
yourArray.add(test10);
4 - Now you have your array, not sorted, to sort it you just have to call the method
Collections.sort(yourArray);
Now you have your ArrayList of StudentListings sorted.
There is another way to achieve this result, that is described here, I don't like it very much because using that way you have to redefine the comparison everytime you need to sort an array and because your main code results more complex, but it has the same result of the steps I explained (therefore the linked method is useful if you have to sort two different arrays of the same class objects in different ways, eg. one by students name and the other by students surname).

Multiple problems with sort method and toString not working

I'm having an issue with a problem for homework.. the issues I am having are:
I have the following errors on my sort method:
The method sort(int[]) in the type Main is not applicable for the
arguments (Class)
studentArray cannot be resolved to a type
Syntax error, insert ". class" to complete ArgumentList
My toString method also doesnt seem to be putting out any information in the console.
HERE IS THE HOMEWORK PROBLEM:
For the lab this week, you will sort an array of objects - using any of the sort methods discussed in Chapter 23 or the Selection sort. It's your choice. Use the following criteria for your assignment:
The object class should be a Student with the following attributes:
id: integer
name: String
write the accessors, mutators, constructor, and toString().
In your main test class you will write your main method and do the following things:
Create an array of Student objects with at least 5 students in your array.
The sort method must be written yourself and included in the main class. The sort
method will sort based on student id.
Output the array out in unsorted order as it exists.
Sort the array
Output the sorted array
HERE IS MY MAIN CLASS:
public static void main(String[] args) {
Student studentArray[] = new Student[5];
for (int i=0; i < studentArray.length; i++) {
studentArray[i] = new Student();
}
studentArray[0].id = 5555;
studentArray[0].name = "Jim Jackson";
studentArray[1].id = 4444;
studentArray[1].name = "Craig Creedmoor";
studentArray[2].id = 3333;
studentArray[2].name = "Bill Biggums";
studentArray[3].id = 2222;
studentArray[3].name = "Frances Freeland";
studentArray[4].id = 1111;
studentArray[4].name = "Leslie Limerick";
for (int i = 0; i<5; i++) {
studentArray[i].toString();
}
sort(studentArray[]);
for (int i = 0; i<5; i++) {
studentArray[i].toString();
}
}
public void sort(int[] studentArray) {
for (int i = 1; i < studentArray.length; i++) {
int currentElement = studentArray[i];
int k;
for (k = i -1; k >=0 && studentArray[k] > currentElement; k--) {
studentArray[k + 1] = studentArray[k];
}
studentArray[k +1] = currentElement;
}
}
HERE IS MY STUDENT CLASS
public int id;
public String name;
Student() {
}
public int getID() {
return id;
}
public void setID(int i) {
this.id = i;
}
public String getName() {
return name;
}
public void setName(String n) {
this.name = n;
}
public String toString() {
return "The student's name is: " + this.name + "\n" +
"The student's ID is: " + this.id;
}
So according to the assignment instructions, here is what I got from it...
You needed a constructor in your student class, you were adding objects to the array improperly, Your sort method was also accessing the element within the array which is a "Student" and you were comparing it to type "int". To fix that I made the object in the student array actually access the ID.
Also.... Your sort method did not seem to work for me. The instructions said that you could use a selection sort so that is what I implemented instead. Let me know if you have questions.
This should work, let me know if it doesn't because I don't know how your Student class is defined within your project.
public static void main(String[] args) {
Student studentArray[] = new Student[5];
studentArray[0] = new Student(5555, "Jim Jackson");
studentArray[1] = new Student(4444, "Craig Creedmor");
studentArray[2] = new Student(3333, "Bill Biggums");
studentArray[3] = new Student(2222, "Frances Freeland");
studentArray[4] = new Student(1111, "Leslie Limerick");
sort(studentArray);
for (int i = 0; i<5; i++) {
System.out.println(studentArray[i].toString());
}
}
public static void sort(Student[] arr) {
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++)
if (arr[j].getID() < arr[index].getID())
index = j;
int smallerNumber = arr[index].getID();
String smallerString = arr[index].getName();
arr[index].setID(arr[i].getID());
arr[index].setName(arr[i].getName());
arr[i].setID(smallerNumber);
arr[i].setName(smallerString);
}
}
And then for Student class
public class Student {
private int id;
private String name;
public Student(int id, String name){
this.id = id;
this.name = name;
}
public int getID() {
return id;
}
public void setID(int i) {
this.id = i;
}
public String getName() {
return this.name;
}
public void setName(String n) {
this.name = n;
}
public String toString() {
return "The student's name is: " + this.name + "\n" +
"The student's ID is: " + this.id;
}
}

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

how to swap two array objects in java

I'm trying to sort courses and organize them by course number.
I have created an array of objects which contain 3 attributes (department, num, title). I want to sort this array by 'num' using the selection sort method. When i try to swap the two arrays the compiler says int cannot be converted to Course[].
public static void sortByNumber(Course[] arr){
int size = arr.length;
for (int i = 0; i < size - 1; i++) {
int min = i;
for (int j = i + 1; j < size; j++) {
if (arr[j].getNum() < arr[min].getNum()) {
min = j;
}
}
int temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}
this is my other class.
public class Course {
//INSTANCE VARIABLES
private String dept = "";
private int num = 0;
private String title = "";
//CONSTRUCTORS
public Course(String dept, int num) {
this.dept = dept;
this.num = num;
}
public Course(String dept, int num, String title) {
this.dept = dept;
this.num = num;
this.title = title;
}
public Course() {
this.dept = "AAA";
this.num = 100;
this.title = "A course";
}
//SETTER AND GETTER METHODS
public void setDept(String dept) {
this.dept = dept;
}
public void setNum(int num) {
this.num = num;
}
public void setTitle(String title) {
this.title = title;
}
public String getDept() {
return this.dept;
}
public int getNum() {
return this.num;
}
public String getTitle() {
return this.title;
}
}
int temp = arr[i];
arr[i] is Course, temp is int. You cannot assign a Course into an int variable, neither can you assign an int into a Course variable, because they are two completely different types.
Make your temp a Course:
Course temp = arr[i];
Ishamael's answer was correct. I will throw out this addition as you later may find it very useful to allow the user to sort by any field:
First you will need to add the Comparable interface to your Course class and write the compareTo() method. I've added an enum to the class to match each field you might want to sort by:
public class Course implements Comparable<Course>{
public static enum SortBy {
DEPARTMENT,
COURSE_NUM,
TITLE,
NOT_SORTED;
}
public static SortBy sortBy = SortBy.NOT_SORTED;
#Override
public int compareTo(Course course) {
if(sortBy == SortBy.DEPARTMENT) return getDept().compareTo(course.getDept());
if(sortBy == SortBy.COURSE_NUM) return getNum() - course.getNum();
if(sortBy == SortBy.TITLE) return getTitle().compareTo(course.getTitle());
return 0;
}
...
You can now modify your 'if' statement in your sort method to:
if (arr[j].compareTo(arr[min]) < 0) {
min = j;
}
Here is an example of using it now...
public static void main(String[] args) {
Course[] arr = {
new Course("dep-B", 3, "title-F"),
new Course("dep-C", 1, "title-E"),
new Course("dep-A", 2, "title-D")
};
System.out.println("Sorted by default (not sorted)");
System.out.println(Arrays.toString(arr));
System.out.println("Sorted by Department");
Course.sortBy = SortBy.DEPARTMENT;
sortByNumber(arr);
System.out.println(Arrays.toString(arr));
System.out.println("Sorted by Course Number");
Course.sortBy = SortBy.COURSE_NUM;
sortByNumber(arr);
System.out.println(Arrays.toString(arr));
System.out.println("Sorted by Title");
Course.sortBy = SortBy.TITLE;
sortByNumber(arr);
System.out.println(Arrays.toString(arr));
}

Reading input from a text file using scanner into array

I am trying to read the input from a text file using scanner class and pass into an array. I know how to read the input using scanner class. The only problem I am facing here is I am unable to pass into the array.
public class ReadItemData {
public static void main(String[] args) throws Exception {
Scanner aScanner = new Scanner(new FileReader(
"src//chapter11//Items.txt"));
while (aScanner.hasNext()) {
String code = aScanner.next();
String sku = aScanner.next();
double qty = aScanner.nextDouble();
System.out.println(code + " " + sku + " " + qty);
}
}
The above code works without the array concept. I want to extend the same concept to read the above data into a array of size 100. Any suggestions would be helpful. My final aim is to sort the input which is in array by code,sku
This is how I used comparable interface for sorting. How can I extend this concept for arrays?
I used something like this for sorting(without the array concept)
class Item implements Comparable {
private int qty;
private String sku,code;
public Item(int qty, String sku,String code) {
this.qty = qty;
this.sku = sku;
this.code = code;
}
public int getQty() {
return qty;
}
public String getSku() {
return sku;
}
public String getCode() {
return code;
}
public int compareTo(Object o) {
Item i = (Item) o;
if (this.getQty() < i.getQty())
{
return -1;
}
if (this.getQty() > i.getQty())
{
return 1;
}
return 0;
}
}
Thanks!!
String[] array = new String[100];
int currentIndex = 0;
while (aScanner.hasNext()) {
String code = aScanner.next();
String sku = aScanner.next();
double qty = aScanner.nextDouble();
array[currentIndex] = code;
array[currentIndex++] = sku;
array[currentIndex++] = ""+qty;
currentIndex++;
}
As mentioned in the comments, you can use 2D array of 100 rows and 3 columns like this:
Object[][] array = new Object[100][3];
int i=0,j=0;
while (aScanner.hasNext()) {
String code = aScanner.next();
String sku = aScanner.next();
double qty = aScanner.nextDouble();
array[i][j++] = code; // array of row i and columns j
array[i][j++] = sku;
array[i][j] = qty;
i++; // increment i since it's for rows
j=0;//reset j because it's for columns
}

Categories