Object reference - java

I have a problem to get to right object. When I start my program it creates a object. And when I call opon a methode, the methode creates a new object, but when I am trying to print the object information, I am getting information from the first object. How do I refere to the new object ?
public Meny () {
tekstgr = new Tekstgrensesnitt();
fil = new Fil();
this.cde = new CDarkiv();
}
public CDArkivADT lesFraFil(CDArkivADT cde, String filnavn) throws java.io.IOException {
try {
// // 1 - FileReader
FileReader ansFil = new FileReader(filnavn);
// 2 - BufferedReader
BufferedReader innfil = new BufferedReader(ansFil);
// 3 - Leser den første posten som er antall info-poster
String linje = innfil.readLine();
int n = Integer.parseInt(linje);
// Oppretter CDarkiv
cde = new CDarkiv(n);
// 4 - Les postene, en hel post om gangen
for (int i = 0; i < n; i++) {
String post = innfil.readLine();
String[] felt = post.split(SKILLE);
int nr = Integer.parseInt(felt[0]);
String artist = felt[1];
String tittel = felt[2];
int år = Integer.parseInt(felt[3]);
Sjanger sjanger = Sjanger.valueOf(felt[4]); //Eventuelt lagret som heltall
//...Må så konvertere til enum
String plselskap = felt[5];
CD cd = new CD(nr, artist, tittel, år, sjanger, plselskap);
cde.leggTilCd(cd);
}
System.out.println(Arrays.toString(cde.getArkiv()));
// 4 - Lukk filen
innfil.close();
}
catch (FileNotFoundException unntak) {//arver fra IOException må stå først
// hvis ikke vil unntaket for IOException skygge
System.out.println("Finner ikke filen " + filnavn);
System.exit(-1);
}
catch (IOException e) {
System.out.println("Feil ved lesing av fil: " + e);
System.exit(1);
}
return cde;
}
public void start() {
Scanner tast = new Scanner(System.in);
String filnav = "test.txt";
System.out.println("Press '1' for å 'Lese fra fil'" + "\n" + "Press '2' for å 'Skrive til fil'");
int g = tast.nextInt();
if(g == 1) {
try {
fil.lesFraFil(cde, filnav);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Tast '1' for å søke etter tittel." + "\n" + "Tast '2' for å søke etter artist/gruppe");
int f = tast.nextInt();
if(f == 1) {
String twmp = tast.nextLine();
String temp = tast.nextLine();
CD d = cde.finnCD(temp);
tekstgr.visCD(d);
} else {
String temp = tast.nextLine();
cde.finnArtist(temp);
}
}
public static void main(String[] args) {
Meny meny = new Meny();
meny.start();
}

Where is your first declaration of cde?
When you pass it through your method, the reference you get in your parameters is a copy of the original reference, thus assigning a value to it does not change the original variable.
I see you are returning cde in your method, and this works, but you are not using the returned object in your main method. I'd suggest remove the cde parameter as it is pointless, and change your lesFraFil call like this:
CDArkivADT cde = file.lesFraFil(filnav);

public class CDarkiv implements CDArkivADT {
private CD[] cdTabell;
private int antall;
public CDarkiv (int antall) {
this.antall = antall;
cdTabell = new CD[antall];
}
public CDarkiv() {
antall = 0;
cdTabell = new CD[0];
}
{...}
public interface CDArkivADT {
public void utvidKapasitet(); //Utvider kapasiteten til et CD arkiv
public CD[] getArkiv(); //Henter arkiv
public void leggTilCd (CD c); //Legger til en CD i arkiv
public void slettCd (CD c); //Sletter en CD i arkiv
public CD finnCD (String s); //Finner CD-er ved gitt delstreng
public String finnArtist (String s); //Finner alle CD-er som tilhører en artist ved gitt delstring
public int hentAntall(Sjanger sjanger); //Henter antall CD-er i en sjanger
public int getAntall (); //Henter antall CD-er
}

Related

Problem with reading textfiles with scanner in Java and ArrayLists

I'm having a problem where I read a textfile named "songs.txt" with Scanner in a function called loadFiles() which every line is:
Music ID # Song Name # Release Date
And with this I create a Song object, and then store said object in a ArrayList. After reading the file, I clone this ArrayList so I can return a ArrayList with the songs read and clear the first ArrayList to prevent the cases where for exemple:
(PS: I use the ArrayLists as global variables)
songs.txt has this structure:
1oYYd2gnWZYrt89EBXdFiO#Message In A Bottle#1979
7zxc7dmd82nd92nskDInds#Sweet Child of Mine#1980
And the loadFiles() is called 2 times, the ArrayList would have a size of 4 instead of 2 as it should be. So that's why after songs.txt is read I copy the arrayList and then clear the first ArrayList that way the ArrayList that's returned only has the size of 2.
This is my code:
package pt.ulusofona.aed.deisiRockstar2021;
import java.io.IOException;
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
public class Main {
public static ArrayList < Song > teste6 = new ArrayList < > ();
public static ArrayList < Song > getSongsArray = new ArrayList < > ();
public static ArrayList < Artista > testeSongArtists = new ArrayList < > ();
public static ParseInfo parseInfoSongsTxT = new ParseInfo(0, 0);
public static ParseInfo parseInfoSongsArtistsTxT = new ParseInfo(0, 0);
public static ParseInfo parseInfoSongsDetailsTxT = new ParseInfo(0, 0);
public static void main(String[] args) throws IOException {
ArrayList < Song > teste7 = new ArrayList < Song > ();
loadFiles();
loadFiles();
teste7 = getSongs();
ParseInfo teste8 = getParseInfo("songs.txt");
System.out.println("\n----------------------TESTE DO MAIN----------------------");
System.out.println(teste7.toString());
System.out.println(teste8.toString());
System.out.println(getSongsArray.size());
}
public static void loadFiles() throws IOException {
//Aqui lê-se o ficheiro songs.txt
System.out.println("----------------------LEITURA DO FICHEIRO songs.txt------------");
String nomeFicheiro = "songs.txt";
try {
File ficheiro = new File(nomeFicheiro);
FileInputStream fis = new FileInputStream(ficheiro);
Scanner leitorFicheiro = new Scanner(fis);
while (leitorFicheiro.hasNextLine()) {
String linha = leitorFicheiro.nextLine();
String dados[] = linha.split("#");
if (dados.length != 3) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[0].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[1].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[2].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
//Meter para ignorar a acabar com espaço
parseInfoSongsTxT.NUM_LINHAS_OK += 1;
String idTemaMusical = dados[0];
String nome = dados[1];
int anoLancamento = Integer.parseInt(dados[2]);
Song song = new Song(idTemaMusical, nome, null, anoLancamento, 0, false, 0, 0, 0, 0);
teste6.add(song);
}
leitorFicheiro.close();
getSongsArray = (ArrayList < Song > ) teste6.clone();
teste6.clear();
} catch (FileNotFoundException exception) {
String mensagem = "Erro: o ficheiro " + nomeFicheiro + " nao foi encontrado.";
System.out.println(mensagem);
}
System.out.println(teste6.toString());
System.out.println("Ok: " + parseInfoSongsTxT.NUM_LINHAS_OK + ", Ignored: " + parseInfoSongsTxT.NUM_LINHAS_IGNORED + "\n");
System.out.println("----------------------LEITURA DO FICHEIRO song_artists.txt------------");
//Aqui é lido o ficheiro song_artists.txt, mas falta ver se é preciso separar vários artistas com o mesmo ID para posições diferentes no ArrayList
String nomeFicheiro2 = "song_artists.txt";
try {
File song_artists = new File(nomeFicheiro2);
FileInputStream fis2 = new FileInputStream(song_artists);
Scanner leitorFicheiro2 = new Scanner(fis2);
while (leitorFicheiro2.hasNextLine()) {
String linha = leitorFicheiro2.nextLine();
String dados[] = linha.split("#");
if (dados.length != 2) {
parseInfoSongsArtistsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[0].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[1].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
parseInfoSongsArtistsTxT.NUM_LINHAS_OK += 1;
String idTemaMusical = dados[0];
String artista = dados[1];
Artista artista2 = new Artista(idTemaMusical, artista);
testeSongArtists.add(artista2);
}
leitorFicheiro2.close();
} catch (FileNotFoundException exception) {
String mensagem = "Erro: o ficheiro " + nomeFicheiro2 + " não foi encontrado.";
System.out.println(mensagem);
}
System.out.println(testeSongArtists.toString());
System.out.println("Ok: " + parseInfoSongsArtistsTxT.NUM_LINHAS_OK + ", Ignored: " + parseInfoSongsArtistsTxT.NUM_LINHAS_IGNORED + "\n");
System.out.println("----------------------LEITURA DO FICHEIRO song_details.txt------------");
//Aqui lê-se o ficheiro song_details.txt
boolean letra = false;
ArrayList < Song > testeSongDetails = new ArrayList < Song > ();
String nomeFicheiro3 = "song_details.txt";
try {
File song_details = new File(nomeFicheiro3);
FileInputStream fis3 = new FileInputStream(song_details);
Scanner leitorFicheiro3 = new Scanner(fis3);
while (leitorFicheiro3.hasNextLine()) {
String linha = leitorFicheiro3.nextLine();
String dados[] = linha.split("#");
if (dados.length != 7) {
parseInfoSongsDetailsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[0].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[1].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[3].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[4].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[5].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[6].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
parseInfoSongsDetailsTxT.NUM_LINHAS_OK += 1;
String idTemaMusical = dados[0];
//System.out.println(idTemaMusical);
int duracao = Integer.parseInt(dados[1]);
//System.out.println(duracao);
int letraExplicita = Integer.parseInt(dados[2]);
//System.out.println(letraExplicita);
if (letraExplicita == 0) {
letra = false;
} else {
letra = true;
}
//System.out.println(letra);
int populariedade = Integer.parseInt(dados[3]);
//System.out.println(populariedade);
double dancabilidade = Double.parseDouble(dados[4]);
//System.out.println(dancabilidade);
double vivacidade = Double.parseDouble(dados[5]);
//System.out.println(vivacidade);
double volumeMedio = Double.parseDouble(dados[6]);
//System.out.println(volumeMedio);
Song song = new Song(idTemaMusical, null, null, 0, duracao, letra, populariedade, dancabilidade, vivacidade, volumeMedio);
testeSongDetails.add(song);
}
leitorFicheiro3.close();
} catch (FileNotFoundException exception) {
String mensagem = "Erro: o ficheiro " + nomeFicheiro3 + " não foi encontrado.";
System.out.println(mensagem);
}
System.out.println("Ok: " + parseInfoSongsDetailsTxT.NUM_LINHAS_OK + ", Ignored: " + parseInfoSongsDetailsTxT.NUM_LINHAS_IGNORED);
}
public static ArrayList < Song > getSongs() {
return getSongsArray;
}
public static ParseInfo getParseInfo(String fileName) {
if (fileName == "songs.txt") {
return parseInfoSongsTxT;
}
if (fileName == "song_artists.txt") {
return parseInfoSongsArtistsTxT;
}
if (fileName == "song_details.txt") {
return parseInfoSongsDetailsTxT;
}
return null;
}
}
The problem is that when I made a test to check the function where the ArrayList is returned to see the size of the ArrayList it always comes as 0.
I think it's because only the function the returns the ArrayList is tested so loadFiles() isn't executed so the ArrayListo never gets cloned and that makes the ArrayList that is returned stay the same.
I thought about calling loadFiles() inside getSongs() and that way I would guarantee that the ArrayList is cloned but that would make getSongs use "throws IOException" and since I have to respect the school's project guide and getSongs doesn't include "throws IOException" i can't put it there.
But the more I think about it, that doesn't even make sense because how can they test it with a file of their own and loadFiles() isn't executed?
I'm out of ideas how to solve this problem, any help is welcome thank you.

TreeMap with (String,ArrayList<String,Int>)

I am trying to read an input file. Each value of the input file is inserted into the TreeMap as
If word is not existing: Insert the word to the treemap and associate the word with an ArrayList(docId, Count).
If the Word is present in the TreeMap, then check if the current DocID matches within the ArrayList and then increase the count.
THe
For the ArrayList, I created another class as below:
public class CountPerDocument
{
private final String documentId;
private final int count;
CountPerDocument(String documentId, int count)
{
this.documentId = documentId;
this.count = count;
}
public String getDocumentId()
{
return this.documentId;
}
public int getCount()
{
return this.count;
}
}
After that, I am trying to print the TreeMap into a text file as <DocID - Count>
Not sure what I am doing wrong here, but the output I get is as follows:
The Stem is todai:[CountPerDocument#5caf905d, CountPerDocument#27716f4, CountPerDocument#8efb846, CountPerDocument#2a84aee7, CountPerDocument#a09ee92, CountPerDocument#30f39991]
Wondering if anyone can guide me what i am doing wrong and if my method isn't correct what am i supposed to do?
public class StemTreeMap
{
private static final String r1 = "\\$DOC";
private static final String r2 = "\\$TITLE";
private static final String r3 = "\\$TEXT";
private static Pattern p1,p2,p3;
private static Matcher m1,m2,m3;
public static void main(String[] args)
{
BufferedReader rd,rd1;
String docid = null;
String id;
int tf = 0;
//CountPerDocument cp = new CountPerDocument(docid, count);
List<CountPerDocument> ls = new ArrayList<>();
Map<String,List<CountPerDocument>> mp = new TreeMap<>();
try
{
rd = new BufferedReader(new FileReader(args[0]));
rd1= new BufferedReader(new FileReader(args[0]));
int docCount = 0;
String line = rd.readLine();
p1 = Pattern.compile(r1);
p2 = Pattern.compile(r2);
p3 = Pattern.compile(r3);
while(line != null)
{
m1 = p1.matcher(line);
m2 = p2.matcher(line);
m3 = p3.matcher(line);
if(m1.find())
{
docid = line.substring(5, line.length());
docCount++;
//System.out.println("The Document ID is :");
//System.out.println(docid);
line = rd.readLine();
}
if(m2.find()||m3.find())
{
line = rd.readLine();
}
else
{
if(!(mp.containsKey(line))) // if the stem is not on the TreeMap
{
//System.out.println("The stem is not present in the tree");
tf = 1;
ls.add(new CountPerDocument(docid,tf));
mp.put(line, ls);
line = rd.readLine();
}
else
{
if(ls.indexOf(docid) > 0) //if its last entry matches the current document number
{
//System.out.println("The Stem is present for the same docid so incrementing docid");
tf = tf+1;
ls.add(new CountPerDocument(docid,tf));
line = rd.readLine();
}
else
{
//System.out.println("Stem is present but not the same docid so inserting new docid");
tf = 1;
ls.add(new CountPerDocument(docid,tf)); //set did to the current document number and tf to 1
line = rd.readLine();
}
}
}
}
rd.close();
System.out.println("The Number of Documents in the file is:"+ docCount);
//Write to an output file
String l = rd1.readLine();
File f = new File("dictionary.txt");
if (f.createNewFile())
{
System.out.println("File created: " + f.getName());
}
else
{
System.out.println("File already exists.");
Path path = Paths.get("dictionary.txt");
Files.deleteIfExists(path);
System.out.println("Deleted Existing File:: Creating New File");
f.createNewFile();
}
FileWriter fw = new FileWriter("dictionary.txt");
fw.write("The Total Number of Stems: " + mp.size() +"\n");
fw.close();
System.out.println("The Stem is todai:" + mp.get("todai"));
}catch(IOException e)
{
e.printStackTrace();
}
}
}
You didn't define the function String toString() in your class CountPerDocument. So, when you try to print a CountPerDocument variable, the default printed value is CountPerDocument#hashcode.
To decide how to represent a CountPerDocument variable in your code, add in your class the next function:
#Override
public String toString() {
return "<" + this.getDocumentId() + ", " + this.getCount() + ">";
}
Try to override toString method in CountPerDocument. Something like this:
public class CountPerDocument
{
private final String documentId;
private final int count;
CountPerDocument(String documentId, int count)
{
this.documentId = documentId;
this.count = count;
}
public String getDocumentId()
{
return this.documentId;
}
public int getCount()
{
return this.count;
}
#Override
public String toString() {
return documentId + "-" + count;
}
}

How to overwrite integer at specific part of text file?

I have a textfile called "BookDetails.txt"
It is formatted in Book Title, Author, Publisher, Branch Call Number, and # of Copies like so:
1984 : George Orwell : Penguin : FIC Orw : 23
In my program, I am trying to overwrite the number of copies from 23 to 22 (decrementing by one essentially) when a patron checks out the specific book
public class CheckOutDialog extends javax.swing.JDialog {
private static final DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
ArrayList<CheckOut> checkOuts = new ArrayList<CheckOut>();
String bookTitle;
int numberOfCopies;
/**
* Creates new form CheckOutDialog
*/
public CheckOutDialog(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
Date currentDate = new Date();
jTextFieldDate.setText(df.format(currentDate));
}
private void jButtonCheckOutActionPerformed(java.awt.event.ActionEvent evt) {
String firstName = jTextFieldFirstName.getText();
String lastName = jTextFieldLastName.getText();
bookTitle = jTextFieldBookTitle.getText();
String checkOutDate = jTextFieldDate.getText();
CheckOut checkOutInfo = new CheckOut(firstName, lastName, bookTitle, checkOutDate);
checkOuts.add(checkOutInfo);
CheckOutCopy();
}
public void CheckOutCopy() //This method checks for book and num of copies
{
try {
File f = new File("BookDetails.txt");
Scanner fileRead = new Scanner(f);
boolean foundTitle = false;
fileRead.nextLine();
while(fileRead.hasNextLine())
{
String textLine = fileRead.nextLine();
String[] bookInfo = textLine.split(" : ");
String tempBookTitle = bookInfo[0];
numberOfCopies = Integer.parseInt(bookInfo[4]);
if(tempBookTitle.trim().equals(bookTitle))
{
foundTitle = true;
break;
}
}
if(foundTitle && numberOfCopies > 0)
{
OverwriteCopies();
WriteCheckOut();
this.setVisible(false);
}
else if(numberOfCopies == 0)
{
if(JOptionPane.showConfirmDialog(null, "Would you like to add the patron to the queue?", "No copies available", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
{
AddPatronQueue();
}
else
{
JOptionPane.getRootFrame().dispose();
}
}
else
{
JOptionPanes.messageBox("Book was not found in Library Catalog", "Check Out Error");
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}
private void OverwriteCopies()
{
numberOfCopies--;
//Unsure how to proceed from here
}
private void WriteCheckOut()
{
WriteFile wf = new WriteFile("CheckOutDetails.txt");
for(int i = 0; i < checkOuts.size(); i++)
{
CheckOut c = checkOuts.get(i);
String checkOutDetails = c.getFirstName() + " : " + c.getLastName() + " : " + c.getBookTitle() + " : " + c.getCheckOutDate();
wf.write(checkOutDetails);
}
wf.close();
}
My program is successful in finding a specific book and its number of copies (and it produces the JOptionPane if it has 0 copies left). However, I am unsure of how I can overwrite and update that specific element within the text file. I have done some research and it seems that RandomAccessFile may be one possible option. Is the RAF the viable solution to my problem or is there another option that I can take?

Needing to update my outfile after items are changed

For my program I have it set up that I can edit and change values of items that are stored within my outfile in the program itself. However the numbers that they change to only update in the program itself. For example if I sell 10 ketchups than in my program i would have 0 but my outfile would still say I have 10. I need my outfile to update with my program. I came up with an override method but all it does currently is adds content on a new line within the outfile, I am not sure how I would go about actually updating any information stored on the outfile any help would be great.
Code:
public class Driver {
public static ArrayList<Item> list = new ArrayList<Item>();
static double myBalance = 100;
/*static ArrayList<Item> list = new ArrayList<Item>();*/
/**
* #param args
* #throws IOException
* #throws FileNotFoundException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
ArrayList<String> inventoryList = new ArrayList<String>();
BufferedReader readIn = null;
try {
readIn = new BufferedReader(new FileReader("inventory.out"));
readIn.lines().forEach(inventoryList::add);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(readIn != null) {
readIn.close();
}
}
for (int i = 0; i < 4; i++) {
String item = inventoryList.get(i);// input String like the one you would read from a file
String delims = "[,]"; //delimiter - a comma is used to separate your tokens (name, qty,cost, price)
String[] tokens = item.split(delims); // split it into tokens and place in a 2D array.
String name = tokens[0]; System.out.println(name);
double cost = Double.parseDouble(tokens[1]);System.out.println(cost);
int qty = Integer.parseInt(tokens[2]);System.out.println(qty);
double price = Double.parseDouble(tokens[3]);System.out.println(price);
list.add(new Item(name, cost, qty, price));
}
sell("Mayo", 10);
buy("Ketchup", 20);
remove_item("Ketchup");
add_item("Tums", 20, 10, 5);
overwrite("New line");
PrintAll();
}
// Method to sell items from the arraylist
public static void sell(String itemName, int amount) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getName().equals(itemName)) {
int number = i;
list.get(number).qty -= amount;
myBalance += list.get(number).getPrice() * amount;
}
}
}
// Method to buy more of the items in our array list
public static void buy(String itemName, int amount) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getName().equals(itemName)) {
int number = i;
list.get(number).qty += amount;
myBalance -= list.get(number).getPrice() * amount;
}
}
}
// Method to remove an item completely from our inventory
public static void remove_item(String itemName) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getName().equals(itemName)) {
int number = i;
list.remove(number);
}
}
}
public static void add_item(String itemName, double itemCost, int qty, double itemPrice) {
list.add(new Item(itemName, itemCost, qty, itemPrice));
}
public static void PrintAll() {
String output = "";
for(Item i : list) {
int everything = i.getQty();
String everything2 = i.getName().toString();
output += everything +" "+ everything2 + "\n";
}
JOptionPane.showMessageDialog(null, "Your current balance is: $" + myBalance + "\n" + "Current stock:" + "\n" + output);
}
public static void overwrite(String update) {
try
{
String filename= "inventory.out";
FileWriter fw = new FileWriter(filename,true); //the true will append the new data
fw.write("\n"+"add a line");//appends the string to the file
fw.close();
}
catch(IOException ioe)
{
System.err.println("IOException: " + ioe.getMessage());
}
}
}
Outfile contents:
Ketchup,1,10,2
Mayo,2,20,3
Bleach,3,30,4
Lysol,4,40,5
If you know the name of your outfile then clear the outfile as and when you need it updated and then write to it again. You can use the below code to erase content of a file.
PrintWriter writer = new PrintWriter(file);
writer.print("");
writer.close();

Java getShopItem() and getShopUser methods

Hi Guys I am trying to write a method, getShopItem(), for the Shop class, that will return a pointer to a ShopItem object stored in itemsList when given the item's itemCode value, below is my attempt at coding which has been unsucessful and will not compile:
public shop item.getshopitem(shopItem)
{
return this.shopitem
}
Shop Class:
public class Shop
{
private ArrayList<Shop> shopCollection;
private ArrayList<ShopUser> usersList;
private ArrayList<Tool> toolsList;
private int toolCount;
private String toolName;
private int power;
private int timesBorrowed;
private boolean rechargeable;
private int itemCode;
private int cost;
private double weight;
private boolean onLoan;
private JFrame myFrame;
private FileDialog fileDialogBox;
private int mode;
public void ReadToolData (String data) throws FileNotFoundException,NoSuchElementException
{
// public void FileDialogBox() throws FileNotFoundException
{
if ( userSelectMode() ) // LOAD or SAVE if successful
{
String path = "E:/LEWIS BC 2/java project/project 1 part 3/items_all.txt"; // start browsing in root on drive E:
// String path = "E:/LEWIS BC 2/java project/project 1 part 3/userData.txt"; // start browsing in root on drive E:
setUpFileDialog(path);
fileDialogBox.setVisible(true);
}
else
{
String message = "No option selected, aborting";
String title = "Error";
JOptionPane.showMessageDialog(myFrame, message, title,
JOptionPane.WARNING_MESSAGE);
return; // or System.exit(1)
}
// see what the user has selected
String fileName = fileDialogBox.getFile();
if ( fileName==null )
{
String message = "Selection cancelled by user, aborting";
String title = "Error";
JOptionPane.showMessageDialog(myFrame, message, title,
JOptionPane.WARNING_MESSAGE);
return; // or System.exit(2)
}
String directoryPath = fileDialogBox.getDirectory();
String message = "File selected: " + fileName + "\nFolder: " + directoryPath;
JOptionPane.showMessageDialog(myFrame, message, "File Selected",
JOptionPane.INFORMATION_MESSAGE);
// now create a File object
File fileObject = new File(directoryPath, fileName);
// note that this does NOT create an actual file -- it simply
// creates a reference, or a "handle", for a file
// normally would now do something useful with the File object !!
// -- let's check if the file exists and, if so, when it was last modified
if ( fileObject.exists() )
{
Date whenModified = new Date(fileObject.lastModified());
DateFormat df = DateFormat.getDateTimeInstance();
message = "Time file was last modified: " + df.format(whenModified);
}
else
message = "File " + fileObject.getAbsolutePath() + " does not exist";
JOptionPane.showMessageDialog(myFrame, message, "Do Something Useful",
JOptionPane.INFORMATION_MESSAGE);
}
try
{ // The name of the file which we will read from
String filename = "items_all.txt";
// Prepare to read from the file, using a Scanner object
File file = new File(filename);
Scanner in = new Scanner(file);
ArrayList<Tool> shops = new ArrayList<Tool>();
// Read each line until end of file is reached
while (in.hasNextLine())
{
// Read an entire line, which contains all the details for 1 account
String line = in.nextLine();
// Make a Scanner object to break up this line into parts
Scanner lineBreaker = new Scanner(line);
// 1st part is the toolCount
try
{
// need to put checks for empty line & comments
int toolCount = lineBreaker.nextInt();
// 2nd part is the toolName
String toolName = lineBreaker.next();
// 3rd part is the amount of money or the Cost...
int cost = lineBreaker.nextInt();
int total = lineBreaker.nextInt();
}
catch (InputMismatchException e)
{
System.out.println("File not found1.");
}
catch (NoSuchElementException e)
{
System.out.println("File not found2");
}
}
}
catch (FileNotFoundException e)
{
System.out.println("File not found");
} // Make an ArrayList to store all the
// Return the ArrayList
// return shops;
}
public static void main(String[] args)
{
String test = "245.34,2456 345.2,34.12,23456 23,4";
Scanner input = new Scanner(test);
input.useDelimiter(",");
while (input.hasNextDouble())
{
System.out.println(input.nextDouble());
}
System.out.println("I get to the end");
}
/**
* Default Constructor for Testing
*/
public void extractTokens(Scanner scanner ) throws IOException, FileNotFoundException
{
//extracts tokens from the text file
File text = new File("E:/LEWIS BC 2/java project/project 1 part 3/items_all.txt");
String toolName = scanner.next();
String itemCode = scanner.next();
String power = scanner.next();
String timesBorrowed = scanner.next();
String onLoan = scanner.next();
String cost = scanner.next();
String weight = scanner.next();
extractTokens(scanner);
// System.out.println(parts.get(1)); // "en"
}
/**
* Creates a collection of tools to be stored in a tool list
*/
public Shop(String toolName, int power,int timesborrowed,boolean rechargeable,int itemCode,int cost,double weight,int toolcount,boolean onLoan)
{
toolsList = new ArrayList<Tool>();
toolName = new String();
power = 0;
timesborrowed = 0;
rechargeable = true;
itemCode = 001;
cost = 100;
weight = 0.0;
toolCount = 0;
onLoan = true;
}
/**
* Default Constructor for Testing
*/
public Shop()
{
// initialise instance variables
toolName = "Spanner";
itemCode = 001;
timesBorrowed = 0;
power = 0;
onLoan = true;
rechargeable = true;
itemCode = 001;
cost = 100;
weight = 0.0;
toolCount = 0;
}
//
// /**
// * Creates a collection of tools to be stored in a tool list
// */
// public Shop() {
// this.toolsList = new ArrayList<Tool>();
// this.toolName = toolName;
// this.power = power;
// this.timesborrowed = timesborrowed;
//
//
// }
//
// /**
// * Default Constructor for Testing
// */
// public Shop(){
// // Call the previous defined constructor
//
// }
/**
* Reads ElectronicToolData data from a text file
*
* #param <code>fileName</code> a <code>String</code>, the name of the
* text file in which the data is stored.
*
* #throws FileNotFoundException
*/
//
// while (there are more lines in the data file )
// {
// lineOfText = next line from scanner
// if( line starts with // )
// { // ignore }
// else if( line is blank )
// { // ignore }
// else
// { code to deal with a line of ElectricTool data }
// }
private boolean userSelectMode()
{
String[] options = {"LOAD", "SAVE"};
String instr = "Select LOAD for read access, SAVE for write access";
String title = "Select Mode";
int button = JOptionPane.showOptionDialog(myFrame, instr, title,
JOptionPane.DEFAULT_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, options, null);
boolean success;
if ( button==0 )
{
mode = FileDialog.LOAD;
success = true;
}
else if ( button==1 )
{
mode = FileDialog.SAVE;
success = true;
}
else
success = false;
return success;
}
private void setUpFileDialog(String path)
{
String fileDialogTitle = null;
if ( mode == FileDialog.LOAD )
fileDialogTitle = "Open";
else if ( mode == FileDialog.SAVE)
fileDialogTitle ="Save As";
else
{
// defensive programming -- this should never happen !
System.out.println("*** Unexpected Error -- Aborting ***");
System.exit(1);
}
fileDialogBox = new FileDialog(myFrame, fileDialogTitle, mode);
fileDialogBox.setDirectory(path); // start browsing in folder
// corresponding to path
}
/**
* Creates a tool collection and populates it using data from a text file
*/
public Shop(String fileName) throws FileNotFoundException
{
this();
ReadToolData(fileName);
}
/**
* Adds a tool to the collection
*
* #param <code>tool</code> an <code>Tool</code> object, the tool to be added
*/
public void storeTool(Tool tool)
{
toolsList.add(tool);
}
/**
* Shows a tool by printing it's details. This includes
* it's position in the collection.
*
* #param <code>listPosition</code> the position of the animal
*/
public void showTool(int listPosition)
{
Tool tool;
if( listPosition < toolsList.size() )
{
tool = toolsList.get(listPosition);
System.out.println("Position " + listPosition + ": " + tool);
}
}
/**
* Returns how many tools are stored in the collection
*
* #return the number of tools in the collection
*/
public int numberOfToolls()
{
return toolsList.size();
}
/**
* Displays all the tools in the collection
*
*/
public void showAllTools()
{
System.out.println("Shop");
System.out.println("===");
int listPosition = 0;
while( listPosition<toolsList.size() ) //for each loop
{
showTool(listPosition);
listPosition++;
}
System.out.println(listPosition + " tools shown" ); // display number of tools shown
}
public void printShopiteDetails()
{
// The name of the file to open.
String fileName = "items_all.txt";
// This will reference one line at a time
String line = null;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader =
new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
// Always close files.
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
/**
* Adds a shop item to the shop.
*
* #param <code>shop</code> an <code>Shop</code> object, the Shop item can be added to the shop.
*/
public void storeShopitem(Shop shop)
{
shopCollection.add(shop);
}
/**
* Adds a shop user to the shop.
*
* #param <code>shop</code> an <code>Shop</code> object, the new Shop user can be added to the shop.
*/
public void storeShopUser(ShopUser shopUser)
{
usersList.add(shopUser);
}
/**
* Accessor method processhireRequest
*
* #return shopuser and shopitem object's
*/
public void processHireRequest(ShopItem shopItem, ShopUser shopUser)
{
this.itemCode = itemCode;
}
/**
* Accessor method processhireRequest
*
* #return shopuser and shopitem object's
*/
public void processReturnRequest(ShopItem shopItem, ShopUser shopUser)
{
this.itemCode = itemCode;
}
}
ShopItem class:
public abstract class ShopItem
{
private ArrayList<Tool> toolsList;
Shop shop;
private int toolCount;
private String toolName;
private int power;
private int timesBorrowed;
private boolean rechargeable;
private int itemCode;
private int cost;
private double weight;
private boolean onLoan;
private static JFrame myFrame;
private String Tool;
private String ElectricTool;
private String HandTool;
private String Perishable;
private String Workwear;
private String ShopUserID;
public void ReadToolData (String data) throws FileNotFoundException,NoSuchElementException
{
// shows the directory of the text file
File file = new File("E:/LEWIS BC 2/java project/project 1 part 3/ElectricToolData.txt");
Scanner S = new Scanner (file);
// prints out the data
System.out.println();
// prints out the
System.out.println();
S.nextLine();
S.nextLine();
S.nextLine();
S.nextLine();
S.nextInt ();
}
/**
* Creates a collection of tools to be stored in a tool list
*/
public ShopItem(String toolName, int power,int timesborrowed,boolean rechargeable,int itemCode,int cost,double weight,int toolcount,boolean onLoan,boolean ShopUserID)
{
toolsList = new ArrayList<Tool>();
rechargeable = true;
power = 0;
timesborrowed = 0;
// ShopUserID = new String();
toolName = new String();
itemCode = 001;
cost = 100;
weight = 0.0;
toolCount = 0;
onLoan = true;
// ShopUserID = null;
}
/**
* Default Constructor for Testing
*/
public ShopItem()
{
// initialise instance variables
rechargeable = true;
power = 0;
timesBorrowed = 0;
ShopUserID = "SU002171";
toolName = "Spanner";
itemCode = 001;
cost = 100;
weight = 0.0;
toolCount = 0;
onLoan = true;
}
/**
* Reads ElectronicToolData data from a text file
*
* #param <code>fileName</code> a <code>String</code>, the name of the
* text file in which the data is stored.
*
* #throws FileNotFoundException
*/
public void readData(String fileName) throws FileNotFoundException
{
//
// while (there are more lines in the data file )
// {
// lineOfText = next line from scanner
// if( line starts with // )
// { // ignore }
// else if( line is blank )
// { // ignore }
// else
// { code to deal with a line of ElectricTool data }
// }
myFrame = new JFrame("Testing FileDialog Box");
myFrame.setBounds(200, 200, 800, 500);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
{
FileDialog fileBox = new FileDialog(myFrame,
"Open", FileDialog.LOAD);
fileBox.setVisible(true);
}
{
File dataFile = new File(fileName);
Scanner scanner = new Scanner(dataFile);
while( scanner.hasNext() )
{
String info = scanner.nextLine();
System.out.println(info);
}
scanner.close();
}
}
/**
* Default Constructor for Testing
*/
public void extractTokens(Scanner scanner) throws IOException, FileNotFoundException
{
// extracts tokens from the scanner
File text = new File("E:/LEWIS BC 2/java project/java project part 3/step_5_data.txt");
String ToolName = scanner.next();
int itemCode = scanner.nextInt();
int cost = scanner.nextInt();
int weight = scanner.nextInt();
int timesBorrowed = scanner.nextInt();
boolean rechargeable = scanner.nextBoolean();
boolean onLoan = scanner.nextBoolean();
String ShopUserID = scanner.next();
extractTokens(scanner);
// System.out.println(parts.get(1)); // "en"
}
/**
* Creates a tool collection and populates it using data from a text file
*/
public ShopItem(String fileName) throws FileNotFoundException
{
this();
ReadToolData(fileName);
}
/**
* Adds a tool to the collection
*
* #param <code>tool</code> an <code>Tool</code> object, the tool to be added
*/
public void storeTool(Tool tool)
{
toolsList.add(tool);
}
/**
* Shows a tool by printing it's details. This includes
* it's position in the collection.
*
* #param <code>listPosition</code> the position of the animal
*/
public void showTool(int listPosition)
{
Tool tool;
if( listPosition < toolsList.size() )
{
tool = toolsList.get(listPosition);
System.out.println("Position " + listPosition + ": " + tool);
}
}
/**
* Returns how many tools are stored in the collection
*
* #return the number of tools in the collection
*/
public int numberOfToolls()
{
return toolsList.size();
}
/**
* Displays all the tools in the collection
*
*/
public void showAllTools()
{
System.out.println("Shop");
System.out.println("===");
int listPosition = 0;
while( listPosition<toolsList.size() ) //for each loop
{
showTool(listPosition);
listPosition++;
}
System.out.println(listPosition + " tools shown" ); // display number of tools shown
}
public void printAllDetails()
{
// The name of the file to open.
String fileName = "ElectricToolDataNew.txt";
// This will reference one line at a time
String line = null;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader =
new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
// Always close files.
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
is this above code correct and should it work??
any answers or help would be greatly appreciated.
public shop item.getshopitem(shopItem)
This isn't valid Java. You dont need to prepend the function.
public ShopItem getshopitem(int shopItem)
I think the method you are trying to write is
public ShopItem getShopItem(int shopItem)
{
return this.shopItem;
}
Although, in the actual method implementation, you will want to search your list of ShopItems for the given item code.
If you are going to be storing item codes that correspond to ShopItems, I suggest using a HashMap with item codes as the keys and ShopItems as the values.

Categories

Resources