I am writing a simple start-up java program. The problem I am facing is that the company name is not being added properly.
public class Company {
public static BufferedReader br;
public static BufferedReader br1;
public static String numberOfCompanies;
public static void main(String[] args) {
// TODO Auto-generated method stub
CompanyDetails qw = new CompanyDetails();
try{
//Scanner in = new Scanner(System.in);
br = new BufferedReader(new InputStreamReader(System.in));
br1 = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter number of companies: ");
numberOfCompanies = br.readLine();
int G = Integer.parseInt(numberOfCompanies);
for (int i = 1; i <= G; i++) {
qw = new CompanyDetails();
System.out.println("Enter name of the company: ");
String company = br1.readLine();
qw.company(company, i);
}
for (int i = 0; i <= G; i++) {
qw.companySummary(G);
}
} catch (IOException io) {
io.printStackTrace();
}
}
}
class CompanyDetails {
String company, name;
public String input;
public static BufferedReader br;
public double iE;
public static String numberOfCompanies;
String nameOfCompany;
String[] nameofCompany1 = new String[100];
int ir,i,employee;
ArrayList<String> bulk = new ArrayList<String>();
public String[] company(String input, int i) {
// TODO Auto-generated method stub
//ArrayList bulk = new ArrayList();
//for(int ith = i; ith<= 2; i++){
nameOfCompany = i+input;
bulk.add(nameOfCompany);
bulk.add(nameOfCompany);
// }
return nameofCompany1;
}
public void employee(double d) {
// TODO Auto-generated method stub
ir = (int)d;
}
public void companySummary(int G) {
System.out.println("Number of companies: " + G);
System.out.println("Name of company: " +bulk +" ");
System.out.println("Number of employees: "+ir);
}
}
The output I am getting is
Why aren't I getting 234 at the position 1 of the arraylist ??
You are creating a new CompanyDetails object in each iteration of the loop, there by loosing your earlier object:
for (int i = 1; i <= G; i++) {
qw = new CompanyDetails();
You are already creating an CompanyDetails object at the start of main method:
CompanyDetails qw = new CompanyDetails();
So you don't have to do it again in the for loop.
public String[] company(String input, int i) {
nameOfCompany = i+input;
bulk.add(nameOfCompany);
bulk.add(nameOfCompany); .// Why are you adding nameOfCompany twice .
return nameofCompany1; //Why are you returning nameofCompany1 which is null here
}
qw = new CompanyDetails(); //this line should be out of the loop.
Work on Naming Convention.
Please provide more details on what you want to do and what output you expect .
Take a look at code-snippet: qw = new CompanyDetails(); is instantiated per loop.
It should be:
qw = new CompanyDetails();
for (int i = 1; i <= G; i++) {
...
}
As #CodeBuzz pointed out : remove bulk.add(nameOfCompany); in company() method and also do not iterate the qw.companySummary(G); method.
In your CompanyDetails class remove one line bulk.add(nameOfCompany); in the method public String[] company(String input, int i) and put qw = new CompanyDetails(); outside of the for loop in you main method and it will work fine.
Main class
public class Company {
public static BufferedReader br;
public static BufferedReader br1;
public static String numberOfCompanies;
public static void main(String[] args) {
// TODO Auto-generated method stub
CompanyDetails qw = new CompanyDetails();
try{
//Scanner in = new Scanner(System.in);
br = new BufferedReader(new InputStreamReader(System.in));
br1 = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter number of companies: ");
numberOfCompanies = br.readLine();
int G = Integer.parseInt(numberOfCompanies);
qw = new CompanyDetails();
for (int i = 1; i <= G; i++) {
System.out.println("Enter name of the company: ");
String company = br1.readLine();
qw.company(company, i);
}
for (int i = 0; i <= G; i++) {
qw.companySummary(G);
}
} catch (IOException io) {
io.printStackTrace();
}
}
}
CompanyDetails class
class CompanyDetails {
String company, name;
public String input;
public static BufferedReader br;
public double iE;
public static String numberOfCompanies;
String nameOfCompany;
String[] nameofCompany1 = new String[100];
int ir,i,employee;
ArrayList<String> bulk = new ArrayList<String>();
public String[] company(String input, int i) {
// TODO Auto-generated method stub
//ArrayList bulk = new ArrayList();
//for(int ith = i; ith<= 2; i++){
nameOfCompany = i+input;
//bulk.add(nameOfCompany);
bulk.add(nameOfCompany);
// }
return nameofCompany1;
}
public void employee(double d) {
// TODO Auto-generated method stub
ir = (int)d;
}
public void companySummary(int G) {
System.out.println("Number of companies: " + G);
System.out.println("Name of company: " +bulk +" ");
System.out.println("Number of employees: "+ir);
}
}
I can see your question has been well answered. I have one little remark I would like to add related to naming conventions. I would rename method company in the CompanyDetails class to AddCompany or registerCompany to make sure your readers understand the meaning of that method without having to go deep into its implementation details.
Regards,
The program for retrieving Employee details is below:
package employee;
import java.util.*;
public class Employee
{
String name, gender,address;
int id;
float salary,da,hra,gross_pay;
public void getdata()
{
Scanner in= new Scanner(System.in);
System.out.println("Enter the name of employee");
name=in.next();
System.out.println("Enter the id of employee");
id=in.nextInt();
System.out.println("Enter the gender of employee");
gender=in.next();
System.out.println("Enter the address of employee");
address=in.next();
}
public void calc()
{
Scanner in= new Scanner (System.in);
System.out.println("enter the salary of employee");
salary=in.nextFloat();
da=salary*15/100;
hra=salary*10/100;
gross_pay=salary+da+hra;
}
public void display()
{
System.out.println("Employee Details");
System.out.println("Employee name:"+name+" ");
System.out.println("Employee id:"+id+" ");
System.out.println("Employee gender:"+gender+" ");
System.out.println("Employee address:"+address+" ");
System.out.println("Employee salary:"+salary+" ");
System.out.println("da amount"+da+" ");
System.out.println("hra amount:"+hra+" ");
System.out.println("Gross_pay of employee:"+gross_pay+" ");
}
public static void main(String[] args)
{
Employee emp=new Employee();
emp.getdata();
emp.calc();
emp.display();
}
}
Output:
Enter the name of employee
Raju
Enter the id of employee
20
Enter the gender of employee
Male
Enter the address of employee
XYZ Street, India.
Enter the salary of employee
45000
Employee Details
Employee name:Raju
Employee id:20
Employee gender:Male
Employee address:XYZ
Employee salary:45000.0
DA amount6750.0
HRA amount:4500.0
Gross_pay of employee:56250.0
Related
I am trying to make a program that takes input from the user, searches through 2D array and prints out if the input matches data from the arrays. So, basically if the user types in VA, it should output Virginia. I am reading data from a Binary file that has 2 rows of data. The 1st row contains 2 letter abbreviations for all the states and the 2nd row contains the state names. For example: VA Virginia and in new line FL Florida and so on. Below is what I have so far. readStateFile() method works fine. I just need some help with getState method.
public static void main(String[] args) throws IOException {
try {
int age = getAge();
String[][] states = readStateFile();
String state = getState(states);
int ZIPCode = getZIPcode();
System.out.printf("\nAge:\t\t%d\n", age);
System.out.printf("Address:\t%s %s\n\n", ZIPCode, state);
System.out.println("Your survey is complete. " + "Your participation has been valuable.");
} catch (CancelledSurveyException e) {
System.out.println(e.getMessage());
} finally {
System.out.println("Thank you for your time.");
}
}
private static String getState(String[][] states) throws IOException {
states = readStateFile();
String in = "";
String[][] abb;
abb = states;
System.out.println("Please enter the 2 letter state abbrevation or 'q' to quit: ");
Scanner st = new Scanner(System.in);
in = st.next();
if (in.equals("q")) {
System.out.println("Your survey was cancelled.\n" + "Thank you for your time.");
System.exit(0);
}
if (abb.equals(states)) {
for (int i = 0; states[0][i] != null; i++) {
if (abb.equals(states[0][i])) {
for (int state = 1; state <= 100; state++) {
System.out.println(states[0][i]);
}
}
}
} else {
System.out.println("You've entered invalid state abbrevation.");
}
return in;
}
private static String[][] readStateFile() throws IOException {
String states[][] = new String[50][50];
try {
FileInputStream fstream = new FileInputStream("states copy.bin");
DataInputStream inputFile = new DataInputStream(fstream);
for (int i = 0, j = i + 1; i < 50; i++) {
states[i][0] = inputFile.readUTF();
states[i][j] = inputFile.readUTF();
// System.out.println(states);
}
inputFile.close();
return states;
} catch (EOFException e) {
System.out.println("Survey Cancelled");
}
return states;
} ```
Instead of using a multidimensional array, it might be more helpful to use a HashMap.
Each abbreviation is used as a key, and the name of the state can be found using that key as a lookup. Illustrated below:
public static void main(final String[] args)
{
try
{
final Map<String, String> states = readStateFile();
// Display the contents of the file
// for (final Map.Entry<String, String> s : states.entrySet())
// {
// System.out.println(s.getKey() + " = " + s.getValue());
// }
final String state = getState(states);
final int age = getAge();
final int postalCode = getZIPcode();
System.out.println();
System.out.printf("Age:\t\t%d\n", Integer.valueOf(age));
System.out.printf("Address:\t%s %s\n\n", Integer.valueOf(postalCode), state);
System.out.println("Your survey is complete. Your participation has been valuable.");
}
catch (final IOException ex)
{
System.out.println(ex.getMessage());
}
System.out.println("Thank you for your time.");
}
private static String getState(final Map<String, String> states)
{
System.out.println("Please enter the 2 letter state abbrevation or 'q' to quit: ");
final StringBuilder sb = new StringBuilder();
try (final Scanner st = new Scanner(System.in))
{
final String stateAbbrev = st.next().toUpperCase(Locale.getDefault());
if ("Q".equals(stateAbbrev))
{
System.out.println("Your survey was cancelled." + System.lineSeparator() + "Thank you for your time.");
System.exit(0);
}
if (states.containsKey(stateAbbrev))
{
final String stateName = states.get(stateAbbrev);
sb.append(stateName);
}
else
{
System.out.println("You've entered an invalid state abbrevation: " + stateAbbrev);
}
}
return sb.toString();
}
private static Map<String, String> readStateFile() throws IOException
{
final List<String> lines = Files.readAllLines(Paths.get("C:/states copy.bin"));
// Get a list of items, with each item separated by any whitespace character
final String[] stateAbbrev = lines.get(0).split("\\s");
final String[] stateNames = lines.get(1).split("\\s");
final Map<String, String> states = new HashMap<>();
for (int i = 0; i < stateAbbrev.length; i++)
{
states.put(stateAbbrev[i], stateNames[i]);
}
return states;
}
So I am a beginner in Java and my professor has us doing this assignment and I've been looking around but I can't seem to find the right answer for my type of code. We had to create a class file and then a public class file to test it.
import java.io.Serializable;
public class Person implements Serializable {
String Fname = new String();
String MI = new String();
String Lname = new String();
String age = new String();
String gpa = new String();
// int age = 20;
// double gpa = 0.0;
String Major = new String();
String answer;
//***********************************************
// The methods declared will go below
// The first method is for the first name
public String getFname() {
return Fname;
}
public void setFname(String Fname) {
this.Fname = Fname;
}
// This method is for the Middle Initial
public String getMI() {
return MI;
}
public void setMI(String MI) {
this.MI = MI;
}
// This method is for the Last name
public String getLname() {
return Lname;
}
public void setLname(String Lname) {
this.Lname = Lname;
}
// This method is for the Age
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
// This method is for the GPA
public String getGpa() {
return gpa;
}
public void setGpa(String gpa) {
this.gpa = gpa;
}
// This method is for the Major
public String getMajor() {
return Major;
}
public void setMajor(String Major) {
this.Major = Major;
}
}
The Person.java code is Serializable is supposed to be written to a fhm file and then Deserialized in order to print the contents of the file into terminal (Unix). Below is the main code which is the TestPerson code that will read the class Person code.
import java.util.Scanner;
import java.io.*;
public class TestPerson {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Person[] Peeps = new Person[3];
Peeps[0] = new Person();
Peeps[1] = new Person();
Peeps[2] = new Person();
Scanner scan = new Scanner(System.in);
String Answer = new String();
String age1 = new String();
String gpa1 = new String();
for (int i = 0; i < Peeps.length - 1; i++) {
// for (int i = 0; i < 3; i++) {
System.out.print("What is the First Name? ");
Answer = scan.nextLine();
Peeps[i].setFname(Answer);
System.out.print("What is MI? ");
Answer = scan.nextLine();
Peeps[i].setMI(Answer);
System.out.print(" What is Last Name? ");
Answer = scan.nextLine();
Peeps[i].setLname(Answer);
System.out.print(" What is the Age? ");
age1 = scan.nextLine();
int age = Integer.parseInt(age1);
// age = scan.nextInt();
Peeps[i].setAge(age1);
System.out.print(" What is the GPA? ");
gpa1 = scan.nextLine();
double gpa = Double.parseDouble(gpa1);
Peeps[i].setGpa(gpa1);
System.out.print(" What is the Major? ");
Answer = scan.nextLine();
Peeps[i].setMajor(Answer);
}
for (int i = 0; i < 3; i++) {
System.out.print(Peeps[i]);
}
try {
FileOutputStream fileOut = new FileOutputStream("Peeps.fhm");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(Peeps);
out.close();
fileOut.close();
System.out.println("\nSerialization Successful\n");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fileIn = new FileInputStream("Peeps.fhm");
ObjectInputStream in = new ObjectInputStream(fileIn);
System.out.println("Deserialized Data: \n" + in.readObject().toString());
in.close();
fileIn.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
My professor wants me to prompt the user to enter data for two of the Person objects at the Terminal and then copy the reference to one of two populated Persons to the last Person. Then the program will write all three Persons to a disk file with the extension of ".fhm" (Which I have completed). My question is how do I copy the reference? My second question is also how do I properly deserialize the file because when I run it, it works but the issue that pops up is that it tells me this:
Deserialized Data:
[LPerson;#5e481248
He wants it to print the information that was inputted by the user. I checked the fhm file that it writes to and it gathers all the information so I'm not sure what I'm doing wrong. Any help would be appreciated guys, sorry the post is kind of long. Thanks in advance.
I'm not sure what you meant by the "copy the reference" part.
The deserialization seems to be working well.
But in your code you're effectively just calling .toString() to print an array, which is probably not what you want.
You probably want to iterate over the items and print them one by one:
FileInputStream fileIn = new FileInputStream("Peeps.fhm");
ObjectInputStream in = new ObjectInputStream(fileIn);
Person[] peeps = in.readObject();
System.out.println("Deserialized Data:");
for (Person person : peeps) {
System.out.printf("First Name: %s MI: %s Last Name: %s%n",
person.getFname(), person.getMI(), person.getLname());
}
Your object is basically a Java array. To print it out, you could use:
System.out.println("Deserialized Data: \n" + Arrays.toString(in.readObject()));
I am trying to perform binary search on an object array list. The user must type in admin number to perform search. Here is my code :
File Controller class to read file from .text file
public class FileController extends StudentApp{
private String fileName;
public FileController() {
String fileName = "student.txt";
}
public FileController(String fileName) {
this.fileName = fileName;
}
public ArrayList<String> readLine() {
ArrayList<String> studentList = new ArrayList<String>();
try {
FileReader fr = new FileReader(fileName);
Scanner sc = new Scanner(fr);
while (sc.hasNextLine()) {
studentList.add(sc.nextLine());
}
fr.close();
} catch (FileNotFoundException exception) {
System.out.println("File " + fileName + " was not found");
} catch (IOException exception) {
System.out.println(exception);
}
return studentList;
}
Student Class with all the setter & getter and compareTo method
public Student(String adminNo, String name, GregorianCalendar birthDate) {
this.adminNo = adminNo;
this.name = name;
this.birthDate = birthDate;
}
public Student(String record) {
Scanner sc = new Scanner(record);
sc.useDelimiter(";");
adminNo = sc.next();
name = sc.next();
birthDate = MyCalendar.convertDate(sc.next());
test1 = sc.nextInt();
test2 = sc.nextInt();
test3 = sc.nextInt();
}
public String toString(){
return (adminNo + " " + name + " " + MyCalendar.formatDate(this.birthDate));
}
public static ArrayList<Student> readStudent(String file) {
FileController fc = new FileController(file);
ArrayList<Student> recs = new ArrayList<Student>();
ArrayList<String> recsReturn = new ArrayList<String>();
recsReturn = fc.readLine();
for (int index = 0; index < recsReturn.size(); index++) {
String input = recsReturn.get(index);
recs.add(new Student(input));
}
return recs;
}
public int compareTo(Student s) {
return Compare(this, s);
}
public int Compare(Student s1, Student s2){
if(s1.getAdminNo().equals(s2.getAdminNo())) {
return 0;
}else{
return 1;
}
}
Executable main method lies here, in StudentSearch Class
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
ArrayList <Student> studentList = new ArrayList <Student> ();
studentList = Student.readStudent("student.txt");
Collections.sort(studentList);
System.out.println("Enter student admin number: ");
String searchAdminNo = sc.next();
int pos = Collections.binarySearch(studentList, new Student(searchAdminNo));
System.out.println(pos);
}
I want to perform search by using the user input admin number. However, here's the error message:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at StudentGradeApps.Student.<init>(Student.java:22)
at StudentGradeApps.StudentSearch.main(StudentSearch.java:14)
I think the problem lies at the compareTo method and my binary search. Because when I removed them, my program can get the array list fine. The error only occurs when I try to perform search on my object list. Any help would be appreciated.
Thanks in advance.
As the error message say, the exception is occurring within the Student constructor -
public Student(String record) {
Scanner sc = new Scanner(record);
sc.useDelimiter(";");
adminNo = sc.next();
name = sc.next();
birthDate = MyCalendar.convertDate(sc.next());
test1 = sc.nextInt();
test2 = sc.nextInt();
test3 = sc.nextInt();
}
You are invoking the constructor here -
int pos = Collections.binarySearch(studentList, new Student(searchAdminNo));
searchAdminNo probably doesn't have that many tokens (delimited by ;) as you are reading in the constructor.
I am writing a program for a user to add a string to an ArrayList then display it.
It doesn't work and it seems there is a problem with compareTo().
Here is my code:
public class database {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static String country[] = new String[100];
static String capital[] = new String[100];
static double population[] = new double[100];
static List<String> countriesList = Arrays.asList(country);
public static void main(String args[]) throws IOException {
country[0] = "Barbados";
country[1] = "France";
country[2] = "Nigeria";
country[3] = "USA";
country[4] = "Japan";
capital[0] = "Bridgetown";
capital[1] = "Paris";
capital[2] = "Abuja";
capital[3] = "Washington";
capital[4] = "Tokyo";
population[0] = 65.3;
population[1] = 315.8;
population[2] = 170.1;
population[3] = 2840;
population[4] = 126.7;
public static void searchCountry() throws IOException {
Scanner in = new Scanner(System.in);
String output;
int size, i;
System.out.println("Search Country:");
output = br.readLine();
boolean found = false;
for (i = 0; i < country.length; i++)
if (output.compareTo(country[i]) == 0) {
found = true;
break;
}
if (found)
System.out.println(output + " is found at index " + i);
else
System.out.println(output + "Country not found, choose Add country to add it");
public static void listCountry() throws IOException {
for (String c : countriesList) {
if (!=null)
System.out.println(c);
}
}
}
There is also a problem with the null at the end of my code.
While writing code, you should better start from the beginning. i.e.
First, write class name and make sure it there is no problem with brackets
public class MyClass{
}
Then, write main method in it.
public class MyClass{
public static void main(String[] args){
}
}
Then, write your methods, and test it in main method.
public class MyClass{
public void mymethod(){
//do something
System.out.println("say something");
}
public static void main(String[] args){
MyClass mc = new MyClass();
mc.mymethod();
}
}
If you try to write everything in one shotm it wont work and if you are not expert it would be hard for you to solve problem.
You can't write a method in a method. Close the brackets of main() before you open the brackets of searchCountry()
You don't check anything against being null. Maybe you mean if(c != null)
Just write it this way and you should be fine:
public class database {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static String country[] = new String[100];
static String capital[] = new String[100];
static double population[] = new double[100];
static List<String> countriesList = Arrays.asList(country);
public static void main(String args[]) {
country[0] = "Barbados";
country[1] = "France";
country[2] = "Nigeria";
country[3] = "USA";
country[4] = "Japan";
capital[0] = "Bridgetown";
capital[1] = "Paris";
capital[2] = "Abuja";
capital[3] = "Washington";
capital[4] = "Tokyo";
population[0] = 65.3;
population[1] = 315.8;
population[2] = 170.1;
population[3] = 2840;
population[4] = 126.7;
searchCountry();
listCountry();
}
public void searchCountry() throws IOException {
Scanner in = new Scanner(System.in);
String output;
int size, i;
System.out.println("Search Country:");
output = br.readLine();
boolean found = false;
for (i = 0; i < country.length; i++)
if (output.compareTo(country[i]) == 0) {
found = true;
break;
}
if (found)
System.out.println(output + " is found at index " + i);
else
System.out.println(output + "Country not found, choose Add country to add it");
}
public void listCountry() {
for (String c : countriesList) {
if (c!=null)
System.out.println(c);
}
}
}
You forgot the c in c != null. You cannot define methods inside of methods in java. Also, use the equals method when testing forString equality, ie if (output.equals(country [i])).
This is a complete program that sorts the file by ID. However, I would like to sort it by grade. I modified it several times but it doesn't seem to work. Could someone please direct me where to change the ID to grade. Also, do you think this code can be simplified or are there any other code simpler than this code.
Sorry for the bad indentation, this source code can also be found here.
student.txt file:
4 A 87 A
5 B 99 A+
1 C 75 A
2 D 55 C
3 E 68 B
source:
import java.io.*;
import java.util.*;
class ShowData implements Comparable {
int id;
String name;
int marks;
String grade;
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setMarks(int marks) {
this.marks = marks;
}
public int getMarks() {
return marks;
}
public void setGrade(String grade) {
this.grade = grade;
}
public String getGrade() {
return grade;
}
public int compareTo(Object Student) throws ClassCastException {
if (!(Student instanceof ShowData))
throw new ClassCastException("Error");
int ide = ((ShowData) Student).getId();
return this.id - ide;
}
}
public class SortFile {
SortFile() {
int j = 0;
ShowData data[] = new ShowData[5];
try {
FileInputStream fstream = new FileInputStream("C:/student.txt");
// Use DataInputStream to read binary NOT text.
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
ArrayList list = new ArrayList();
while ((strLine = br.readLine()) != null) {
list.add(strLine);
}
Iterator itr;
for (itr = list.iterator(); itr.hasNext();) {
String str = itr.next().toString();
String[] splitSt = str.split(" ");
String id = "", name = "", marks = "", grade = "";
for (int i = 0; i < splitSt.length; i++) {
id = splitSt[0];
name = splitSt[1];
marks = splitSt[2];
grade = splitSt[3];
}
data[j] = new ShowData();
data[j].setId(Integer.parseInt(id));
data[j].setName(name);
data[j].setMarks(Integer.parseInt(marks));
data[j].setGrade(grade);
j++;
}
Arrays.sort(data);
File file = new File("C:/new.txt");
FileWriter fw = new FileWriter(file, true);
BufferedWriter out = new BufferedWriter(fw);
System.out.println("********Sorted by id********");
String strVal = "";
for (int i = 0; i < 5; i++) {
ShowData show = data[i];
int no = show.getId();
String name = show.getName();
int marks = show.getMarks();
String grade = show.getGrade();
System.out.println(no + " " + name + " " + marks + " " + grade);
String d = no + " " + name + " " + marks + " " + grade;
ArrayList al = new ArrayList();
al.add(d + "\n");
Iterator itr1 = al.iterator();
while (itr1.hasNext()) {
out.write(itr1.next().toString());
out.newLine();
}
}
out.close();
} catch (Exception e) {
}
}
public static void main(String[] args) {
SortFile data = new SortFile();
}
}
The compareTo() method is currently comparing the IDs, not the grades. Try compare the
marks instead.