how do I make the taillength update with age? - java

//Srivet av Jonathan Arnfjell joar6216
public class Dog {
private String name; // name of dog
private int age; // in years
private int weight; // in pounds
private String breed; // breed of dog
private double tailLength; // Length of tail
private double div = 10;
private double smallTail = 3.7;
private double ageDouble;
private double weightDouble;
public Dog(String name, String breed, int age, int weight) {
this.name = name;
this.breed = breed;
this.age = age;
this.weight = weight;
this.ageDouble = age;
this.weightDouble = weight;
this.tailLength = ageDouble * weightDouble / div;
}
public String getName() {
return name;
}
public String getBreed() {
return breed;
}
public int getAge() {
return age;
}
public int getWeight() {
return weight;
}
public double getTailLength() {
if (breed.equalsIgnoreCase("tax") || breed.equalsIgnoreCase("dachshund")) {
return smallTail;
} else {
return tailLength;
}
}
public void setAge(int newAge) {
if (newAge < age) {
System.out.println("ERROR: Age goes up!");
System.exit(0);
} else
age = newAge;
}
public String toString() {
return name + " " + breed + " " + age + " " + weight + " " + getTailLength();
}
public static void main(String args[]) {
Dog d1 = new Dog("Fluffy", "tax", 5, 6);
Dog d2 = new Dog("Fido", "Fakehund", 7, 15);
System.out.println(d2);
System.out.println(d2.getTailLength());
d2.setAge(9);
System.out.println(d2);
System.out.println(d2.getTailLength());
}
}

Just change your setAge() function to this:
public void setAge(int newAge) {
if (newAge < age) {
System.out.println("ERROR: Age goes up!");
System.exit(0);
} else
age = newAge;
this.tailLength = age * weightDouble / div;
}
}

Always try to have 1 source of truth. If the tail length is generated based on other values, then you shouldn't store the value of tail length, the getTailLength() function could calculate the tail length every time it is called.
You could recalculate tail length every time tail length is called, to make sure the tail length is updated before it is used. But if you are calculating it every time it is used, then there doesn't seem to be a point in storing it.
Another option could be to use something similar to a simplified observer pattern. When weight or age is updated, call a method that updates the tail length.
To me though it makes the most sense not to store it, and to simply calculate it when you want it.

Related

The values from expected output are not showing

I instantiated the SpaceStation class and called addAstronaut method but the name, weight, altitude, and astronauts are not showing in my output when I run it.
SpaceStation.java:
public class SpaceStation {
//private members
private String name;
private double stationWeight;
private double altitude;
private Astronaut[] Astronauts;
private int totalAstronauts;
//overloaded constructor
public SpaceStation(String name, double
weight) {
int altitude = 0;
int totalAstronauts = 0;
}
//method
public void addAstronaut(String name, double
height, double weight) {
Astronauts = new Astronaut[3];
stationWeight = stationWeight + weight;
totalAstronauts++;
}
public double setAltitude(double altitude) { return this.altitude = altitude; }
public String toString() {
return "SpaceStation: " + name + "\n" +
"Weight(kg): " + stationWeight + "\n" +
"Altitude(km): " + (altitude) + "\n" +
"Astronauts: " + (totalAstronauts);
}
public static void main(String[] args) {
SpaceStation aa = new SpaceStation("ISS", 419700.0);
System.out.println(aa);
aa.addAstronaut("Eli", 167.64, 81.65);
aa.addAstronaut("John", 185.43, 100.30);
aa.addAstronaut("Joey", 175.38, 90.38);
aa.setAltitude(400.0);
}
}
Your code contains four errors:
1- You are not setting the content of the instance variable name in the constructor. This causes the line SpaceStation: null when printing the output. You need to set the name in the constructor. Change the constructor to be like this:
public SpaceStation(String name, double
weight) {
this.name = name; // This line was added
int altitude = 0;
int totalAstronauts = 0;
}
2- You are printing the content of ss before adding your astronauts and setting the altitude. At that time, there are no astronauts added, so it's normal that the weight, number of astronauts and altitude is 0. If you print the content of the space station after doing those operations, it's going to work:
public static void main(String[] args) {
SpaceStation ss = new SpaceStation("ISS", 419700.0);
ss.addAstronaut("Smith", 167.64, 81.65);
ss.addAstronaut("John", 185.43, 100.30);
ss.addAstronaut("Joey", 175.38, 90.38);
ss.setAltitude(400.0);
System.out.println(ss); // This line was moved after the addAstronaut and setAltitude methods.
}
3- As #sagi flagged, in the constructor, you're declaring and initializing another variable than in your class, but with the same name. Technically, doubles and integers are already initialized with 0.0 so you don't really notice it, but the variables altitude and totalAstronauts in your constructor are useless as they are. Suggesting to update the constructor like this:
public SpaceStation(String name, double
weight) {
this.name = name;
altitude = 0; // Removed "int"
totalAstronauts = 0; //Removed "int"
Astronauts = new Astronaut[3];
}
4- As #sagi flagged, you're re-initializing the Astronaut array every time you add an astronaut. You need to initialize it in the constructor once, and presumably set the astronauts in the array every time you add one.
With all of those comments, the SpaceStation class should look like this:
package gov.nasa.spacevehicles;
import gov.nasa.personnel.Astronaut;
public class SpaceStation {
//private members
private String name;
private double stationWeight;
private double altitude;
private Astronaut[] Astronauts;
private int totalAstronauts;
//overloaded constructor
public SpaceStation(String name, double
weight) {
this.name = name;
altitude = 0;
totalAstronauts = 0;
Astronauts = new Astronaut[3];
}
//method
public void addAstronaut(String name, double
height, double weight) {
Astronauts[totalAstronauts] = new Astronaut(name, height, weight);
stationWeight = stationWeight + weight;
totalAstronauts++;
}
public double setAltitude(double altitude) { return this.altitude = altitude; }
public String toString() {
return "SpaceStation: " + name + "\n" +
"Weight(kg): " + stationWeight + "\n" +
"Altitude(km): " + (altitude) + "\n" +
"Astronauts: " + (totalAstronauts);
}
public static void main(String[] args) {
SpaceStation ss = new SpaceStation("ISS", 419700.0);
ss.addAstronaut("Smith", 167.64, 81.65);
ss.addAstronaut("John", 185.43, 100.30);
ss.addAstronaut("Joey", 175.38, 90.38);
ss.setAltitude(400.0);
System.out.println(ss);
}
}
(1) The constructor of SpaceStation does not set the passed in values of name and weight to the parameters of the SpaceStation object. Add this.name = name and this.stationWeight = weight to the constructor. The this keyword tells Java that the variable you are referring to is the parameter of the object that the constructor is being called for.
The constructor also creates new variables named altitude and totalAstronauts that exist only inside of the constructor. To change the values of the parameters of the object the constructor is called for, add this.altitude = altitude and this.totalAstronauts = totalAstronauts to the constructor.
//overloaded constructor
public SpaceStation(String name, double weight) {
this.altitude = 0;
this.totalAstronauts = 0;
this.name = name;
this.stationWeight = weight;
}
(2) Your main method prints ss before you perform operations on it. Place it after the other code in your main:
public static void main(String[] args) {
SpaceStation ss = new SpaceStation("ISS", 419700.0);
ss.addAstronaut("Smith", 167.64, 81.65);
ss.addAstronaut("John", 185.43, 100.30);
ss.addAstronaut("Joey", 175.38, 90.38);
ss.setAltitude(400.0);
System.out.println(ss);
}
(3) The Astronauts array is overwritten every time addAstronaut() is called. Fix this by creating and adding a new Astronaut instance to the Astronauts array in addAstronaut(). You should add a line to the constructor to initialize the array to an empty array of a size of 3 or greater so there is space to add Astronaut objects in addAstronaut().
//overloaded constructor
public SpaceStation(String name, double weight) {
this.altitude = 0;
this.totalAstronauts = 0;
this.name = name;
this.stationWeight = weight;
// Add this line
Astronauts = new Astronaut[10];
}
//method
public void addAstronaut(String name, double height, double weight) {
// Adds a new Astronaut object to the array at index totalAstronauts
Astronauts[totalAstronauts] = new Astronaut(name, height, weight);
stationWeight = stationWeight + weight;
totalAstronauts++;
}
There are mainly 2 errors due to which name is been shown has null.
1: You haven't set name in your constructor, Which resulted in name having a default value of null.
So when you say this.name = name it tells that I have this in me, please look and set its value.
//overloaded constructor
public SpaceStation(String name) {
this.name = name; // changed
int altitude = 0;
Astronauts = new Astronaut[3];
int totalAstronauts = 0;
}
Also in the main function, you were trying to print it before setting the values for it.
You should have first given the values for it and then print it.
public static void main(String[] args) {
SpaceStation ss = new SpaceStation("ISS", 419700.0);
ss.addAstronaut("Smith", 167.64, 81.65);
ss.addAstronaut("John", 185.43, 100.30);
ss.addAstronaut("Joey", 175.38, 90.38);
ss.setAltitude(400.0);
System.out.println(ss); // changed
}
Additionally, I see you have made an Astronaut[] Astronauts array but never added any Astronauts in it. So what's the whole point of it?
When you were adding Astronauts it only stored the total numbers of astronauts but never an actual Astronauts Object.
//method
public void addAstronaut(String name, double
height, double weight, Astronaut object) {
Astronauts[totalAstronauts] = object; // changed
stationWeight = stationWeight + weight;
totalAstronauts++;
}
Main:
public static void main(String[] args) {
SpaceStation ss = new SpaceStation("ISS");
ss.addAstronaut("Smith", 167.64, 81.65, new Astronaut("Smith", 167.64, 81.65));
ss.addAstronaut("John", 185.43, 100.30, new Astronaut("John", 185.43, 100.30));
ss.addAstronaut("Joey", 175.38, 90.38, new Astronaut("Joey", 175.38, 90.38));
ss.setAltitude(400.0);
System.out.println(ss);
// (Added) Printing astronauts from array
for(Astronaut a : ss.Astronauts) {
System.out.println(a);
}
}
Astronaut class:
public class Astronaut {
//private fields
private String name;
private double height;
private double weight;
//defualt constructor
public Astronaut() { }
//overloaded constructor
public Astronaut (String name, double height, double weight) {
this.name = name;
this.height = height;
this.weight = weight;
}
// Added
public String toString() {
return "\nAstronaut Name: "+name+"\n"+name+" Height: "+height+"\n"+name+" Weight: "+weight;
}
}
Output:
SpaceStation: ISS
Weight(kg): 272.33
Altitude(km): 400.0
Astronauts: 3
Astronaut Name: Smith
Smith Height: 167.64
Smith Weight: 81.65
Astronaut Name: John
John Height: 185.43
John Weight: 100.3
Astronaut Name: Joey
Joey Height: 175.38
Joey Weight: 90.38

How to calculate only integer types in array?

import java.util.*;
class Distance {
private String name;
private int dist;
public Distance(String name, int dist) {
this.name = name;
this.dist = dist;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getDist() {
return dist;
}
public void setDist(int dist) {
this.dist = dist;
}
public String toString() {
return "Distance [name=" + name + ", school street=" + dist + "]";
}
}
class DistanceComp {
public static Distance longdistance(Distance[] dim) {
Distance max = dim[0];
for (int i = 1; i < dim.length; i++) {
if (max.getDist() < dim[i].getDist())
max = dim[i];
}
return max;
}
public static Distance shortdistance(Distance[] dim) {
Distance min = dim[0];
for (int i = 1; i < dim.length; i++) {
if (min.getDist() > dim[i].getDist())
min = dim[i];
}
return min;
}
}
public class week03_01 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Distance[] dist = new Distance[3];
System.out.print(">> how many students? : ");
int num = in.nextInt();
for (int i = 0; i < num; i++) {
System.out.print(">> name and distance : ");
dist[i] = new Distance(in.next(), in.nextInt());
}
System.out.println("\na student with the longest commute to school : " + DistanceComp.longdistance(dist));
System.out.println("a student with the shortest commute to school : " + DistanceComp.shortdistance(dist));
System.out.println("school distance difference is " + );
}
}
I also want to print the "shool distance differecnce".
but it doesn't calculate. i think it has String types.
I think calculate only integer types in an array, but i don't know the code.
Or is s there any other way? Ask for advice.
In your DistanceComp class, create a method to subtract two Distances similar like you did for longdistance and shortdistance:
public static int subtractDistance(Distance dist1, Distance dist2) {
int difference = Math.abs(dist1.getDist() - dist2.getDist());
return difference;
}
Then, use that in your System.out:
System.out.println("school distance difference is " + DistanceComp.subtractDistance(DistanceComp.longdistance(dist), DistanceComp.shortdistance(dist)));
Some notes fyi:
Your code currently only works with 3 students.
Instead of using long names, assign them to a shorter-named variable. This helps with code readability.

How to fix "reached end of file while parsing"

I am writing a program to find and display the student with the highest GPA, as well as the student with the lowest GPA out of a class with 4 attributes (first name, last name, age, GPA).
The output for my code results in "build successful," but the parsing error still shows up and there isn't the proper output information.
public class app
{
public static void main(String args[ ])
{
student st1 = new student("Rebecca", "Collins", 22, 3.3);
student st2 = new student("Alex", "White", 19, 2.8);
student st3 = new student("Jordan", "Anderson", 22, 3.1);
student[ ] studentArray = new student[3];
studentArray[0] = st1;
studentArray[1] = st2;
studentArray[2] = st3;
var maxStudent = studentArray[0];
// Start at 1 because we assumed the first student in the array
// has the current max.
//
for (int i = 1; i < studentArray.length; i++)
{
// If the current student has a GPA higher than the student
// with the current max, make the current student the student
// with the current max.
//
if(studentArray[i].gpa > maxStudent.getGpa())
{
boolean max = false;
boolean min;
min = false;
for (student studentArray1 : studentArray) {
boolean gpa = false;
}
System.out.print("The highest GPA is: "+max);
System.out.println();
System.out.print("The lowest GPA is: "+min);
System.out.println();
System.out.println("Name: "+ studentArray[i].firstName + " "+ studentArray[i].lastName);
System.out.println("Age: "+ studentArray[i].age);
System.out.println("GPA: "+ studentArray[i].gpa);
}
}
public class student
{
//class variables
public String firstName;
public String lastName;
public int age;
public double gpa;
public int max = 0;
public int min = 0;
//constructor method
student(String a, String b, int c, double d)
{
firstName = a;
lastName = b;
age = c;
gpa = d;
}
student(String a, String b, int c, double d, int e, int f)
{
firstName = a;
lastName = b;
age = c;
gpa = d;
min = e;
max = f;
}
//a method that returns the student's complete name
String getInfo()
{
return getFirstName() +" " + getLastName() +" " + getMax();
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(String fn)
{
firstName = fn;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String ln)
{
lastName = ln;
}
public int getAge()
{
return age;
}
public void setAge(int x)
{
age = x;
}
public double getGpa()
{
return gpa;
}
public void getGpa(double g)
{
gpa = g;
}
public int getMax()
{
return max;
}
public void getMax(int e)
{
max = e;
}
public int getMin()
{
return min;
}
public void getMin(int f)
{
min = f;
}
}
I would appreciate any insight that addresses the error and solutions for what I can do to make this code work properly.
There are a number of (possible) issues with your posted code; you appear to be using an inner student class; your braces don't match up and your indentation doesn't seem to be consistent, and the var keyword doesn't exist in versions of Java prior to 10 (and we have no knowledge of your installed JDK or configured project compiler level). Your student(s) shouldn't have individual min and max fields.
There is some debate about the merits of a class with all public fields; but any possible advantage to that is negated when you also implement getters and setters for all of them.
You need two loops; one to find the min and max, one to display the student(s). Java naming conventions should be respected (class names start with a capital letter). And you have a getGpa(double) that should be a setter.
Fixing all of that, it might look something like
public class App {
public static class Student {
private String firstName;
private String lastName;
private int age;
private double gpa;
public Student(String a, String b, int c, double d) {
firstName = a;
lastName = b;
age = c;
gpa = d;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String fn) {
firstName = fn;
}
public String getLastName() {
return lastName;
}
public void setLastName(String ln) {
lastName = ln;
}
public int getAge() {
return age;
}
public void setAge(int x) {
age = x;
}
public double getGpa() {
return gpa;
}
public void setGpa(double g) {
gpa = g;
}
}
public static void main(String[] args) throws Exception {
Student st1 = new Student("Rebecca", "Collins", 22, 3.3);
Student st2 = new Student("Alex", "White", 19, 2.8);
Student st3 = new Student("Jordan", "Anderson", 22, 3.1);
Student[] studentArray = { st1, st2, st3 };
Student maxStudent = studentArray[0];
Student minStudent = studentArray[0];
for (int i = 1; i < studentArray.length; i++) {
if (studentArray[i].getGpa() > maxStudent.getGpa()) {
maxStudent = studentArray[i];
}
if (studentArray[i].getGpa() < minStudent.getGpa()) {
minStudent = studentArray[i];
}
}
System.out.printf("The highest GPA is: %.1f%n", maxStudent.getGpa());
System.out.printf("The lowest GPA is: %.1f%n", minStudent.getGpa());
for (Student s : studentArray) {
System.out.printf("Name: %s %s%n", s.getFirstName(), s.getLastName());
System.out.printf("Age: %d%n", s.getAge());
System.out.printf("GPA: %.1f%n", s.getGpa());
}
}
}
which I ran; producing
The highest GPA is: 3.3
The lowest GPA is: 2.8
Name: Rebecca Collins
Age: 22
GPA: 3.3
Name: Alex White
Age: 19
GPA: 2.8
Name: Jordan Anderson
Age: 22
GPA: 3.1
And, if you're using Java 8+, you could simplify the main code with DoubleSummaryStatistics by streaming the Student(s), mapping to the gpa value and then collecting the statistics. Like,
public static void main(String[] args) throws Exception {
Student st1 = new Student("Rebecca", "Collins", 22, 3.3);
Student st2 = new Student("Alex", "White", 19, 2.8);
Student st3 = new Student("Jordan", "Anderson", 22, 3.1);
Student[] studentArray = { st1, st2, st3 };
DoubleSummaryStatistics dss = Arrays.stream(studentArray).mapToDouble(Student::getGpa).summaryStatistics();
System.out.printf("The highest GPA is: %.1f%n", dss.getMax());
System.out.printf("The lowest GPA is: %.1f%n", dss.getMin());
Arrays.stream(studentArray).map(s -> String.format("Name: %s %s%nAge: %d%nGPA: %.1f", //
s.getFirstName(), s.getLastName(), s.getAge(), s.getGpa())).forEach(System.out::println);
}

ArrayList. ArrayList to int and double

I have the problem that I can't take a number from the arraylist and make it into a int or double which I have to do to cacluate the BMI using weight and height. Please have a look!
The assignment is to put in guests' weight, length, and name and sort the ones with a bad length to height ratio out. In the main I create an array with a couple of guests and when I run it says:
"Exception in thread "main" java.lang.NumberFormatException: For input string "name"
and
java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at Diet.putOnDiet(Diet.java:12)
at TestDiet.main(TestDiet.java:7)
The Diet class is as follows:
public class Diet{
public static ArrayList<Guest> putOnDiet(ArrayList <Guest> list){
ArrayList<Guest> namn = new ArrayList<Guest>();
ArrayList<Guest> hej = new ArrayList<Guest>();
for(int i = 0; i<=list.size()/3; i = i+3){
int langd = Integer.parseInt(list.get(i+1).toString()); //I dont know how to make this work
double vikt = Double.parseDouble(list.get(i).toString());
String name = list.get(i+2).toString();
if ((vikt) > 1.08*(0.9*(langd -100))){
namn.add(new Guest(vikt, langd, name));
}
}
return namn;
}
}
And the Guest class:
public class Guest {
private double weight; private double length; private String name;
public Guest(double weight, double length, String name){
this.name = name; this.weight = weight; this.length = length; // Maybe the problem is here. How do you modify the class to make it work?
}
public String getName() {
return name;
}
public double getWeight()
{
return weight;
}
public double getLength() {
return length;
}
public void setName(String name) {
this.name = name;
}
public void setWeight(double weight) {
this.weight = weight;
}
public void setLength(double length)
{ this.length = length;
}
public boolean isSlim() {
if (weight >= 1.08 * 0.9 * (length - 100)) {
return false;
}
else
return true;
}
public String toString() {
return name + "\n" + weight + "\n" + length;
}
}
Are you sure that the you are parsing an integer?
Well number parsing exception is thrown when it can't parse the number. When the string is not a number like "somthing#$%^&". So try replacing this line
int langd = Integer.parseInt(list.get(i+1).toString());
with this
try {
int langd = Integer.parseInt(list.get(i+1).toString());
} catch (NumberFormatException e) {
System.out.println(list.get(i+1).toString() +" : This is not a number");
System.out.println(e.getMessage());
}
EDIT After reading WOUNDEDStevenJones answer I also think you should not be even using toString() or parsing methods. See WOUNDEDStevenJones answer for more details.
It looks like you'll want to change it to
for (int i=0; i<list.size(); i++) {
double langd = list.get(i).getLength();
double vikt = list.get(i).getWeight();
String name = list.get(i).getName();
}
and kind of ignore your getString() method for this purpose
Note: I'm not sure what you're trying to do with your different indexes, but they'll probably all be .get(i)
The method list.get(i) will return an object of type Guest. Guest has methods, getWeight() and getLength().
list.get(i).getWeight()
This would actually give you a double value in return.
And,
Integer.parseInt(list.get(i).getWeight().toString())
This should be able to parse.
Hope this helps.
_san

bubble sorting an array of a class

I wrote a program that is supposed to read in records from a file and enter them into an array of a Student class. I then need to sort them by name.
import java.io.*;
import java.util.Scanner;
public class StudentTest
{
public static void main(String[] args)
{
String name;
String address;
String major;
double gpa;
int classLevel;
int college;
String blank;
String idNumber;
Scanner fileIn = null;
try
{
fileIn = new Scanner (new FileInputStream("student.dat"));
}
catch (FileNotFoundException e)
{
System.out.println("File not found");
System.exit(0);
}
Student[] aStudent = new Student[15];
int index = 0;
for (index=0; index <= 15; index++)
{
while (fileIn.hasNext())
{
name = fileIn.nextLine();
address = fileIn.nextLine();
major = fileIn.nextLine();
gpa = fileIn.nextDouble();
classLevel = fileIn.nextInt();
college = fileIn.nextInt();
fileIn.nextLine();
idNumber = fileIn.nextLine();
aStudent[index] = new Student(name, address, major, gpa, classLevel, college, idNumber);
aStudent[index].Display();
}
}
Student temp = null;
for (int pass = 0; pass < (index-1); pass++)
{
for (int c = 0; c < (index - 1); c++)
{
if (aStudent[].getName() > aStudent[c+1].getName())
{
temp = aStudent[];
aStudent[]=aStudent[+1];
aStudent[+1]=temp;
}
}
}
}
}
import java.util.Scanner;
public class Student
{
private String name;
private String address;
private String major;
private double gpa;
private int classLevel;
private int college;
private String idNumber;
Scanner keyboard = new Scanner(System.in);
public Student(String name, String address, String major, double gpa, int classLevel, int coll, String idNum)
{
this.name = name;
this.address = address;
this.gpa = gpa;
this.major = major;
this.classLevel = classLevel;
this.college = coll;
this.idNumber = idNum;
}
public String getName()
{
return name;
}
public String getAddress()
{
return address;
}
public String getMajor()
{
return major;
}
public double getGPA()
{
return gpa;
}
public int getClassLevel()
{
return classLevel;
}
public int getCollege()
{
return college;
}
public String getID()
{
return idNumber;
}
public void setAddress(String address)
{
}
public void setMajor(String maj)
{
}
public void setCollege(int coll)
{
}
public void Display()
{
System.out.println("Name: "+getName());
System.out.println("Address: "+getAddress());
System.out.println("Major: " + getMajor());
System.out.println("GPA: "+getGPA()+" Class Level: "+getClassLevel()+" College: "+getCollege());
System.out.println("ID: "+getID());
System.out.println("===============================");
}
}
I wrote the sort the way my proffessor described it in class, but I am still getting errors that "the > operator is undefined for the argument type(s) java.laungage.String"
Any help would be greatly appreciated.
thanks
Edit:
I used Ashan's suggestion and now it looks like this.
for (int pass = 0; pass < (index-1); pass++)
{
for (int c = 0; c < (index - 1); c++)
{
if (aStudent[c].getName().compareTo(aStudent[c+1].getName()) > 0)
{
temp = aStudent[c];
aStudent[c]=aStudent[+1];
aStudent[+1]=temp;
That cleared up that error. However, I am now getting a NullPointerException.
You cannot compare strings using operator such as < , > . To compare strings there is a methodd provided in String class called compareTo. This method compares two strings lexicographically.
compareTo returns
0 incase both the strings are lexicographically equal
-1 if the calling string is lexicographically smaller than the input string
1 if the calling string is lexicographically larger than the input stirng
You can replace the following condition
if (aStudent[].getName() > aStudent[c+1].getName())
using compareTo method as:
if (aStudent[].getName().compareTo(aStudent[c+1].getName()) > 0)
I think error is because you cannot compare how big is the name or how small it is. Making a bubble search to sort names by alphabetical order, you need to check their first characters ASCII. Which is a pretty easy thing to do. I am not good at Java, but C++. So algorithms are same ;) Good luck ;)
You may want to use compareTo() of String. > and < are used for int, float numbers, characters and etc., not for objects like strings. If objects support compare operations, it must implement the Comparable interface, in which you will define the compareTo() method.
This method will return -1 if it is less than the other, 0 if they are equal and 1 if it is greater than the other object.

Categories

Resources