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.
Related
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 + ")"); ```
i'm new in Reactive programming and have a lot of questions.
I think it is not a lack of examples or documentation it is just my understanding is wrong.
I'm trying to emulate slow subscriber;
Here is the code example
Flux.create(sink -> {
int i = 0;
while (true) {
try {
System.out.println("Sleep for " + MILLIS);
Thread.sleep(MILLIS);
int it = i++;
System.out.println("Back to work, iterator " + it);
sink.next(it);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).subscribeOn(Schedulers.elastic())
.subscribe(x -> {
try {
System.out.println("Value: " + x + ", Thread: " + Thread.currentThread().toString());
Thread.sleep(MILLIS + 4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System out is
Sleep for 1000
Back to work, iterator 0
Value: 0, Thread: Thread[elastic-2,5,main]
Sleep for 1000
Back to work, iterator 1
Value: 1, Thread: Thread[elastic-2,5,main]
Sleep for 1000
Back to work, iterator 2
Value: 2, Thread: Thread[elastic-2,5,main]
I thought if subscriber is slow, i should see more threads due to Schedulers.elastic()
Also i tried to make publishOn() and it seems like i make it async, but still couldn't handle result in several threads.
Thanks for comments and answers.
If you want it to run in diferent threads you need to use .parallel() like this and the emit will be don in different thread
Flux.create(sink -> {
int i = 0;
while (true) {
try {
System.out.println("Sleep for " + MILLIS);
Thread.sleep(100);
int it = i++;
System.out.println("Back to work, iterator " + it);
sink.next("a");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
})
.parallel()
.runOn(Schedulers.elastic())
.subscribe(x -> {
try {
System.out.println("Value: " + x + ", Thread: " + Thread.currentThread().toString());
Thread.sleep(100 + 4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
})
;
}
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
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);
}
I have used Jtidy parser in java to fetch the title text.
String titleText=null;
try {
titleText = doc.getElementsByTagName("title").item(0)
.getFirstChild().getNodeValue();
} catch (Exception e1) {
try {
titleText = doc.getElementsByTagName("title").item(1)
.getFirstChild().getNodeValue();
} catch (Exception e2) {
try {
titleText = doc.getElementsByTagName("title").item(2)
.getFirstChild().getNodeValue();
} cathc (...)
}
}
above code is working fine,It is reading title at 0'th index,if not found then at 1'st index,and then at 2'nd index.But here I am getting issue:-for some page,title text is present at mid of page or below that,so this code is not working for such pages.In this way,for such condition, length of program is getting increased.Is there any other solution,which will read the title from entire page in one go?.Please help me.
I suggest you do it like this:
String titleText=null;
NodeList titles = doc.getElementsByTagName("title");
for (int i = 0; titleText == null && i < titles.getLength(); i++) {
try {
titleText = doc.item(i).getFirstChild().getNodeValue();
} catch (SomeException e) {
}
}