reading .txt file contains employees information and printing out them (Java) - java

Please I need help, I am trying to get my code working properly. The code is supposed to read .txt file with the name A2Q1in.txt" and print out all the information that the file contains by using loadEmployees method. when compile the code I get 2 errors that I do not know how to fix them, please have a look at output at the end of question.
Code:
mport java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class A2Q1
{
public static void main(String[] parms)
{
Employee [] employees ;
String [] array_;
array_ = new String [50];
employees = loadEmployees();
System.out.println("\nProgram completed normally.");
}
public static Employee[] loadEmployees()
{
Employee[] employees;
BufferedReader fileIn;
String inputLine;
try
{
fileIn = new BufferedReader(new FileReader("A2Q1in.txt"));
inputLine = fileIn.readLine();
while (inputLine != null)
{
System.out.println(inputLine);
inputLine = fileIn.readLine();
}
fileIn.close();
}
catch (IOException ioe)
{
System.out.println(ioe.getMessage());
}
print String employees(employees);
}
}
/*********************************************************************/
/*********************************************************************/
class Employee
{
private String employeecomany;
private String name;
private String division;
private Double wage;
public Employee(String employeecomany, String name, String division, Double wage)
{
this.employeecomany = employeecomany;
this.name = name;
this.division = division;
this.wage = wage;
}
public double getWage()
{
return getWage;
}
public String toString()
{
return String.format("%-10s %3d $%4.2f $%5.2f ", employeecomany, name, division, getWage());
}
}
output errors
2 errors and 2 warnings found:
* Errors *
File: C:\Users\samiralbayati\Desktop\Comp 1020 JAVA assignment 2\A2Q1.java [line: 39]
Error: Syntax error, insert ";" to complete LocalVariableDeclarationStatement
File: C:\Users\samiralbayati\Desktop\Comp 1020 JAVA assignment 2\A2Q1.java [line: 68]
Error: getWage cannot be resolved to a variable

Try to remove the print String employees(employees); and write return employees;
and change your code
public double getWage()
{
return getWage;
}
to
public double getWage()
{
return wage;
}
This is because, you did not initialized or declared the getWage variable.

Related

Java file-I/O not reading

I have a problem with maing java reading a file for me. I have a .txt-file with all the danish islands but somehow it will not display in the console no matter how i try.
This is the class with the main method. From here it reads the file and splits the lines in order to put the data into an ArrayList.
public class DanishIslandFileReader {
private File inFile;
private List<DanishIsland> islandList;
public DanishIslandFileReader(String fName) {
inFile = new File(fName);
}
private void readFile() {
islandList = new ArrayList<DanishIsland>();
Scanner scan = null;
try {
scan = new Scanner(inFile);
} catch (FileNotFoundException fnfe) {
System.out.println(fnfe);
}
while (scan.hasNext()) {
String line = scan.nextLine();
String[] tokens = line.split(" ");
String name = tokens[0];
double circ = Double.parseDouble(tokens[1]);
double area = Double.parseDouble(tokens[2]);
int addr = Integer.parseInt(tokens[3]);
int adkm = Integer.parseInt(tokens[4]);
DanishIsland island = new DanishIsland(name, circ, area, addr, adkm);
System.out.println(island.toString());
islandList.add(island);
}
scan.close();
}
public List<?> getList() {
return islandList;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException {
System.out.println(new File(".").getAbsolutePath());
// DanishIslandFileReader fr = new DanishIslandFileReader("Islands punktum.txt");
DanishIslandFileReader fr = new DanishIslandFileReader("Islands komma.txt");
fr.readFile();
System.out.println("Result:\n" + fr.getList());
}
}
When the line has been split it goes through another class which turns the data into a String and puts it into another Arraylist which will be printed in the consol.
public class DanishIsland {
private String name;
private double circumference;
private double area;
private int addresses;
private int addrPerKm2;
public DanishIsland(String name, double circumference, double area,
int addresses, int addrPerKm2) {
super();
this.name = name;
this.circumference = circumference;
this.area = area;
this.addresses = addresses;
this.addrPerKm2 = addrPerKm2;
}
public String getName() {
return name;
}
public double getCircumference() {
return circumference;
}
public double getArea() {
return area;
}
public int getAddresses() {
return addresses;
}
public int getAddrPerKm2() {
return addrPerKm2;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(name);
builder.append("\t");
builder.append(circumference);
builder.append("\t");
builder.append(area);
builder.append("\t");
builder.append(addresses);
builder.append("\t");
builder.append(addrPerKm2);
builder.append("\n");
return builder.toString();
}
}
I do not get any errors or exceptions and the program run till it thinks the list has been printed.
Problem is that the list is empty and I can't seem to make any sort of "sout" from the .txt-file. Whar am I doing wrong?
Lolland 298,388 1234,96 38919 32
Bornholm 108,047 588,025 27125 46
Falster 145,926 516,268 26654 52
Mors 139,254 361,745 12374 34
Have you tried debugging it?
I think it is not entering
while (scan.hasNext())
because scan.hasNext returns false.
This could be a file permission issue.
Also this may be related:
Why is hasNext() False, but hasNextLine() is True?

Read data that has an integer and string in a text file - Java

I have read the file and it should print out the data on the console, but the problem is that I get this error message: Exception in thread "main" java.lang.NumberFormatException: For input string: "UNKNOWN". I've put the maximum length as an integer, but how do I put it as a string as well?
Here's what I have done so far:
import java.util.*;
import java.io.*;
public class Task1 {
public static void main(String[] args) {
List<Person> personFile = new ArrayList<>();
try {
BufferedReader br = new BufferedReader(new FileReader("people-data.txt"));
String fileRead = br.readLine();
while (fileRead != null) {
String[] peopleData = fileRead.split(":");
String commonName = personData[0];
String latinName = personData[1];
int maximumLength = Integer.parseInt(personData[2]);
Person personObj = new Person(commonName, latinName, maximumLength);
personFile.add(personObj);
fileRead = br.readLine();
}
br.close();
}
catch (FileNotFoundException ex) {
System.out.println("File not found!");
}
catch (IOException ex) {
System.out.println("An error has occured: " + ex.getMessage());
}
System.out.println(personFile);
}
}
Person Class:
import java.util.*;
public class Person1 {
private String commonName;
private String latinName;
private int maximumLength;
public Person1(String personName, String latinName, int maximumLength) {
this.commonName = personName;
this.latinName = latinName;
this.maximumLength = maximumLength;
}
public String getCommonName() {
return commonName;
}
public String getLatinName() {
return latinName;
}
public int getMaximumLength() {
return maximumLength;
}
#Override
public String toString() {
return null;
}
}
Text File:
Alisha Khan:Cephaloscyllium ventriosum:100
Jessica Lane:Galeocerdo cuvier:UNKNOWN
Michael Brown:Sphyrna mokarren:600
...
This line in your input file:
Jessica Lane:Galeocerdo cuvier:UNKNOWN
is causing problem on this line in your code:
int maximumLength = Integer.parseInt(personData[2]);
because parseInt throws NumberFormatException on UNKNOWN. You need to decide what you want to do in this case. For example this code will keep maximumLength to default value -1 when an invalid integer is encountered:
int maximumLength = -1;
try {
int maximumLength = Integer.parseInt(personData[2]);
} catch (NumberFormatException e) {
}
You should teach your code your convention of UNKNOWN. Currently the code treats it as number.

Java: Making .txt doc into String. Performing string methods [duplicate]

This question already has an answer here:
What does "Incompatible types: void cannot be converted to ..." mean?
(1 answer)
Closed 4 years ago.
import java.util.Scanner;
import java.io.File;
public class Book
{
private String bookString;
private String bookTitle;
private String bookAuthor;
public Book(String fileName, String title, String author)
{
readBook(fileName);
bookTitle = title;
bookAuthor = author;
}
public boolean containsTitle()
{
}
public int getNumOfCharacters()
{
}
public int countWords(String word)
{
}
public int countSentences()
{
}
public String randomWord(int length)
{
}
public int firstOccurrence(String word)
{
}
public String getSecondSentence()
{
}
public void readBook(String fileName)
{
bookString = "";
try
{
Scanner file = new Scanner(new File(fileName));
while (file.hasNextLine())
{
String line = file.nextLine();
bookString += line + "\n";
}
file.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
Here is some skeleton code that I am trying to finish. My first question is-- don't I have to store the readBook(fileName) in a variable? I tried to store it, then finish the getNumOfCharecters() method with:
bSL = bS.length()
return bSL
I am getting an error message. "incompatible types; void cannot be converted to java.lang.String"
Thanks to anyone willing to help.
The error you get should suggest you that the method is supposed to return a string. Change your method to :
public String readBook(String fileName)
{
bookString = "";
try
{
Scanner file = new Scanner(new File(fileName));
while (file.hasNextLine())
{
String line = file.nextLine();
bookString += line + "\n";
}
file.close();
}
catch (Exception e)
{
System.out.println(e);
}
return bookString;
}
then get the output into a variable like String bS = readBook( fileName );

Why am I getting null pointer exception in this program when using enhanced for loop

I am getting a null pointer exception in the selectAllStudent Method.
When I am using foreach loop but When I am using a normal loop it is working fine.
Please explain the reason. Thank you
Driver Class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) {
Student[] sdb = new Student[2];
try {
for (Student s : sdb) {
s = takeInput();
}
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}
selectAllStudent(sdb);
}
static void selectAllStudent(Student[] sdb) {
for (Student s : sdb) {
s.printStudentDetails(); // Getting NullPOinterException here
}
}
public static Student takeInput() throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the details ");
System.out.print("ROLL :"); int rollno = Integer.parseInt(in.readLine());
System.out.print("NAME :"); String name = in.readLine();
System.out.print("BRANCH :"); String branch = in.readLine();
return (new Student(rollno,name,branch));
}
}
Student Class
public class Student {
private int rollno;
private String name;
private String branch;
Student(int rollno, String name, String branch) {
this.rollno = rollno;
this.name = name;
this.branch = branch;
}
void printStudentDetails() {
System.out.println("ROLLNO :" + rollno);
System.out.println("NAME :" + name);
System.out.println("BRANCH :" + branch);
System.out.println("-------------------");
}
}
You are not assigning a new Student to the array in this for loop.
for (Student s : sdb) {
s = takeInput();
}
The takeInput method is returning a Student properly, but you've assigned it to a local reference s, not as an element in the array sdb. The elements of the array remain null, and the NullPointerException comes from attempting to call printStudentDetails on null in the selectAllStudent method.
You can convert the enhanced for loop to a standard for loop, assigning the Student with an array access expression.
for (int i = 0; i < sdb.length; i++)
{
sdb[i] = takeInput();
}

sort line by last name and in order

Ok so I have this code so far that sorts by job position, now It also needs to be sort by last name and in alphabetical order. Ive managed to make it by sort by position then give the average salary and total.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class faculty {
private static final String ASSISTANT = "assistant";
private static final String ASSOCIATE = "associate";
private static final String FULL = "full";
public static void main(String[] args) {
FileInputStream filestream;
BufferedReader reader;
PrintWriter writer;
String line;
double totalAssistant = 0;
double totalAssociate = 0;
double totalFull = 0;
try {
filestream = new FileInputStream("Faculty List.txt");
reader = new BufferedReader(new InputStreamReader(filestream));
writer = new PrintWriter("test.txt");
List<String> assistantList = new ArrayList<String>();
List<String> associateList = new ArrayList<String>();
List<String> fullList = new ArrayList<String>();
while ((line = reader.readLine()) != null) {
String[] split = line.split(" ");
double value = Double.parseDouble(split[split.length - 1]);
String type = split[split.length - 2];
if (ASSISTANT.equals(type)) {
assistantList.add(line);
} else if (ASSOCIATE.equals(type)) {
totalAssociate += value;
associateList.add(line);
} else if (FULL.equals(type)) {
totalFull += value;
fullList.add(line);
}
}
writeInFileOutput(writer, totalAssistant, assistantList);
writeInFileOutput(writer, totalAssociate, associateList);
writeInFileOutput(writer, totalFull, fullList);
reader.close();
writer.close();
} catch (IOException e) {
System.out.println(e);
} finally {
reader = null;
filestream = null;
writer = null;
}
}
private static void writeInFileOutput(PrintWriter writer, double totalSalary, List<String> listLines) {
for (String assistant : listLines) {
writer.append(assistant).append("\n");
}
writer.append("-------\n");
writer.append("Total Salary:$").append(String.valueOf(totalSalary)).append("\n");
writer.append("Average Salary: $")
.append(String.valueOf(totalSalary / listLines.size())).append(" \n\n");
}
}
Output
Pablo Bailey EDUC associate 68757.00
Lonnie Williamson GENS associate 134777.00
Raymond Page EDUC associate 120150.00
Wallace Fitzgerald BUSN associate 40889.00
Juana Robbins SOBL associate 93669.00
Steven Hall SOBL associate 117532.00
Melissa Davis EDUC associate 132186.00
Karla Valdez BUSN associate 16385.00
Melba Luna HLTH associate 70358.00
Sonja Washington HLTH associate 59302.00
Julio Diaz HLTH associate 102641.00
Virgil Briggs PAC associate 40936.00
Terrell Sherman EDUC associate 161595.00
Jorge Scott CSIS associate 124175.00
Tanya Duncan BUSN associate 178894.00
Troy Cannon BUSN associate 58890.00
-------
Total Salary: $3645049.0
Average Salary: $104144.25714285714
that's what my current output is, its sorted by rank. I now have to add to the list sort by last name first followed by first name alphabetically.this is just a small sample of the output cause the text file is pretty long.
The new lines can be added to the output.
I would make your stuff much more object oriented. So this means: introduce a new object employee that has some fields like following example:
public class Employee {
private String firstName;
private String familyName;
private String department;
private Enum jobPosition;
private double salary;
// Put constructor and some getters and setters for your field here
}
public enum JobPosition {
assistant,
associate,
full
}
When reading your input, split into the fields you need to create your employee and create 1 list with all your employees. Because you now have objects instead of a String containing multiple properties of one employee you can easily sort your objects on each property you want.
I'd use Aster's approach, and then either make Employee implement Comparable<Employee>, or make a Comparator<Employee>.
With Comparable<Employee>
public class Employee implements Comparable<Employee> {
#Override
public int compareTo(Employee e) {
int deptResult = this.department.compareToIgnoreCase(e.department);
if (deptResult != 0) {
return deptResult;
}
familyNameResult = this.familyName.compareToIgnoreCase(e.familyName);
if (familyNameResult != 0) {
return familyNameResult;
}
return this.firstName.compareToIgnoreCase(e.firstName);
}
}
With Comparator<Employee>
public class EmployeeComparator implements Comparator<Employee> {
#Override
public int compare(Employee e1, Employee e2) {
int deptResult = e1.getDepartment().compareToIgnoreCase(e2.getDepartment());
if (deptResult != 0) {
return deptResult;
}
familyNameResult = e1.getFamilyName().compareToIgnoreCase(e2.getFamilyName());
if (familyNameResult != 0) {
return familyNameResult;
}
return e1.getFirstName().compareToIgnoreCase(e2.getFirstName());
}
}

Categories