I am working on an inventory program and keep running into an issue. I have some text files that are named using a combination of numbers. I call them shelves. I open them up and edit them to store items in them. I am having a problem after I remove some objects from one of these.
How that process goes is I will open the file. Load it into a JTable. Select the item and amount I wish to remove. Then re save the file. That all works great until I go to open another shelf. Any other shelf I try to open after that process tells me that the shelf does not exist even if it the same one I just used. I can still go through the path on my computer and find it just fine and I can close the program and reopen it and it works just fine again until I remove and item from the shelf. I will post any relevant code below. Thanks for the help guys.
String[] binCombos = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10"};
JComboBox<String> aisle, column, row;
JButton open = new JButton("Open Shelf");
tableHolder = new JScrollPane(shelfsContents);
aisle = new JComboBox<String>(binCombos);
column = new JComboBox<String>(binCombos);
row = new JComboBox<String>(binCombos);
open.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
shelfCombo = aisle.getSelectedItem().toString() + column.getSelectedItem().toString() + row.getSelectedItem().toString() + ".txt";
File shelfName = new File(sPath + "\\" + shelfCombo);
if(shelfName.exists() == true && Console.console.IsPulling() == false)
{
OpenShelf(shelfName);
}
else
{
System.out.println(shelfName + " does not exist");
}
}
});
private void SaveShelf()
{
try
{
BufferedWriter bfw = new BufferedWriter(new FileWriter("shelfCombo"));
for(int i = 0; i < tableModel.getRowCount(); i++)
{
for(int j = 0; j < tableModel.getColumnCount(); j++)
{
if(j == 1 || j == 3)
{
if(Integer.parseInt(tableModel.getValueAt(i,3).toString()) > 0)
{
bfw.write(tableModel.getValueAt(i, j).toString());
bfw.write(" : ");
}
}
}
bfw.newLine();
}
bfw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
try this code
private void SaveShelf(){
PrintWriter pw ;
try
{
pw = new PrintWriter(new File("shelfCombo"));
for(int i = 0; i < tableModel.getRowCount(); i++)
{
for(int j = 0; j < tableModel.getColumnCount(); j++)
{
if(j == 1 || j == 3)
{
if(Integer.parseInt(tableModel.getValueAt(i,3).toString()) > 0)
{
pw.print(tableModel.getValueAt(i, j).toString());
pw.print(" : ");
}
}
}
pw.println();
pw.flush();
}
pw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
finally{
pw.close();
}
}
Related
Hi I am new on programing and I am having a problem I am trying to copy some things from a file to a array
and I just want to copy in the position 1,2,3 and 4 from the file. Example copy to the array 11 , G , 0 , 20.
FILE TEXT:
0;11;G;0;200;1
2;10;F;0;300;2
0;12;J;0;100;3
String[][] aa = new String[100][6];
try {
Scanner x = new Scanner(new File("Turmas.txt"));
x.useDelimiter("[;\n]");
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 6; j++) {
if (x.hasNext()) {
aa[i][j] = x.next();
}
}
}
x.close();
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(
null, "An error occurred, try restarting the program!",
"ERROR!", JOptionPane.ERROR_MESSAGE
);
}
String[][] aaa = new String[100][4];
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 4; j++) {
if (aa[i][j] == null) {
System.out.println("null " + i + " " + j);
}
else {
if (aa[i][0].equals(String.valueOf(SAVEID))) {
aaa[i][j] = aa[i][1];
aaa[i][j + 1] = aa[i][2];
aaa[i][j + 2] = aa[i][3];
aaa[i][j + 3] = aa[i][4];
}
}
}
}
System.out.println(aaa[0][0]);
System.out.println(aaa[0][1]);
System.out.println(aaa[0][2]);
System.out.println(aaa[0][3]);
If only 4 values are needed from the input array are needed, why not just read these specific values?
String[] result = new String[4];
try (Scanner input = new Scanner(new File("Turmas.txt")) // input closed automatically
.useDelimiter(";|\\R") // use character class \R to match line-feed characters
) {
if (input.hasNext()) {
input.next(); // skip the 1st token
for (int i = 0; i < result.length && input.hasNext(); i++) {
result[i] = input.next();
}
}
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(
null, "An error occurred, try restarting the program!",
"ERROR!", JOptionPane.ERROR_MESSAGE
);
}
If it is needed to read the columns with indexes [1..4] from the file containing 6 columns per line, it is cleaner to read the source file line by line, split each line by ;, skip 1 column with index 0, and keep the 4 columns.
String[][] result = new String[100][4];
try (Scanner input = new Scanner(new File("Turmas.txt"))) {
for (int i = 0; i < result.length && input.hasNextLine(); i++) {
String[] parts = input.nextLine().split(";");
for (int j = 1; j < Math.min(result[i].length, parts.length); j++) {
result[i][j - 1] = parts[j];
}
}
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(
null, "An error occurred, try restarting the program!",
"ERROR!", JOptionPane.ERROR_MESSAGE
);
}
This loop:
for(int j=0;j<4;j++)
runs again with a value of j = 1 after it completes the first iteration, so when it gets to the expression aaa[i][j+3] the second index evaluates to 4, which of course is illegal. I'm not sure why you used a for loop there, since you manually increment the index values as you assign the aaa values?
I have a jTextField, jLabel and a jButton. I want to set the jTextField to empty and update the jLabel to some new text after I perform jButton action.
This my code for jButtonActionPerformed(ActionEvent e) method:
private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {
BufferedWriter fw;
StringBuilder guessword = new StringBuilder(word);
try {
fw = new BufferedWriter(new FileWriter("C:\\Users\\Arihant\\JavaApplication1\\src\\javaapplication1\\scores.txt", true));
while(guesses != 0) {
jLabel26.setText(Integer.toString(guesses));
guesschar = jTextField2.getText().charAt(0);
flag = 0;
for(int j = 0; j < word.length() / 2; j++) {
if(Character.toLowerCase(guesschar) == temp[j] && (guessword.toString().indexOf(Character.toLowerCase(guesschar)) < 0)) {
flag = 1;
for(int k = 0; k < word.length(); k++) {
if(Character.toLowerCase(guesschar) == word.charAt(k))
guessword.setCharAt(k, Character.toLowerCase(guesschar));
}
if(guessword.toString().equals(word)) {
switch (difficulty) {
case "EASY":
points = guesses * 50;
break;
case "MODERATE":
points = guesses * 100;
break;
case "HARD":
points = guesses * 200;
break;
default:
points = 0;
break;
}
try {
fw.append(name + " " + points);
fw.newLine();
fw.close();
} catch (IOException ex) {
Logger.getLogger(HangMan.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex);
}
jPanel13.removeAll();
jPanel13.add(jPanel4);
jPanel13.repaint();
jPanel13.revalidate();
jLabel29.setText("<html>YOU WIN!<br/> The word was: </html>" + word);
jLabel31.setText("You scored: " + points + " points.");
jLabel28.setText("Play again?");
}
}
}
if(flag == 0) {
guesses--;
}
jPanel13.repaint();
jPanel13.revalidate();
jLabel1.setText(guessword.toString());
jTextField2.setText("");
Document document = jTextField2.getDocument();
document.addDocumentListener(new JButtonStateController(jButton8, 0));
((AbstractDocument) jTextField2.getDocument()).setDocumentFilter(new JTextFieldFilter(0));
}
} catch (IOException ex) {
Logger.getLogger(HangMan.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex);
}
}
When I click jButton8, it just skips the entire code in try-catch block and goes directly to jPanel13.removeAll();.
I want to set the jTextField2 to empty and jButton8 to disabled, each time I click jButton8.
Tell me, where I am wrong and how can I improve my code?
I am working on a driving licence project on j2Me wich is including Tests like quizz , well and i am having a problem after parsing the questions and moving them into choiceGroups just like that :
if (questions.length > 0) {
for (int i = 0; i < questions.length; i++) {
ChoiceGroup reponses = new ChoiceGroup("Reponses" + i, Choice.EXCLUSIVE);
reponses.append(questions[i].getReponse1(), null);
reponses.append(questions[i].getReponse2(), null);
reponses.append(questions[i].getReponse3(), null);
pass.append(questions[i].getContenu());
pass.append(reponses);
}
}
} catch (Exception e) {
System.out.println("Exception:" + e.toString());
}
disp.setCurrent(pass);
and the next step is the command who's controlling the choiceGroups to test them if they are like the true answer or not .
so i am blocked here .
if (c == valider) {
int result = 0;
for (int i = 0; i < pass.size(); i++) {
String ch = pass.get(i).getLabel();
System.out.println(ch);
}
}
I don't know how to get the choice from the choicegroup
any help
Actually, I am not sure what totally you want for:
This code will help you get selected items from choicegroup that i did long time before:
//get a selected array in choicegroup
private String[] choiceGroupSelected(ChoiceGroup cg) {
String selectedArray[] = new String[cg.size()];
int k = 0;
for (int i = 0; i < cg.size(); i++) {
if (cg.isSelected(i)) {
selectedArray[k] = cg.getString(i);
k++;
}
}
return selectedArray;
}
That function will help me get all selected items for deleting action below:
private void deleteSpecificItem() {
try {
String temp = null;
int index;
//get ChoiceGroup size
int numbers = cgTrip.size();
String selectedItems[] = choiceGroupSelected(cgTrip);
//
rs = services.RecordStoreManager.openRecordStoreByName("TripRS");
re = rs.enumerateRecords(null, null, true);
String[] tripList = new String[2];
for (int i = 0; i < numbers; i++) {
temp = selectedItems[i];
if (temp != null) {
while (re.hasNextElement()) {
try {
index = re.nextRecordId();
System.out.println("RecordID: " + index);
byte[] byteBuff = rs.getRecord(index);
String source = new String(byteBuff);
tripList = services.StringManager.getItems(source, ";", 2);
String strProcess = tripList[0] + "-" + tripList[1];
//inspect all of items in choicegroup and if they are selecting then compare with record
//If comparison is true then delete this record
if (temp.equals(strProcess)) {
System.out.println("Delete RecordID: " + index);
rs.deleteRecord(index);
re.keepUpdated(true);
break;
}
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
}
}
}
try {
rs.closeRecordStore();
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
rs = null;
re.destroy();
this.LoadTripItem();
} catch (RecordStoreNotOpenException ex) {
ex.printStackTrace();
}
}
In the tool I am making to aid me in creating my new game I need to be able to load and save tile maps and edit them. When I click the mouse it will change the current tile the mouse is hovering over to the tile of my choice. For some reason whenever I click on any tile the first tile is always changed to some strange blackish color and an index out of bounds exception is thrown. It says "Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1
at Engine.Map.loadUpdatedMap(Map.java:161)
at Engine.Pane.mousePressed(Pane.java:65). I checked the text file and it is replaced with the current tile size (when it should be 0). Code is posted below, any ideas?
this is where the error occurs (Map.java)
public void loadUpdatedMap(){
try {
BufferedReader reader = new BufferedReader(new FileReader(new File(fileName + ".txt")));
for (int i = 0; i < mapHeight; i++){
String read = reader.readLine();
String[] skips = read.split(" ");
for (int j = 0; j < mapWidth; j++){
map[i][j] = Byte.parseByte(skips[j]);
}
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
This is the way I am replacing the tiles (Pane.java)
public void mousePressed(MouseEvent e) {
if (map.created && map.tileSize != 0){
currentX = e.getX() / map.tileSize;
if (e.getY() / map.tileSize > 1){
currentY = (e.getY() - map.tileSize) / map.tileSize;
}
else{
currentY = (e.getY() / map.tileSize);
}
map.setTile(currentX, currentY, currentSelection);
map.loadUpdatedMap();
}
}
Code used to save map
public void saveToLocation(){
try{
if (fileName == null){
fileName = "default";
}
FileOutputStream fout = new FileOutputStream(new File(System.getProperty("user.dir"), fileName + ".txt"));
System.out.println("File was saved to: " + new File(System.getProperty("user.dir"), fileName + ".txt"));
fout.write(String.valueOf(tileSize).getBytes());
fout.write(System.getProperty("line.separator").getBytes());
fout.write(String.valueOf(mapWidth).getBytes());
fout.write(System.getProperty("line.separator").getBytes());
fout.write(String.valueOf(mapHeight).getBytes());
fout.write(System.getProperty("line.separator").getBytes());
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
fout.write(String.valueOf(map[i][j]).getBytes());
fout.write(String.valueOf(" ").getBytes());
}
fout.write(System.getProperty("line.separator").getBytes());
}
fout.close();
}catch (Exception e){
e.printStackTrace();
}
}
Before anything is clicked
After first click
The text file results
How big is your ships array after
String[] skips = read.split(" ");
According to your code it is mapWidth and then you are trying to extract that many elements from the array.
Maybe
for (int j = 0; j < skips.length; j++){
would be more correct
I have a program reading from a text file (currently 653 lines long) all separated by a comma. But when I go to save the file to a new location, it only saves 490 lines. It also seems that the last line in the newly created text file is cut in half. Any ideas on what might be the problem?
Here is the code that I used to open and sort the data in the list:
try {
scanner = new Scanner(file);
// Put the database into an array and
// Make sure each String array is 13 in length
while (scanner.hasNext()) {
line = scanner.nextLine();
word = line.split(",");
if (word.length < 13) {
String[] word2 = {"","","","","","","","","","","","",""};
for (int i = 0; i < word.length; i++) {
word2[i] = word[i];
}
dataBaseArray.add(word2);
}
else {
dataBaseArray.add(word);
}
}
}
catch (FileNotFoundException exc) {
JOptionPane.showMessageDialog(this, "File cannot be found.", "error finding file", JOptionPane.ERROR_MESSAGE);
}
// Splitting the database into vacant numbers/dead lines/vacant cubicles
for (int i = 0; i < dataBaseArray.size(); i++) {
if (dataBaseArray.get(i)[8].equals("VACANT")) {
vacantNums.add(dataBaseArray.get(i));
}
else if (dataBaseArray.get(i)[4].equals("DEAD")) {
deadLines.add(dataBaseArray.get(i));
}
else if (dataBaseArray.get(i)[6].equals("") && dataBaseArray.get(i)[7].equals("")) {
vacantCubs.add(dataBaseArray.get(i));
}
else if (dataBaseArray.get(i)[7].equals("")) {
people.add(dataBaseArray.get(i));
}
else {
people.add(dataBaseArray.get(i));
}
}
// Resetting the DB Array to put the values back in it
dataBaseArray = new ArrayList<>();
// Ordering the arrays I want them to appear in the list
// Orering the people to appear in alphabetical order
Collections.sort(people, new Comparator<String[]>() {
#Override
public int compare(String[] strings, String[] otherStrings) {
return strings[7].compareTo(otherStrings[7]);
}
});
// Put the people in the DB Array
for (int i = 0; i < people.size(); i++) {
dataBaseArray.add(people.get(i));
}
// Put the vacant numbers in the AB Array
for (int i = 0; i < vacantNums.size(); i++) {
dataBaseArray.add(vacantNums.get(i));
}
// Put the vacant cubicles in the AB Array
for (int i = 0; i < vacantCubs.size(); i++) {
dataBaseArray.add(vacantCubs.get(i));
}
// Put the dead lines in the AB Array
for (int i = 0; i < deadLines.size(); i++) {
dataBaseArray.add(deadLines.get(i));
}
list = new String[dataBaseArray.size()];
// Add the DB Array to the list
for (int i = 0; i < list.length; i++) {
if (dataBaseArray.get(i)[8].equals("VACANT")) {
list[i] = "VACANT";
}
else if (dataBaseArray.get(i)[4].equals("DEAD")) {
list[i] = "DEAD";
}
else if (dataBaseArray.get(i)[6].equals("") && dataBaseArray.get(i)[7].equals("")) {
list[i] = "Vacant Cubicle";
}
else if (dataBaseArray.get(i)[7].equals("")) {
list[i] = dataBaseArray.get(i)[6];
}
else {
list[i] = dataBaseArray.get(i)[7] + ", " + dataBaseArray.get(i)[6];
}
}
// Populate the list
lstAdvance.setListData(list);
Here is what I used to save the file:
try {
saveFile = new FileWriter("Save Location");
String newLine = System.getProperty("line.separator");
for (int i = 0; i < dataBaseArray.size(); i++) {
for (int j = 0; j < dataBaseArray.get(i).length; j++) {
saveFile.append(dataBaseArray.get(i)[j] + ",");
}
saveFile.append(newLine);
}
}
catch (IOException exc) {
JOptionPane.showMessageDialog(this,"error", "error", JOptionPane.ERROR_MESSAGE);
}
Writing to a file is buffered. You have to close() or flush() your writer (saveFile) at the end of writing.
Even better: you should do close() on your writer in the finally block.
Try it using the FileWriter and BufferedWriter....
File f = new File("Your_Path");
FileWriter fw = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(fw);
And yes..its very important to do bw.close() (Closing the Buffer)
See this question : Java FileWriter with append mode
The problem is that your FileWriter object needs to be "append mode" . Then, you append to the file with the "write" method rather than the "append" method. Use a finally catch clause to call "close" . You don't need to flush ( I dont think).