compare lines in JTextArea - java

Im working on a project where I create an online-shop-like application. Have everything working apart from last thing, which is reading the whole basket(items added to basket)
I have a button that adds item to the order(they are displayed in jtextarea).
I have another button that finishes shopping and is supposed to print your items which were added to jtextarea. Unfortunately I was only able to figure out how to read the last line in jtextarea. so basically what happens :
customer orders x, amount 1
customer orders y, amount 3
customer orders z, amount 7
It will only print the last line. any suggestion?
Here is the code
btnFinish.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int end = textArea.getDocument().getLength();
int start = 0;
try {
start = Utilities.getRowStart(textArea, end);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
while (start == end)
{
end--;
try {
start = Utilities.getRowStart(textArea, end);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
String text = null;
try {
text = textArea.getText(start, end - start);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
System.out.println("(" + text + ")"); ```

Related

Is there a good alternative to individual try/catch statements?

Code below is repetitive, no need to read all.
This code finds 8 neighbors around a plane, if the plane is on the edge
index can go out of bounds on each of them, hence I have to check each
individually
// Catch out of bound exception
try {
// top
neighborPlanes.add((Plane) items.get(index - rowLength));
} catch (IndexOutOfBoundsException e) {
// Do nothing
}
try {
// top left
neighborPlanes.add((Plane) items.get(index - rowLength - 1));
} catch (IndexOutOfBoundsException e) {
// Do nothing
}
try {
// top right
neighborPlanes.add((Plane) items.get(index - rowLength + 1));
} catch (IndexOutOfBoundsException e) {
// Do nothing
}
try {
// middle left
neighborPlanes.add((Plane) items.get(index - 1));
} catch (IndexOutOfBoundsException e) {
// Do nothing
}
try {
// middle right
neighborPlanes.add((Plane) items.get(index + 1));
} catch (IndexOutOfBoundsException e) {
// Do nothing
}
try {
// bottom
neighborPlanes.add((Plane) items.get(index + rowLength));
} catch (IndexOutOfBoundsException e) {
// Do nothing
}
try {
// bottom left
neighborPlanes.add((Plane) items.get(index + rowLength - 1));
} catch (IndexOutOfBoundsException e) {
// Do nothing
}
try {
// bottom right
neighborPlanes.add((Plane) items.get(index + rowLength + 1));
} catch (IndexOutOfBoundsException e) {
// Do nothing
}
Is there a way to make this not look terrible?
Would making a function call with nested try/catch inside be a better solution?
Yes, create a separate method like addNoThrow that does the add with the same parameters inside a try/catch.
But as #federico-klez-culloca wrote, it's better to check the values first. That could be done in a safeAdd method that checks inputs and only gets and adds if they are valid.

Get all checked value from the table

I'm trying to get all value from a table where the checkbox is checked, I've make codes but it only gets one output and not working if I checked randomly you have to start checking from the start to make it work.
This the Output I need:
this my current codes I've make:
TableModel model = table_test.getModel();
for(int i=0; i<model.getRowCount();++i)
{
Boolean isChecked = Boolean.valueOf(model.getValueAt(i, 0).toString());
String col = model.getValueAt(i,1).toString();
if (isChecked==true) {
try{
textarea.setText(col);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
}
this codes only display is one value at the text area.
I hope you can help me with this problem.
You can try below.
TableModel model = table_test.getModel();
for(int i=0; i<model.getRowCount();++i)
{
Boolean isChecked = Boolean.valueOf(model.getValueAt(i, 0).toString());
String col = model.getValueAt(i,1).toString();
if (isChecked==true) {
try{
textarea.append(col);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
}

how to implement a linked list properly using java

I am working in a project with linked list (JAVA) but I am not being able to figure out how to insert the person. How could I get the switch to work? Or should I use something else? I also thought about creating a class outside the main method and just call it but it did not work as well. Any help will be much appreciate
public void listOfPeople() { // Beginning of the method listOfPeople where shows the employees
// *** instance the person object ad loading your variables
Personqueue p1 = new Personqueue(); //saving the employee in a variable???
p1.setFname("John");
p1.setLname("Smith");
p1.setDOA(15);
p1.setPassportN(306589);
p1.setNumber(1);
vectorObj.add(p1); // add the employee in a vector
Personqueue p2 = new Personqueue(); //saving the employee in a variable???
p1.setFname("Paul");
p1.setLname("Clooney");
p1.setDOA(5);
p1.setPassportN(30614584);
p1.setNumber(2);
vectorObj.add(p2); // add the employee in a vector
}
public void ascendingOrder(Vector<Personqueue> vector) { // bubble sort method to order the vector
int j;
boolean flag = true; // set flag to true to begin first pass
Personqueue temp; // holding the variable temporarily
while (flag) {
flag = false; // set flag to false awaiting a possible swap
for (j = 0; j < vector.size() - 1; j++) {
if (vector.get(j).getNumber() > vector.get(j + 1).getNumber()) {
temp = vector.get(j); // swap elements
vector.set(j, vector.get(j + 1));
vector.set(j + 1, temp);
flag = true; // shows a swap occurred
}
}
}
}
public void newPerson(int positionPerson) { // beginning of newPerson method
String Option = null; // declaration of local variables that are used only in this method and don't use too much space
Personqueue p = new Personqueue(); //instead of setting it to null, here we are calling
// a constructor which was declared in Personqueue class.
// switch (positionPerson) {
// case 1: // insert a person at the start of the queue
// // p = new QueueStart();
// break; // executes in order to end the switch in case one of the options is valid
// case 2: // insert a person at a chosen point in the queue
// // p = new ChoosePosition();
// case 3: // insert a person at the end of the queue
// // p = new EndQueue();
// break;
// default:
// System.out.println("Invalid Option!!!"); // in case the option is not one of the cases above, print this...
// return; // return to the do/while loop in Principal method
// }
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Name:"); // user input
try {
Option = br.readLine();
String name = Option;
p.setFname(name);
} catch (IOException e) {
System.out.println(e);
}
System.out.println("Surname:"); // user input
try {
Option = br.readLine();
String lname = Option;
p.setLname(lname);
} catch (IOException e) {
System.out.println(e);
}
System.out.println("Date Of Arrival: "); // user input
try {
Option = br.readLine();
int doa = Integer.parseInt(Option); // use parseInt in order to convert Integer to String to be read by BufferedReader.
p.setDOA(doa);
} catch (IOException e) {
System.out.println(e);
}
System.out.println("Passport Number:"); // user input
try {
Option = br.readLine();
int pn = Integer.parseInt(Option);
p.setPassportN(pn);
} catch (IOException e) {
System.out.println(e);
}
System.out.println("Number:"); // user input
try {
Option = br.readLine();
int no = Integer.parseInt(Option);
p.setNumber(no);
} catch (IOException e) {
System.out.println(e);
}
vectorObj.addElement(p); // save all the data in the vector
System.out.print("Saving Person :" + p.getFname()); // print to the user the name's been saved
try {
for (int i = 0; i < 6; i++) {
System.out.print(".");
Thread.sleep(300); // suspend the "." execution for a specified period.
}
} catch (InterruptedException e) { // exception p o method thread // catch for thread above
e.printStackTrace();
}
System.out.println();
System.out.println("Person: " + p.getFname() + " is saved!!!");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} // end of the Method newPerson
Check your variables in listOfPeople(...), p2 was not used correctly.
Take a look at Example of LinkedList in Java

Appending text on a character interval

I am trying to write a program where the participant communicates with the program (I/O) via a console. Trick is, the console is part of a GUI, because I need the program to run off of a executable jar file. I append text with a scrollable text field, like so
textArea.append(printChar);
I give the method a String to work with, and it uses a nested for loop to take it, char by char, and append each Char (using string.substring()).
My problem is that it freezes up the entire time its supposed to be printing, then just displays it all. I don't know why, because I tested it using System.out.print, and it worked exactly as I wanted. So something is different about appending and printing. Any ideas?
Also, I am using Thread.Sleep(100) for my wait time.
public void actionPerformed(ActionEvent evt) {
if (!preforming){
preforming = true;
String input = textField.getText(); //Text from Input
textArea.append(dungeon.name + ": " + input + newline); //Add "text" to bottom of console
String[] output = dungeon.action(input);
//print everything in array output, char by char, with 2-3 seconds after each
for (int i = 0; i < output.length; i++){
String printThis = output[i];
if (printThis.length() > 0){
for (int j = 0; j < printThis.length(); j++){
String printChar = printThis.substring(j, j+1);
textArea.append(printChar);
//System.out.print(printChar);
try{
Thread.sleep(5);
} catch (InterruptedException e) {
System.out.print("Error ");
}
/*try { //useless
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
}
textArea.append("" + newline);
}
//cleaning up input bar
textField.setText("");
textField.selectAll();
//Make sure the new text is visible, even if there
//was a selection in the text area.
textArea.setCaretPosition(textArea.getDocument().getLength());
preforming = false;
}
}
I've edited my answer as you are showing more of your codes. Since, there is an outer loop in your code, I just included it inside the run method of timer in this new edit. And also I don't have the code for the dungeon so I just temporarily replace it with constant values so the program can run in my test.
public void actionPerformed(ActionEvent evt) {
java.util.Timer timer = new java.util.Timer();
timer.schedule(new java.util.TimerTask() {
public void run() {
if (!preforming){
preforming = true;
String newline = "\n";
String dungeonName = "Star Light";
String input = textField.getText(); //Text from Input
textArea.append(dungeonName + ": " + input + newline); //Add "text" to bottom of console
String[] output = {
"Twinkle twinkle little star.",
"How I wonder what you are.",
"Up above the world so high."
};
//print everything in array output, char by char, with 2-3 seconds after each
for (int i = 0; i < output.length; i++){
String printThis = output[i];
if (printThis.length() > 0){
for (int j = 0; j < printThis.length(); j++){
String printChar = printThis.substring(j, j+1);
textArea.append(printChar);
//System.out.print(printChar);
try{
Thread.sleep(25);
} catch (InterruptedException e) {
System.out.print("Error ");
}
/*try { //useless
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
}
textArea.append("" + newline);
}
//cleaning up input bar
textField.setText("");
textField.selectAll();
//Make sure the new text is visible, even if there
//was a selection in the text area.
textArea.setCaretPosition(textArea.getDocument().getLength());
preforming = false;
}
}
}, 1);
}

How to write formatted numbers as numbers in JExcel (jxl)

I am using Java Spring and jxl to create Excel workbook on server side. The data that needs to be shown in Excel consists of already formatted numbers. I am using
WritableCellFormat wcf = new WritableCellFormat();
wcf.setAlignment(Alignment.RIGHT);
....
....
sheet.addCell(new Label(j, i + 1, xxx, wcf));
//where xxx is a string which is a number already formatted
In the downloaded excel file, all these numbers are stored as text and so Excel can't use formulas on them, it gives a warning as 'Number stored as Text' and I have to do 'Convert to Number'.
In jxl, can we pass strings and tell to interpret them as numbers? All the numbers I have are valid numbers formatted differently using $, %, thousands separators. I don't want to convert them to valid numbers and give them formatting again while exporting to excel.
Please help. Thank you.
I had a similar problem
I changed the variable to int and used new Number function it helped.
int eday = Integer.parseInt(Trainingresult.getString("Day"));
//Label Eday = new Label(1, i, eday);
firstsheet.addCell(new Number(1,i,eday));
/*use new Number to write number cell*/
WritableWorkbook w;
try {
w = Workbook.createWorkbook(new File("c:/test.xls"));
WritableSheet s = w.createSheet("Demo Book", 0);
WritableCellFormat wcf = new WritableCellFormat();
for (int i=0;i<10;i++){
int row = i+1;
/*add cell number*/
s.addCell(new Number(1, i, (i*15)));
/*add cell number*/
s.addCell(new Number(2, i, (i*3+Math.random()*10)));
/*add formula*/
s.addCell(new Formula(3,i,"B"+row+" * C"+row));
}
w.write();
w.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RowsExceededException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (WriteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
first, add import
import jxl.write.Number;
because you could get other Number class and get error,
after that do anything
double dval = 1;
Number number = new Number(k, n, dval);
So you could also useful this codes
if(readCell.getType() == CellType.BOOLEAN) {
boolean bv = false;
if(readCell.getContents().equals("true")) {
bv = true;
}
Boolean b = new Boolean(i,j,bv);
writesheet.addCell(b);
} else
if(readCell.getType() == CellType.NUMBER) {
//if (!readCell.getContents().equals("")) {
double dval = 0;
try {
dval = Double.parseDouble(readCell.getContents());
} catch (NumberFormatException ex) {
}
Number n = new Number(i, j, dval);
writesheet.addCell(n);

Categories