why is updateStocks() not changing price? - java

I have a method to read a text file of five stocks using Scanner and delimiter. I also have a method which should take a double multiplier and an array of stock objects and change the price with that multiplier. The method which reads the stock file functions correctly, however, when I attempt to change the stock objects that have been assigned values with the filereading method, it does not change the price. After I use method updateStocks(), I test stock[1] to see if the value has changed and it has not.
After I run this:
public class Main {
public static void main (String args[]) {
// stock object with which to call methods
Stock theStock = new Stock("", "", 0);
// this array holds the stocks to be read
Stock[] stocks = new Stock[100];
// here is the multiplier I am attempting to use
double multiplier = 1/3;
// first I read in the stocks file
theStock.readStocksWithScanner(stocks);
// then I call the updateStockPrices method
theStock.updateStockPrices(multiplier,stocks);
// lastly, I test to see if the method has functioned correctly
System.out.println(stocks[1]);
}
}
This is my output:
Apple AAPLE 152.70
Alphabet GOOGLE 873.96
IBM IBM 194.37
Microsoft MSFT 65.67
Oracle ORCLE 62.82
Company name: Apple Stock symbol: AAPLE Stock Price: 152.7
Press any key to continue . . .
Here is the method updateStockPrices:
// this is the method which does not seem to function as intended
public void updateStockPrices(double multiplier, Stock[] objects)
{
// I loop to the length of the array in the parameter
for(int i = 1; i < objects.length; i++)
{
// try to manipulate the stock
try{
double subtractThis = stocks[i].getPrice() * multiplier;
objects[i].setPrice(stocks[i].getPrice() - subtractThis);
}// and catch any null objects
catch(NullPointerException e){
// if null I then increment the counter
i++;}
// Is code missing in order for this to function as intended? or have I made a mistake?
}
}
and here is stocks.java:
import java.util.Scanner ;
import java.util.InputMismatchException ;
import java.io.FileInputStream ;
import java.io.IOException ;
import java.io.FileNotFoundException ;
import java.io.PrintWriter ;
public class Stock {
private static final double MULTIPLIER = (1/3);
public static final String FILE_NAME = "stocks1.txt";
public String newFile = "stocks2.txt";
public static final String FORMAT = "%-10s%6s\t%.2f%n";
private PrintWriter writer = null;
private String name = "";
private String symbol = "";
private double price = 0;
protected Stock stocks[] = new Stock[100];
FileInputStream inputStream = null;
String workingDirectory = System.getProperty("user.dir");
String absolutePath = workingDirectory + "\\" + FILE_NAME;
public Stock(String aName, String aSymbol, double aPrice)
{
this.name = aName;
this.symbol = aSymbol;
this.price = aPrice;
}
// the fileReading method reads the stocks in
public void readStocksWithScanner(Stock[] stocks)
{
this.stocks = stocks;
String workingDirectory = System.getProperty("user.dir");
String absolutePath = workingDirectory + "\\" + FILE_NAME;
FileInputStream inputStream = null;
try{
inputStream = new FileInputStream(absolutePath);
}
catch (FileNotFoundException e)
{
System.out.println("File not found: " + FILE_NAME);
System.out.println("Exiting program.");
System.exit(0) ;
}
Scanner inputFile = new Scanner(inputStream);
int lineNumber = 1;
try{
while(inputFile.hasNextLine())
{
inputFile.useDelimiter(",");
String name = inputFile.next();
inputFile.useDelimiter(",");
String symbol = inputFile.next();
inputFile.useDelimiter("[,\\s]") ;
Double thePrice = inputFile.nextDouble();
inputFile.nextLine();
// here the stocks are given the values found in the text file and initialized above
stocks[lineNumber] = new Stock(name, symbol, thePrice);
// I print them out using a format constant, in order to ensure the method has functioned correcly
System.out.printf(FORMAT, name, symbol, thePrice);
// then I increment the lineNumber
lineNumber++;
}
// I close the stream and should be left with a partially filled array of stock items
inputStream.close();
}catch (IOException e) {
System.out.println("Error reading line " + lineNumber + " from file " + FILE_NAME) ;
System.exit(0) ;
}
catch(InputMismatchException e) {
System.out.println("Couldn't convert price to a number on line " + lineNumber) ;
System.exit(0) ;}
}
public void setName(String name)
{
this.name = name;
}
public void setSymbol(String symbol)
{
this.symbol = symbol;
}
public void setPrice(double aPrice)
{
this.price = aPrice;
}
public String getName()
{
return name;
}
public String getSymbol()
{
return symbol;
}
public double getPrice()
{
return price;
}
public boolean equals(Object other)
{
if(other.getClass() != getClass() || other == null )
{
return false;
}
Stock stock = (Stock) other;
{
if(stock.getName() == getName() && stock.getSymbol() == getSymbol() && stock.getPrice() == getPrice())
{
return true;
}
return false;
}
}
public String toString()
{
return "Company name: " + getName() + " Stock symbol: " + getSymbol() + " Stock Price: " + getPrice();
}
// this is the method which does not seem to function as intended
public void updateStockPrices(double multiplier, Stock[] objects)
{
// I loop to the length of the array in the parameter
for(int i = 1; i < objects.length; i++)
{
// try to manipulate the stock
try{
double subtractThis = stocks[i].getPrice() * multiplier;
objects[i].setPrice(stocks[i].getPrice() - subtractThis);
}// and catch any null objects
catch(NullPointerException e){
// if null I then increment the counter
i++;}
// Is code missing in order for this to function as intended? or have I made a mistake?
}
}
public void createStocks(int stockAmount)
{
Stock[] stocks = new Stock[stockAmount];
}
public void writeStocks(String fileName, Stock[] objects)
{
try{
writer = new PrintWriter(fileName);
}
catch(FileNotFoundException e){
System.out.println("Couldn't create file " + fileName);
System.exit(0);
}
for(Stock s: objects)
{
writer.printf(FORMAT, getName(), getSymbol(), getPrice());
if(objects == null)
writer.close() ;
}
}
public Stock[] getStocks()
{
return stocks;
}
}

simple test
double multiplier = 1/3;
System.out.println(multiplier);
compared to
double multiplier = 1/3f;
System.out.println(multiplier);

Related

Nesting Marshalling while using JAXB & XML Annotation involving list of elements

Many of you have can help me with this question. I went through many question answers on stackoverflow, but in someway the code which I wrote doesnt seem to work the way I want it to work.
Any help will be appreciated.
I also came across this excellent article http://blog.bdoughan.com/2010/09/jaxb-collection-properties.html and it explained to me a lot of things.
I tried implementing it but not getting the required format of xml. Any help will be much appreciated.
Thank you.
Below I am posting the code :
There are 2 classes in my program:
DSC.java and Identity.java , The former class sets the values by calling the get/set methods in the Identity class.
::::::::::Identity.java::::::::::::
#XmlRootElement(name="LabbuddyArray")
public class Identity {
public String toString()
{
return "DSC_XML_OUTPUT [Company_name=" + company_name + ", Model_Number=" + model_number + ", Serial_Number=" + serial_number + ", New_BIAS=" + new_bias +", New_TEMP=" + new_temp + "]";
}
//DECLARE VARIABLES
String company_name;
String model_number;
String serial_number;
String port_number;
float photo_current;
float actual_bias;
float new_bias;
float actual_temp;
float new_temp;
List<String> slots;
public Identity(){}
//DECLARING CLASSES FOR XML FORMATTING
//GETTING AND SETTING SLOTS TO XML
#XmlElementWrapper
#XmlElement(name="slot")
public List<String> getSlots (){
return slots;
}
public void setSlots (List<String> slots){
this.slots = slots;
}
public String getIdentityCompanyName() {
return company_name;
}
#XmlElement(name="setIdentityCompanyName")
public void setIdentityCompanyName(String identity_company_name) {
this.company_name = identity_company_name;
}
//GETTING AND SETTING MODEL_NUMBER TO XML
public String getIdentityModelNumber() {
return model_number;
}
#XmlElement(name="setIdentityModelNumber")
public void setIdentityModelNumber(String model_number) {
this.model_number = model_number;
}
//GETTING AND SETTING SERIAL_NUMBER TO XML
public String getIdentitySerialNumber() {
return serial_number;
}
#XmlElement(name="setIdentitySerialNumber")
public void setIdentitySerialNumber(String serial_number) {
this.serial_number = serial_number;
}
//GETTING AND SETTING PORT_NUMBER TO XML
public String getIdentityPortNumber() {
return port_number;
}
#XmlElement (name="setIdentityPortNumber")
public void setIdentityPortNumber(String port_number) {
this.port_number = port_number;
}
//GETTING AND SETTING PHOTOCURRENT TO XML
public float getMonitorPhotoCurrent() {
return photo_current;
}
#XmlElement(name="setMonitorPhotoCurrent")
public void setMonitorPhotoCurrent(float photo_current) {
this.photo_current = photo_current;
}
//GETTING AND SETTING BIAS TO XML
//ACTUAL BIAS (READ)
public float getControlActualBias() {
return actual_bias;
}
#XmlElement (name="setControlActualBias")
public void setControlActualBias(float actual_bias) {
this.actual_bias = actual_bias;
}
//NEW BIAS (WRITE)
public float getControlNewBias(){
return new_bias;
}
#XmlElement (name="setControlNewBias")
public void setControlNewBias(float new_bias){
this.new_bias = new_bias;
}
//GETTING AND SETTING TEMP TO XML
//ACTUAL TEMP (READ)
public float getControlActualTemp() {
return actual_temp;
}
#XmlElement (name="setControlActualTemp")
public void setControlActualTemp(float actual_temp) {
this.actual_temp = actual_temp;
}
//NEW TEMP (WRITE)
public float getControlNewTemp(){
return new_temp;
}
#XmlElement(name ="setControlNewTemp")
public void setControlNewTemp(float new_temp){
this.new_temp = new_temp;
}
}
:::::::::::DSC.java::::::::::::
public class Dsc {
public static void main(String[] args) throws InterruptedException {
//INITIALIZING SCANNER TO TAKE INPUTS
Scanner input = new Scanner(System.in);
//CALLING ALL FUNCTIONS
Identity identity = new Identity();
List<String> strings = new ArrayList<String>(2);
strings.add("1");
identity.setSlots(strings);
//CREATING SERIAL PORT OBJECT
SerialPort serialPort = new SerialPort("COM4");
//GETTING SERIALPORTS
String[] portNames = SerialPortList.getPortNames();
for(int i = 0; i < portNames.length; i++)
{
System.out.println("Port Available on this machine: " +portNames[i]);
}
identity.setIdentityPortNumber("COM4");
//STARTING TRY BLOCK TO CATCH ERRORS THROUGHOUT THE EXECUTION
try
{
//OPENING PORT AND ASSIGNING PARAMETERS FOR COMMUNICATION
System.out.println("Port opened: " + serialPort.openPort());
System.out.println("Params setted: " + serialPort.setParams(57600, 8, 1, 0));
System.out.println("--------------------------------------------------------");
//IDENTIFYING THE COMPANY NAME ; MODEL NUMBER ; SERIAL NUMBER ; PORT NUMBER
System.out.println("Passing *IDN? to identify the Device: " +serialPort.writeString("*IDN? \n"));
Thread.sleep(500);
String str = serialPort.readString();
System.out.println("The Device ID is: " +str);
String[] deviceid = str.split(",");
System.out.println("Company :" + deviceid[0]);
identity.setIdentityCompanyName(deviceid[0]);
System.out.println("Model Number :" + deviceid[1]);
identity.setIdentityModelNumber(deviceid[1]);
System.out.println("Serial Number :" + deviceid[2]);
identity.setIdentitySerialNumber(deviceid[2]);
System.out.println("--------------------------------------------------------");
//IDENTIFYING THE PHOTOCURRENT
System.out.println("Passing MEAS:IDC? to identify the Photocurrent: " +serialPort.writeString("MEAS:IDC? \n"));
Thread.sleep(500);
String str1 = serialPort.readString();
System.out.println("The Photocurrent is :" +str1);
float photoCurrent = Float.parseFloat(str1);
identity.setMonitorPhotoCurrent(photoCurrent);
System.out.println("--------------------------------------------------------");
//IDENTIFYING THE ACTUAL BIAS
System.out.println("Passing MEAS:BIAS? to identify the Actual BIAS: " +serialPort.writeString("MEAS:BIAS? \n"));
Thread.sleep(500);
String str2 = serialPort.readString();
System.out.println("The Actual BIAS is :" +str2);
float control_actualBias = Float.parseFloat(str2);
identity.setControlActualBias(control_actualBias);
System.out.println("--------------------------------------------------------");
//SETTING THE BIAS
System.out.println("Set the Bias to ?");
float setBias = input.nextFloat();
System.out.println("Setting the user input BIAS to " +setBias +": " +serialPort.writeString("INP:BIAS " +setBias +"\n" ));
Thread.sleep(500);
identity.setControlNewBias(setBias);
System.out.println("--------------------------------------------------------");
//IDENTIFYING THE ACTUAL TEMPERATURE
System.out.println("Passing MEAS:TEMP? to identify the Temperature: " +serialPort.writeString("MEAS:TEMP? \n"));
Thread.sleep(500);
String str3 = serialPort.readString();
System.out.println("The Actual TEMP is: " +str3);
float actualTemp = Float.parseFloat(str3);
identity.setControlActualTemp(actualTemp);
System.out.println("--------------------------------------------------------");
//SETTING THE TEMPERATURE
System.out.println("Set the new TEMP to ?");
float setTemp = input.nextFloat();
System.out.println("Setting the user input TEMP to " +setTemp +": " +serialPort.writeString("INP:TEMP " +setTemp +"\n" ));
Thread.sleep(500);
identity.setControlNewTemp(setTemp);
System.out.println("--------------------------------------------------------");
}
catch (SerialPortException ex)
{
System.out.println(ex);
}
//STARTING THE JAXBCONTEXT & JAXBMARSHALLER CODE TO WRITE OUTPUT IN XML FILE
try
{
File file = new File("C:\\xampp\\htdocs\\StateMachine.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Identity.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(identity, file);
jaxbMarshaller.marshal(identity, System.out);
}
catch (JAXBException e)
{
e.printStackTrace();
}
}
}
:::::::: Current XML output ::::::::
<LabbuddyArray>
<setControlActualBias>5.999</setControlActualBias>
<setControlActualTemp>21.9</setControlActualTemp>
<setControlNewBias>5.0</setControlNewBias>
<setControlNewTemp>23.0</setControlNewTemp>
<setIdentityCompanyName>DSC</setIdentityCompanyName>
<setIdentityModelNumber>HLPD Lab Buddy</setIdentityModelNumber>
<setIdentityPortNumber>COM4</setIdentityPortNumber>
<setIdentitySerialNumber>50311602</setIdentitySerialNumber>
<setMonitorPhotoCurrent>0.0</setMonitorPhotoCurrent>
<slots>
<slot>1</slot>
</slots>
</LabbuddyArray>
::::::Required XML OUTPUT::::::
<LabbuddyArray>
<slot1>
<setControlActualBias></setControlActualBias>
<setControlActualTemp></setControlActualTemp>
<setControlNewBias></setControlNewBias>
<setControlNewTemp></setControlNewTemp>
<setIdentityCompanyName></setIdentityCompanyName>
<setIdentityModelNumber></setIdentityModelNumber>
<setIdentityPortNumber></setIdentityPortNumber>
<setIdentitySerialNumber></setIdentitySerialNumber>
<setMonitorPhotoCurrent></setMonitorPhotoCurrent>
</slot1>
<slot2>
<setControlActualBias></setControlActualBias>
<setControlActualTemp></setControlActualTemp>
<setControlNewBias></setControlNewBias>
<setControlNewTemp></setControlNewTemp>
<setIdentityCompanyName></setIdentityCompanyName>
<setIdentityModelNumber></setIdentityModelNumber>
<setIdentityPortNumber></setIdentityPortNumber>
<setIdentitySerialNumber></setIdentitySerialNumber>
<setMonitorPhotoCurrent></setMonitorPhotoCurrent>
</slot2>
</LabbuddyArray>
Then you should have something like this...
#XmlRootElement(name="LabbuddyArray")
public class Identity {
List<Slots> slots;
#XmlElement(name="slot")
public List<Slots> getSlots() {
return slots;
}
public void setSlots(List<Slots> slots) {
this.slots = slots;
}
}
Create a class 'Slots', copy all the elements and mapping to it.
And in the Dsc class populate the values as required.
Identity identity = new Identity();
List<Slots> slots = new ArrayList<Slots>();
Slots slot = new Slots();
slot.setControlActualBias(Float.valueOf("1.23"));
slots.add(slot);
slot = new Slots();
slot.setControlActualBias(Float.valueOf("1.24"));
slots.add(slot);
identity.setSlots(slots);
This will yield you the response similar to the one below.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<LabbuddyArray>
<slot>
<setControlActualBias>1.23</setControlActualBias>
<setControlActualTemp>0.0</setControlActualTemp>
<setControlNewBias>0.0</setControlNewBias>
<setControlNewTemp>0.0</setControlNewTemp>
<setMonitorPhotoCurrent>0.0</setMonitorPhotoCurrent>
</slot>
<slot>
<setControlActualBias>1.24</setControlActualBias>
<setControlActualTemp>0.0</setControlActualTemp>
<setControlNewBias>0.0</setControlNewBias>
<setControlNewTemp>0.0</setControlNewTemp>
<setMonitorPhotoCurrent>0.0</setMonitorPhotoCurrent>
</slot>
</LabbuddyArray>

Specified text file not found for File I/O in Eclipse

I am trying to do a file I/O in eclipse. Here is the code:
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
public class TextDB {
public static final String SEPARATOR = "|";
// an example of reading
public static ArrayList readProfessors(String filename) throws IOException {
// read String from text file
ArrayList stringArray = (ArrayList) read(filename);
ArrayList alr = new ArrayList();// to store Professors data
for (int i = 0; i < stringArray.size(); i++) {
String st = (String) stringArray.get(i);
// get individual 'fields' of the string separated by SEPARATOR
StringTokenizer star = new StringTokenizer(st, SEPARATOR); // pass in the string to the string tokenizer using delimiter ","
String name = star.nextToken().trim(); // first token
String email = star.nextToken().trim(); // second token
int contact = Integer.parseInt(star.nextToken().trim()); // third token
// create Professor object from file data
Professor prof = new Professor(name, email, contact);
// add to Professors list
alr.add(prof);
}
return alr;
}
// an example of saving
public static void saveProfessors(String filename, List al) throws IOException {
List alw = new ArrayList();// to store Professors data
for (int i = 0; i < al.size(); i++) {
Professor prof = (Professor) al.get(i);
StringBuilder st = new StringBuilder();
st.append(prof.getName().trim());
st.append(SEPARATOR);
st.append(prof.getEmail().trim());
st.append(SEPARATOR);
st.append(prof.getContact());
alw.add(st.toString());
}
write(filename, alw);
}
/**
* Write fixed content to the given file.
*/
public static void write(String fileName, List data) throws IOException {
PrintWriter out = new PrintWriter(new FileWriter(fileName));
try {
for (int i = 0; i < data.size(); i++) {
out.println((String) data.get(i));
}
} finally {
out.close();
}
}
/**
* Read the contents of the given file.
*/
public static List read(String fileName) throws IOException {
List data = new ArrayList();
Scanner scanner = new Scanner(new FileInputStream(fileName));
try {
while (scanner.hasNextLine()) {
data.add(scanner.nextLine());
}
} finally {
scanner.close();
}
return data;
}
public static void main(String[] aArgs) {
TextDB txtDB = new TextDB();
String filename = "professor.txt";
try {
// read file containing Professor records.
ArrayList al = TextDB.readProfessors(filename);
for (int i = 0; i < al.size(); i++) {
Professor prof = (Professor) al.get(i);
System.out.println("Name " + prof.getName());
System.out.println("Contact " + prof.getContact());
}
Professor p1 = new Professor("Joseph", "jos#ntu.edu.sg", 67909999);
// al is an array list containing Professor objs
al.add(p1);
// write Professor record/s to file.
TextDB.saveProfessors(filename, al);
} catch (IOException e) {
System.out.println("IOException > " + e.getMessage());
}
}
}
And my Professor class:
import java.io.Serializable;
public class Professor implements Serializable {
private String name;
private String email;
private int contact;
public Professor(String n, String e, int c) {
name = n;
email = e;
contact = c;
}
public String getName() {
return name;
}
public int getContact() {
return contact;
}
public String getEmail() {
return email;
}
public boolean equals(Object o) {
if (o instanceof Professor) {
Professor p = (Professor) o;
return (getName().equals(p.getName()));
}
return false;
}
}
However, when I run it, the compiler told the the specified file "professor.txt" is not found. I thought the compiler will create the text file automatically based on these code?
Thanks in advance.
Before attempting to read the file in your application, create it if it doesn't exist, either directly :
String filename = "professor.txt" ;
File file = new File(fileName);
if(!file.exists()){
file.createNewFile();
}
Or by calling your write method.
String filename = "professor.txt" ;
File file = new File(fileName);
if(!file.exists()){
TextDB.saveProfessors(filename, new ArrayList());
}
The PrintWriter will create the file for you, even though nothing is written to it (like with this empty list).
In your main you are firstly reading the file and then write it: if the file doesn't exist it will throw you the exception. Probably, the first time you ran it, the file was present (maybe you have write the code to write the file first and then you have launch it).
so, two solutions...
First: change the order of your main.
public static void main(String[] aArgs) {
TextDB txtDB = new TextDB();
String filename = "professor.txt";
try {
Professor p1 = new Professor("Joseph", "jos#ntu.edu.sg", 67909999);
// al is an array list containing Professor objs
al.add(p1);
// write Professor record/s to file.
TextDB.saveProfessors(filename, al);
// read file containing Professor records.
ArrayList al = TextDB.readProfessors(filename);
for (int i = 0; i < al.size(); i++) {
Professor prof = (Professor) al.get(i);
System.out.println("Name " + prof.getName());
System.out.println("Contact " + prof.getContact());
}
} catch (IOException e) {
System.out.println("IOException > " + e.getMessage());
}
}
Second: check if the file exist or not and then skip the read of it if it doesn't
public static void main(String[] aArgs) {
TextDB txtDB = new TextDB();
String filename = "professor.txt";
try {
//check if the file exist
File oFile = new File(filename);
if(oFile.exist()) {
// read file containing Professor records.
ArrayList al = TextDB.readProfessors(filename);
for (int i = 0; i < al.size(); i++) {
Professor prof = (Professor) al.get(i);
System.out.println("Name " + prof.getName());
System.out.println("Contact " + prof.getContact());
}
}
Professor p1 = new Professor("Joseph", "jos#ntu.edu.sg", 67909999);
// al is an array list containing Professor objs
al.add(p1);
// write Professor record/s to file.
TextDB.saveProfessors(filename, al);
} catch (IOException e) {
System.out.println("IOException > " + e.getMessage());
}
}
UPDATE after comment:
public static void main(String[] aArgs) {
TextDB txtDB = new TextDB();
String filename = "professor.txt";
try {
//check if the file exist
File oFile = new File(filename);
if(!oFile.exist()) {
oFile.mkdirs(); //optional
oFile.createNewFile();
}
// read file containing Professor records.
ArrayList al = TextDB.readProfessors(filename);
for (int i = 0; i < al.size(); i++) {
Professor prof = (Professor) al.get(i);
System.out.println("Name " + prof.getName());
System.out.println("Contact " + prof.getContact());
}
Professor p1 = new Professor("Joseph", "jos#ntu.edu.sg", 67909999);
// al is an array list containing Professor objs
al.add(p1);
// write Professor record/s to file.
TextDB.saveProfessors(filename, al);
} catch (IOException e) {
System.out.println("IOException > " + e.getMessage());
}
}

How to copy by reference and deserialize a list of objects in java?

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

Scanner from file doesn't seem to be reading file

I'm doing a Phone Directory project and we have to read from a directory file telnos.txt
I'm using a Scanner to load the data from the file telnos.txt, using a loadData method from a previous question I asked here on StackOverflow.
I noticed attempts to find a user always returned Not Found, so I added a few System.out.printlns in the methods to help me see what was going on. It looks like the scanner isn't reading anything from the file. Weirdly, it is printing the name of the file as what should be the first line read, which makes me think I've missed something very very simple here.
Console
run:
telnos.txt
null
loadData tested successfully
Please enter a name to look up: John
-1
Not found
BUILD SUCCESSFUL (total time: 6 seconds)
ArrayPhoneDirectory.java
import java.util.*;
import java.io.*;
public class ArrayPhoneDirectory implements PhoneDirectory {
private static final int INIT_CAPACITY = 100;
private int capacity = INIT_CAPACITY;
// holds telno of directory entries
private int size = 0;
// Array to contain directory entries
private DirectoryEntry[] theDirectory = new DirectoryEntry[capacity];
// Holds name of data file
private final String sourceName = "telnos.txt";
File telnos = new File(sourceName);
// Flag to indicate whether directory was modified since it was last loaded or saved
private boolean modified = false;
// add method stubs as specified in interface to compile
public void loadData(String sourceName) {
Scanner read = new Scanner("telnos.txt").useDelimiter("\\Z");
int i = 1;
String name = null;
String telno = null;
while (read.hasNextLine()) {
if (i % 2 != 0)
name = read.nextLine();
else
telno = read.nextLine();
add(name, telno);
i++;
}
}
public String lookUpEntry(String name) {
int i = find(name);
String a = null;
if (i >= 0) {
a = name + (" is at position " + i + " in the directory");
} else {
a = ("Not found");
}
return a;
}
public String addChangeEntry(String name, String telno) {
for (DirectoryEntry i : theDirectory) {
if (i.getName().equals(name)) {
i.setNumber(telno);
} else {
add(name, telno);
}
}
return null;
}
public String removeEntry(String name) {
for (DirectoryEntry i : theDirectory) {
if (i.getName().equals(name)) {
i.setName(null);
i.setNumber(null);
}
}
return null;
}
public void save() {
PrintWriter writer = null;
// writer = new PrintWriter(FileWriter(sourceName));
}
public String format() {
String a;
a = null;
for (DirectoryEntry i : theDirectory) {
String b;
b = i.getName() + "/n";
String c;
c = i.getNumber() + "/n";
a = a + b + c;
}
return a;
}
// add private methods
// Adds a new entry with the given name and telno to the array of
// directory entries
private void add(String name, String telno) {
System.out.println(name);
System.out.println(telno);
theDirectory[size] = new DirectoryEntry(name, telno);
size = size + 1;
}
// Searches the array of directory entries for a specific name
private int find(String name) {
int result = -1;
for (int count = 0; count < size; count++) {
if (theDirectory[count].getName().equals(name)) {
result = count;
}
System.out.println(result);
}
return result;
}
// Creates a new array of directory entries with twice the capacity
// of the previous one
private void reallocate() {
capacity = capacity * 2;
DirectoryEntry[] newDirectory = new DirectoryEntry[capacity];
System.arraycopy(theDirectory, 0, newDirectory,
0, theDirectory.length);
theDirectory = newDirectory;
}
}
ArrayPhoneDirectoryTester.java
import java.util.Scanner;
public class ArrayPhoneDirectoryTester {
public static void main(String[] args) {
//create a new ArrayPhoneDirectory
PhoneDirectory newTest = new ArrayPhoneDirectory();
newTest.loadData("telnos.txt");
System.out.println("loadData tested successfully");
System.out.print("Please enter a name to look up: ");
Scanner in = new Scanner(System.in);
String name = in.next();
String entryNo = newTest.lookUpEntry(name);
System.out.println(entryNo);
}
}
telnos.txt
John
123
Bill
23
Hello
23455
Frank
12345
Dkddd
31231
In your code:
Scanner read = new Scanner("telnos.txt");
Is not going to load file 'telnos.txt'. It is instead going to create a Scanner object that scans the String "telnos.txt".
To make the Scanner understand that it has to scan a file you have to either:
Scanner read = new Scanner(new File("telnos.txt"));
or create a File object and pass its path to the Scanner constructor.
In case you are getting "File not found" errors you need to check the current working directory. You could run the following lines and see if you are indeed in the right directory in which the file is:
String workingDir = System.getProperty("user.dir");
System.out.println("Current working directory : " + workingDir);
You need to also catch the FileNotFoundException in the function as follows:
public void loadData(String sourceName) {
try {
Scanner read = new Scanner(new File("telnos.txt")).useDelimiter("\\Z");
int i = 1;
String name = null;
String telno = null;
while (read.hasNextLine()) {
if (i % 2 != 0)
name = read.nextLine();
else {
telno = read.nextLine();
add(name, telno);
}
i++;
}
}catch(FileNotFoundException ex) {
System.out.println("File not found:"+ex.getMessage);
}
}
You are actually parsing the filename not the actual file contents.
Instead of:
new Scanner("telnos.txt")
you need
new Scanner( new File( "telnos.txt" ) )
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

How to sort a file by grade?

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.

Categories