I'm making a application where you can manage the inventory of a store. I want to have the ability to change the current stock of certain items. First you select the items you want to change from a JTable using checkboxes then you click a JButton which triggers an ActionEvent then a JOptionPane appears where you can input the new stock numbers.
The problem is that ,depending on what you select, it doesn't show the proper info asbout the article and sometimes it doesn't even show the JTextField I use for the input
Here is my Code:
if (eventSource == bestelBrandstof) {
ArrayList<Integer> brandstofTID = new ArrayList<Integer>();
ArrayList<String> brandstofType = new ArrayList<String>();
ArrayList<JTextField> aantallen = new ArrayList<JTextField>();
for (int i = 0; i < modelBrandstof.getRowCount(); i++) {
if ((boolean) modelBrandstof.getValueAt(i, 0)) {
brandstofType.add((String) modelBrandstof.getValueAt(i, 1));
brandstofTID.add(Integer.parseInt((String) modelBrandstof.getValueAt(i, 2)));
aantallen.add(new JTextField("", 5));
}
}
if (brandstofType.size() > 0) {
bestellenBrandstof = new JPanel();
bestellenBrandstof.setLayout(new FlowLayout());
bestellenBrandstof.add(new JLabel("Hoeveel liter wilt u van de volgende brandstof(fen) bestellen?"));
for (String a : brandstofType) {
bestellenBrandstof.add(new JLabel(a + " " + brandstofTID.get(brandstofType.indexOf(a))));
bestellenBrandstof.add(aantallen.get(brandstofType.indexOf(a)));
}
int n = JOptionPane.showConfirmDialog(null, bestellenBrandstof);
if (n == JOptionPane.YES_OPTION) {
boolean empty = false;
for (JTextField a : aantallen) {
if (a.getText().equals(""))
empty = true;
}
if (empty == false) {
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
String datumVandaag = dateFormat.format(new Date());
FileWriter fw = new FileWriter("./bestellingen/Bestellen_Brandstof_" + datumVandaag + ".txt");
PrintWriter pw = new PrintWriter(fw);
for (Integer a : brandstofTID) {
pw.print("Nr: " + a.toString() + ", Type: " + brandstofType.get(brandstofTID.indexOf(a)) + ", Tankstation Identificatie: " + aantallen.get(brandstofTID.indexOf(a)).getText());
pw.print(System.lineSeparator());
}
pw.close();
} catch (IOException exc) {
exc.printStackTrace();
}
JOptionPane.showMessageDialog(null, "De Bestellijst in aangemaakt");
} else {
JOptionPane.showMessageDialog(null, "Aantal Liters niet volledig ingevuld");
}
}
} else {
JOptionPane.showMessageDialog(null, "Selecteer onder het kopje 'Bestellen?' welke onderdelen u wilt bestellen");
}
}
Edit:
Here is some similar code I wrote where it works properly
if (eventSource == bestelOnderdelen) {
ArrayList<Integer> onderdeelNrs = new ArrayList<Integer>();
ArrayList<String> onderdeelOmschrijving = new ArrayList<String>();
ArrayList<JTextField> aantallen = new ArrayList<JTextField>();
for (int i = 0; i < modelOnderdelen.getRowCount(); i++) {
if ((boolean) modelOnderdelen.getValueAt(i, 0)) {
onderdeelNrs.add(Integer.parseInt((String) modelOnderdelen.getValueAt(i, 1)));
onderdeelOmschrijving.add((String) modelOnderdelen.getValueAt(i, 2));
aantallen.add(new JTextField("", 5));
}
}
if (onderdeelNrs.size() > 0) {
bestellenOnderdelen = new JPanel();
bestellenOnderdelen.setLayout(new FlowLayout());
bestellenOnderdelen.add(new JLabel("Hoeveel wilt u van de volgende artikelen bestellen?"));
for (Integer a : onderdeelNrs) {
bestellenOnderdelen.add(new JLabel(Integer.toString(a) + " " + onderdeelOmschrijving.get(onderdeelNrs.indexOf(a))));
bestellenOnderdelen.add(aantallen.get(onderdeelNrs.indexOf(a)));
}
int n = JOptionPane.showConfirmDialog(null, bestellenOnderdelen);
if (n == JOptionPane.YES_OPTION) {
boolean empty = false;
for (JTextField a : aantallen) {
if (a.getText().equals(""))
empty = true;
}
if (empty == false) {
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
String datumVandaag = dateFormat.format(new Date());
FileWriter fw = new FileWriter("./bestellingen/Bestellen_Onderdelen_" + datumVandaag + ".txt");
PrintWriter pw = new PrintWriter(fw);
for (Integer a : onderdeelNrs) {
pw.print("Nr: " + a.toString() + ", Omschrijving: " + onderdeelOmschrijving.get(onderdeelNrs.indexOf(a)) + ", Aantal: " + aantallen.get(onderdeelNrs.indexOf(a)).getText());
pw.print(System.lineSeparator());
}
pw.close();
} catch (IOException exc) {
exc.printStackTrace();
}
JOptionPane.showMessageDialog(null, "De Bestellijst in aangemaakt");
} else {
JOptionPane.showMessageDialog(null, "Aantallen niet volledig ingevuld");
}
}
} else {
JOptionPane.showMessageDialog(null, "Selecteer onder het kopje 'Bestellen?' welke onderdelen u wilt bestellen");
}
}
Edit:
I added ArrayList<Integer> uniqueID = new ArrayList<Integer>(); and edited this part
for (Integer a : uniqueID) {
bestellenBrandstof.add(new JLabel(brandstofType.get(uniqueID.indexOf(a)) + " " + brandstofTID.get(uniqueID.indexOf(a))));
bestellenBrandstof.add(aantallen.get(uniqueID.indexOf(a)));
}
I got it the issue is with below line
bestellenBrandstof.add(aantallen.get(brandstofType.indexOf(a)));
If aantallen.get(brandstofType.indexOf(a)) returns same JTextField then it is not added in JPanel again hence some JTextField are not shown.
Please check the value of brandstofType and onderdeelNrs array.
Related
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.
This is a code snippet that shows me trying to write to a file.
public void printContents() {
int i = 0;
try {
FileReader fl = new FileReader("Product List.txt");
Scanner scn = new Scanner(fl);
while (scn.hasNext()) {
String productName = scn.next();
double productPrice = scn.nextDouble();
int productAmount = scn.nextInt();
System.out.println(productName + " is " + productPrice + " pula. There are " + productAmount + " items left in stalk.");
productList[i] = new ReadingAndWritting(productName, productPrice, productAmount);
i = i + 1;
}
scn.close();
} catch (IOException exc) {
exc.printStackTrace();
} catch (Exception exc) {
exc.printStackTrace();
}
}
public void writeContents() {
try {
//FileOutputStream formater = new FileOutputStream("Product List.txt",true);
Formatter writer = new Formatter(new FileOutputStream("Product List.txt", false));
for (int i = 0; i < 2; ++i) {
writer.format(productList[i].name + "", (productList[i].price + 200.0 + ""), (productList[i].number - 1), "\n");
}
writer.close();
} catch (Exception exc) {
exc.printStackTrace();
}
}
The exception thrown while trying to run this code is:
java.util.NoSuchElementException at ReadingAndWritting.printContents(ReadingAndWritting.java:37).
I tried multiple things and only ended up with: "cokefruitgushersAlnassma" in the file. What I want is:
coke 7.95 10
fruitgushers 98.00 6
Alnassma 9.80 7
The Problem seems to be in
String productName = scn.next();
// Here:
double productPrice = scn.nextDouble();
// And here:
int productAmount = scn.nextInt();
After scn.next(), you don't check if scn.hasNext() before requesting the next element (double or int, respectively). So, either your file is not complete, or not in the exact structure you expect, or you just missed the two additional checks before trying to work with data which just isn't there.
Solution could be like:
while (scn.hasNext()) {
String productName = scn.next();
if ( scn.hasNext() ) {
double productPrice = scn.nextDouble();
if ( scn.hasNext() ) {
int productAmount = scn.nextInt();
// Do something with the three values read...
} else {
// Premature end of file(?)
}
} else {
// Premature end of file(?)
}
}
I have a java applicato that use the thermal print to printer a text. I use this printer to print the order for the bar.
This is an example of the ticket:
--> BAR
Coca Cola 1 x 1.5
Fanta 1 x 1.5
-------------------
TOTALE 3.00 euro
And the code to print this ticket works.
But I wanto to change the font size because the font is to small. How can I change the font ??
This is the code that I use to create and printer a ticket:
PrinterBean localPrinterBean = null;
StringBuffer localStringBuffer = null;
HashMap localHashMap=null;
if(emettiScontrinoCartaceo){
//PER LA STAMPA SCOTRNIO
localPrinterBean = getPrinterBean();
localStringBuffer = new StringBuffer();
localHashMap = null;
if ((localPrinterBean.isPrn_Enabled()) && (!localPrinterBean.isPrn_Onlyticket()))
{
//log.info("" + localPrinterBean.getPrn_driver());
localHashMap = PrinterManager.loadEscDriver(localPrinterBean);
//localStringBuffer.append("\n");
localStringBuffer.append(String.format("\t%s->> %s%s\n", new Object[] { localHashMap.get("size2w"), "BAR", localHashMap.get("size2w-off") }));
localStringBuffer.append("\n");
}
//FINE STAMPA SCOTNRINO
}
while (it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
ArticoliScontrini artSco = (ArticoliScontrini) (entry.getValue());
//devo inserire nella lista le righe di stampa dello scontrino
//INIZIO STAMPA SCONTRINO
localStringBuffer.append(String.format("%s\n", new Object[] { artSco.getDescrizioneArticolo() }));
String quantita = artSco.getQuantita() + " x " +artSco.getPrezzoTotStringFormattato();//toString(artSco.getQuantita(), true);
localStringBuffer.append(String.format("\t %s", new Object[] { quantita }));
localStringBuffer.append("\n");
//FINE STAMPA SCONTRINO
}
localStringBuffer.append("------------------------------------------");
localStringBuffer.append("\n");
String totale = "TOTALE " + decimalFormatter2.format(totaleScontrinoCartaceo) + " euro";
localStringBuffer.append(String.format("%s\n", new Object[] { totale }));
String str = localStringBuffer.toString();
try{
cbPrintBuffer(localPrinterBean);
}
catch(Exception e){
VisualMessageScontrini.getErroreStampaScontrino();
}
public void cbPrintBuffer(PrinterBean paramPrinterBean)
throws Exception
{
/*Object localObject1 = JabirCfg.hexItIfn(paramPrinterBean.getPrn_Hexinit());
if ((localObject1 != null) && (!((String)localObject1).equals(""))) {
printRawBytes(paramPrinterBean, ((String)localObject1).getBytes());
}*/
Object localObject1 = null;
if (paramPrinterBean.hasPrn_Bitopt(2))
{
localObject1 = new FileOutputStream(paramPrinterBean.getPrn_driver());
((FileOutputStream)localObject1).write(cbGetFlow());
((FileOutputStream)localObject1).close();
return;
}
localObject1 = PrinterManager.getPrintService_cached(paramPrinterBean);
if (paramPrinterBean.isPrnGd())
{
boolean bool = paramPrinterBean.hasPrn_Bitopt(32);
PrinterJob localObject2 = PrinterJob.getPrinterJob();
((PrinterJob)localObject2).setPrintService((PrintService)localObject1);
((PrinterJob)localObject2).setJobName("easy ticket");
PageFormat localPageFormat = ((PrinterJob)localObject2).defaultPage();
PrinterExtra.deserialize_pagejson_to_PageFormat(paramPrinterBean.getPrn_pagejson(), localPageFormat);
Printable localPrintable = null;
for (int i = 0;; i++)
{
if (bool) {
localPrintable = cbPrintable(i);
} else {
localPrintable = cbPrintable(-1);
}
if (localPrintable == null) {
break;
}
((PrinterJob)localObject2).setPrintable(localPrintable, ((PrinterJob)localObject2).validatePage(localPageFormat));
((PrinterJob)localObject2).print();
if (!bool) {
break;
}
String str = JabirCfg.hexItIfn("0x1b 0x6d");
printRawBytes(paramPrinterBean, str.getBytes());
}
return;
}
DocPrintJob localDocPrintJob = ((PrintService)localObject1).createPrintJob();
Object localObject2 = new SimpleDoc(cbGetFlow(), DocFlavor.BYTE_ARRAY.AUTOSENSE, null);
localDocPrintJob.print((Doc)localObject2, new HashPrintRequestAttributeSet());
}
Hey im trying to write to a file but im getting an error on the line where it writes the line that goes into each line of a text file, cant figure it out any help would be greatly appreciated
The Writer Code
.
public static void stuIDWrite() throws IOException
{
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("Res/stuIDSorted.txt")));
} catch (IOException ex) {
// report
} finally {
try {writer.close();} catch (Exception ex) {}
}
int i = 0;
while (i <= stuArrayIdSort.length + 1)
{
ln = stuArrayIdSort[i].getStuLastName();
fn = stuArrayIdSort[i].getStuFirstName();
pn = stuArrayIdSort[i].getStuFirstName();
id = stuArrayIdSort[i].getStuId();
ft = stuArrayIdSort[i].getFTime();
phn =stuArrayIdSort[i].getPhoneNum();
lj = stuArrayIdSort[i].getLovJava();
con = stuArrayIdSort[i].getCont();
writer.write(ln + "," + fn + "," + pn + ","+ id + "," + ft + "," + phn + "," + lj + "," + con + "\n");
writer.close();
i++;
}
The Full Code
import java.io.*;
import java.util.*;
public class StudentMain {
/**
* #param args
*/
//array and sorting variables
public static studentConstructor[] stuArrayOrig = new studentConstructor[23];
private static studentConstructor[] stuArrayIdSort = new studentConstructor[23];
private static studentConstructor[] stuArrayNameSort = new studentConstructor[23];
private static int lineCount = 0;
private static int nElms = 0;
//writer
//studentConstructor variables
public static String fn; //First Name
public static String ln; //Last Name
public static String pn; //Preferred Name
public static int id; //Student Id Number
public static boolean ft;//Full-time Boolean
public static int phn; //Student Phone Number
public static boolean lj;//Loving java Boolean
public static String con;//Continuing
File idSort = new File("stuListSortID.txt");
public static void StuRead()
{
Scanner inFile = null;
try
{
inFile = new Scanner
(new FileReader("Res/students.txt"));
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
System.out.println("File Not Found");
e.printStackTrace();
}
while (inFile.hasNextLine()){
inFile.useDelimiter(",|\\n"); //breaks the lines into single info
ln = inFile.next();
System.out.println(ln);
fn = inFile.next();
System.out.println(fn);
pn = inFile.next();
System.out.println(pn);
id = inFile.nextInt();
System.out.println(id);
ft = inFile.nextBoolean();
System.out.println(ft);
phn = inFile.nextInt();
System.out.println(phn);
lj = inFile.nextBoolean();
System.out.println(lj);
con = inFile.next();
System.out.println(con);
studentConstructor st = new studentConstructor(ln, fn, pn, id, ft, phn, lj, con);
stuArrayOrig[lineCount] = st;
inFile.nextLine();
System.out.println(stuArrayOrig[lineCount]);
lineCount++;
}
//setting info into other arrays
stuArrayIdSort = stuArrayOrig;
stuArrayNameSort = stuArrayOrig;
System.out.println("orig array length" + stuArrayOrig.length);
System.out.println("id array length" + stuArrayIdSort.length);
System.out.println("name array length" + stuArrayNameSort.length);
System.out.println("number of file lines" + lineCount);
inFile.close();
}
public static void stuIdSort()
{
studentConstructor temp;
boolean sorted = false;
while (sorted == false)
{ sorted=true;
for (int i=0; i<stuArrayIdSort.length-1 ; i++)
{
if(stuArrayIdSort[i].getStuId() > stuArrayIdSort[i+1].getStuId())
{
temp = stuArrayIdSort[i+1];
stuArrayIdSort[i+1] = stuArrayIdSort[i];
stuArrayIdSort[i] = temp;
sorted=false;
}
}
}
for(int i=0; i<stuArrayIdSort.length; i++)
{
int getSC = stuArrayIdSort[i].studentId;
System.out.println("number of swaps " + i+1 +" " +getSC);
}
}
//stuArrayIdSort[i].getStuLastName(),stuArrayIdSort[i].getStuFirstName(),stuArrayIdSort[i].getPrefName(),stuArrayIdSort[i].getStuId(),stuArrayIdSort[i].getFTime(),stuArrayIdSort[i].getPhoneNum(),stuArrayIdSort[i].getLovJava(),stuArrayIdSort[i].getCont()
public static void stuIDWrite() throws IOException
{
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("Res/stuIDSorted.txt")));
} catch (IOException ex) {
// report
} finally {
try {writer.close();} catch (Exception ex) {}
}
int i = 0;
while (i <= stuArrayIdSort.length + 1)
{
ln = stuArrayIdSort[i].getStuLastName();
fn = stuArrayIdSort[i].getStuFirstName();
pn = stuArrayIdSort[i].getStuFirstName();
id = stuArrayIdSort[i].getStuId();
ft = stuArrayIdSort[i].getFTime();
phn =stuArrayIdSort[i].getPhoneNum();
lj = stuArrayIdSort[i].getLovJava();
con = stuArrayIdSort[i].getCont();
writer.write(ln + "," + fn + "," + pn + ","+ id + "," + ft + "," + phn + "," + lj + "," + con + "\n");
writer.close();
i++;
}
}
public static void stuNameSort()
{
}
public static void stuNameWrire()
{
}
}
//lastName, firstName, perName, studentId, fulltime,
Ok, here is what you should do:
What's happening is that you are closing it before it can actually do anything. So, lets move your finally clause to the end of everything:
public static void stuIDWrite() throws IOException
{
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("Res/stuIDSorted.txt")));
int i = 0;
while (i <= stuArrayIdSort.length + 1)
{
ln = stuArrayIdSort[i].getStuLastName();
fn = stuArrayIdSort[i].getStuFirstName();
pn = stuArrayIdSort[i].getStuFirstName();
id = stuArrayIdSort[i].getStuId();
ft = stuArrayIdSort[i].getFTime();
phn =stuArrayIdSort[i].getPhoneNum();
lj = stuArrayIdSort[i].getLovJava();
con = stuArrayIdSort[i].getCont();
writer.write(ln + "," + fn + "," + pn + ","+ id + "," + ft + "," + phn + "," + lj + "," + con + "\n");
i++;
}
} catch (IOException ex) {
// report
} finally {
try {writer.close();} catch (Exception ex) {}
}
I'm not sure you understand how try...catch...finally works. Here's what you have:
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("Res/stuIDSorted.txt")));
} catch (IOException ex) {
// report
} finally {
>>>>>>> **try {writer.close();} catch (Exception ex) {}**
}
int i = 0;
while (i <= stuArrayIdSort.length + 1)
{
//bunch of stuff
writer.write(...);
>>>>>>> **writer.close();**
i++;
}
}
You close writer ONCE before you've even used it (finally block gets executed after the try block), and ONCE inside the loop. So, if somehow the code could make it past the writer.close() in the finally block, it would never make it through the loop more than once.
It is not necessary to close a BufferedWriter. The class makes sure to close it internally.
If you are using Java 7, you might want to consider using the "try-with-resources" syntax, which can simplify a correct implementation of file handling greatly in cases like this. Your original code had some issues, but even the accepted answer has some problems that I believe will result in a NullPointerException in the case where the file can't be opened (unverified).
I think you may also have some problems with your while loop boundary conditions also. I've changed the while loop to the more traditional for loop. Keep in mind that java array elements run from 0 to array.length - 1 inclusive.
public static void stuIDWrite() throws IOException
{
try (FileWriter writer = new FileWriter("Res/stuIDSorted.txt"))
{
for (int i = 0; i < stuArrayIdSort.length; ++i)
{
ln = stuArrayIdSort[i].getStuLastName();
fn = stuArrayIdSort[i].getStuFirstName();
pn = stuArrayIdSort[i].getStuFirstName();
id = stuArrayIdSort[i].getStuId();
ft = stuArrayIdSort[i].getFTime();
phn = stuArrayIdSort[i].getPhoneNum();
lj = stuArrayIdSort[i].getLovJava();
con = stuArrayIdSort[i].getCont();
writer.write(ln + "," + fn + "," + pn + "," + id + "," + ft + "," + phn + "," + lj + "," + con + "\n");
}
}
}
You could also look at using the "enhanced for loop" syntax for the inner loop that may further streamline things.
I implemented this code below in order to read contacts from the addressbook of the phone
The problem is, In a case when all the numbers in the phonebook are saved in the SIM it reads and displays the contacts for selection.
But in a case whereby any number is included on the phone memory, it gives an application error.(OutOfMemoryException)
What do I do (PS do not mind some System.out.println statements there. I used them for debugging)
public void execute() {
try {
// go through all the lists
String[] allContactLists = PIM.getInstance().listPIMLists(PIM.CONTACT_LIST);
if (allContactLists.length != 0) {
for (int i = 0; i < allContactLists.length; i++) {
System.out.println(allContactLists[i] + " " + allContactLists[1]);
System.out.println(allContactLists.length);
loadNames(allContactLists[i]);
System.out.println("Execute() error");
}
} else {
available = false;
}
} catch (PIMException e) {
available = false;
} catch (SecurityException e) {
available = false;
}
}
private void loadNames(String name) throws PIMException, SecurityException {
ContactList contactList = null;
try {
// ----
// System.out.println("loadErr1");
contactList = (ContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY, name);
// System.out.println(contactList.getName());//--Phone Contacts or Sim Contacts
// First check that the fields we are interested in are supported(MODULARIZE)
if (contactList.isSupportedField(Contact.FORMATTED_NAME)
&& contactList.isSupportedField(Contact.TEL)) {
// ContactLst.append("Reading contacts...", null);
// System.out.println("sup1");
Enumeration items = contactList.items();
// System.out.println("sup2");
Vector telNumbers = new Vector();
telNames = new Vector();
while (items.hasMoreElements()) {
Contact contact = (Contact) items.nextElement();
int telCount = contact.countValues(Contact.TEL);
int nameCount = contact.countValues(Contact.FORMATTED_NAME);
// System.out.println(telCount);
// System.out.println(nameCount);
// we're only interested in contacts with a phone number
// nameCount should always be > 0 since FORMATTED_NAME is
// mandatory
if (telCount > 0 && nameCount > 0) {
String contactName = contact.getString(Contact.FORMATTED_NAME, 0);
// go through all the phone numbers
for (int i = 0; i < telCount; i++) {
System.out.println("Read Telno");
int telAttributes = contact.getAttributes(Contact.TEL, i);
String telNumber = contact.getString(Contact.TEL, i);
System.out.println(telNumber + " " + "tel");
// check if ATTR_MOBILE is supported
if (contactList.isSupportedAttribute(Contact.TEL, Contact.ATTR_MOBILE)) {
if ((telAttributes & Contact.ATTR_MOBILE) != 0) {
telNames.insertElementAt(telNames, i);
telNumbers.insertElementAt(telNumber, i);
} else {
telNumbers.addElement(telNumber);
telNames.addElement(telNames);
}
}
// else {
//// telNames.addElement(contactName);
// telNumbers.addElement(telNumber);
// }
System.out.println("telephone nos");
}
// Shorten names which are too long
shortenName(contactName, 20);
for (int i = 0; i <= telNumbers.size(); i++) {
System.out.println(contactName + " here " + telNames.size());
telNames.addElement(contactName);
System.out.println(telNames.elementAt(i) + " na " + i);
}
names = new String[telNames.size()];
for (int j = 0; j < names.length; j++) {
names[j] = (String) telNames.elementAt(j);
System.out.println(names[j] + "....");
}
// allTelNames.addElement(telNames);
System.out.println("cap :" + telNames.size() + " " + names.length);
// telNames.removeAllElements();
// telNumbers.removeAllElements();
}
}
available = true;
} else {
// ContactLst.append("Contact list required items not supported", null);
available = false;
}
} finally {
// always close it
if (contactList != null) {
contactList.close();
}
}
}