I have a simple interface that is designed to select one or more seats in a theater and reserve them for yourself.
I have three columns: zone / row / seat. You select the first to populate the second, and the second to populate the third.
When I select them the first time no problem.
If I change the second row, the third row re-populates (in this case all rows have the same number of seats) it does not break!
However if I change the first row everything breaks!
Now the reason for this is kinda clear, but I don't understand exactly why this is.
This is the first list event trigger:
List_Zona.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
if (! arg0.getValueIsAdjusting()){
RowListModel.clear(); // second list
SeatListModel.clear(); // third list
List_Rand.clearSelection(); // second list
List_Scaun.clearSelection(); // third list
int[] rows = self.repository.getRowsForZone(
List_Zona.getSelectedValue().toString()
);
int index = 0;
while (rows[index]!=0) {
RowListModel.addElement(String.valueOf(rows[index]));
index++;
}
}
}
});
It should clear the other column selections so it should not interfere with this next trigger (second column), but apparently it does, or something happens which I don't get:
List_Rand.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
if (! arg0.getValueIsAdjusting()){
SeatListModel.clear();
int[] seats = self.repository.getSeatByZoneAndRow(
List_Zona.getSelectedValue().toString(),
Integer.parseInt(List_Rand.getSelectedValue().toString())//HERE
);
int index = 0;
while (seats[index]!=0) {
SeatListModel.addElement(String.valueOf(seats[index]));
index++;
}
}
}
});
It can't parse the integer because the second column should be cleared, but it's not ? But even though it's not ... it is ?
What I'm trying to say: The second column should be clear (it's not) but if it's not then the error should not occur, but it does.
I hope this makes some sense!
Can anyone spot the problem ? Should I provide more code ?
The error is a NullPointerException at the second column, because something fishy is happening there (again: at the integer parsing).
By my mind the second column's valueChanged should not trigger at all when I click an item in the first column. It should just clear the other two and that's that. Why am I wrong ?
P.S. First Code snippet is responsible for the second one breaking the program.
Maybe I should also rephrase the question How can I safely clear everything when I re-select a new "Zone" (Zona) - Column one ?
The first listener clears the selection of List_Rand. That makes the selection change: it goes from "the index i is selected" to "no index is selected", so the second listener is invoked. And in the second listener, you're trying to call a method on the selected value of List_Rand. Since you just cleared the selection, there's no selected value anymore, hence the NullPointerException.
Side note: your code is very hard to read, because it doesn't respect the Java naming conventions. Variables start with a lowercase letter, and are camelCased (no underscore in their name).
Other side note : what's the point in calling parseInt(selectedValue.toString())? If the list contains Integer instances, the cast the value to Integer directly. If it contains String, then why not store Integers instead, since this is what you want the list to contain?
Related
In my database, I am searching for a specific value. If that value does not exist, it should simply be added, but if it exists, a counter should be added next to it.
So for instance, if the value Hello World already exists, the added value should be Hello World 1, the next one should be Hello World 2 and so on...
This is what I have tried:
int id = newQuoteRepository.findByTitle(data.getTitle()).size();
System.out.println(id);
if (id > 0) {
data.setTitle(data.getTitle() + id);
}
Well, basically it works but it is not really what I want. So if a value is bar, it will add bar1. And next time, it will add bar1 again, because it is searching for bar and so the added value, which was bar1, will be ignored.
So this is what I have: bar, bar1, bar1, bar1 ...
And this is how it should be: bar, bar1, bar2, bar3 ...
What could be a solution for this issue?
One way to solve this would be to add a counter column to your table and whenever you need to show your title, concatenate the title with this counter.
e.g.
int id = newQuoteRepository.findByTitle(data.getTitle()).size();
if (id > 0) {
data.setCounter(data.getCounter() + 1);
// persist it
}
// Show title:
System.out.println(data.getTitle() + " " + data.getCounter());
There are several advantages to this approach.
You work with numbers directly
No need to do some String magic to achieve what you want
Cleaner
You can use findByTitleLike instead of findByTitle for your task.It will find titles match with the given regex.
Hi I am making an android App, I want to add some values to a database and I want to do N times so I used a for loop as seen below:
private void addCodeToDataBase() {
for (int i = 1; i <= 100; i++) {
//indexnumber is a TextView
indexNumber.setText("Please enter the TAN code for Index number " + i);
//tanCode is an EditText
if (tanCode.getText().toString() != null) {
//index here is just an int so i can use the i inside the onClick
index = i;
//add is a button
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String codeText = tanCode.getText().toString();
dbHandler.addcode(index, codeText);
}
});
} else {
Toast.makeText(addcode.this, "Please enter your code !!!", Toast.LENGTH_LONG).show();
}
}
}
but what I am facing here is the for loop jumps to 100 at the first run, What I mean is the text will show :
Please enter the TAN code for Index number 100
it skips 99 numbers!! how would I fix it ?
It's Because your for loop executes so fast that you can't notice that the change of the text.First i is 0,and then it becomes 1,then the text will be "Please enter the TAN code for Index number 1" ......
your loop is working correctly but it is replacing text on each iteration that's why you think that it is jumping on last value please use break point and debug you will see each value on each iteration or use log in which you will see each value
It's not easy to imagine what your code does without seeing your declarations of indexNumber, tanCode, index, and, in particular, add. So, e.g., we don't know how often your if condition yields true.
However, most probably, the problem is that your assignment add.setOnClickListener(...) is just iterated with no user interaction in between. Now if you repeatedly assign something to your add (whatever that is), the last assignment will win.
If you want 100 buttons, you'll need to have an array or List of buttons to press, where each has a different tan code. If you want one button that repeatedly asks for the different tans, then you have to assign the data for click i + 1 only after click i has been handled, i.e. in the on click listener.
To give more specific help, we would need to know how your user interface should look (how many widgets of what kind) and how each widget should behave.
I have a TableView with two Columns (let's call them A and B). I like to loop through column A and print their values to console. My code doesn't seem to work the way I want it to....
for (int i : myTable.getItems().size()) {
System.out.print(columnA.getCellData(i));
}
Suggestions?
You almost had it! But I don't think that for loop is valid - it expects an Array not an int.
for (Object o : myTable.getItems()) {
System.err.println(columnA.getCellData(o));
}
Or if you are using Java 8, this is a shorter way:
myTable.getItems().stream().forEach((o)
-> System.err.println(columnA.getCellData(o)));
This works for me.
If it doesn't just comment and I'll see what's wrong.
I just checked the code and found a small correction - the type of the item for getCellData() must be String not object. For the first example, this would result in:
for (String[] o : myTable.getItems()) {
System.err.println(columnA.getCellData(o));
}
I am building a Sudoku solver that use the Try and Fail technique to solve any problem. My algorithm is:
1)Update (method that remove any possible value that already given as a final value to element in the same Row, column or squar)
2)Get the minimum element that has minimum number of possible values
3)start solve assuming the first possible value is the final value
4)save the current sate into a stack
5)Try to solve
5-a)If solved, return
5-b)if not solved and with invalid Sudoku, then Pop previous state
6)Repeat step 3) for all possible vaues (9)
7)Repeat step 2) until the puzzel is solved
This is my code
Stack<Element[][]> myStack= new Stack<>();
private Element[][] mySudoku;
public void solve(){
update();//remove all final values from all possible values for each element
if(isSudokuSolved(mySudoku)){
return;
}
//find a cell that is not confirmed and has the minimal candidates
int celli=-1,cellj=-1, p=10;
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
if(mySudoku[i][j].getValue()==0){
if(mySudoku[i][j].getPossibleValues().size()<p){
celli=i;
cellj=j;
p=mySudoku[i][j].getPossibleValues().size();
}
}
}
}
try {
for (int c = 0; c < mySudoku[celli][cellj].getPossibleValues().size() - 1; c++) {
//save state
Element[][] copy=deepCopy(mySudoku);//copy the current state
myStack.push(copy);
//apply candidate to cell
mySudoku[celli][cellj].setValue(mySudoku[celli][cellj].getPossibleValues().get(c));
update();//check is solved
if(checkValidInputSudoku(mySudoku)){
solve();
}else{
try {
mySudoku = myStack.pop();
} catch (EmptyStackException est) {
//do nothing
}
}
}
} catch (Exception e) {
}
//if we have reached here then we are at the last possible value for the candidates so confirm candidate in cell
if(celli!=-1 && cellj!=-1 && p!=10) {//Some problems happen here "out of Boundry -1 Error"
mySudoku[celli][cellj].setValue(mySudoku[celli][cellj].getPossibleValues().get(mySudoku[celli][cellj].getPossibleValues().size()-1));
}
}//end of solve method
I have spent more than 6 hours trying to find out the problem. I have checked for the Update() method, deepCopy() method and checkValidInputSudoku() method. They all works fine. Thank you in Advance
I can see one problem in your code. You have a loop that is sawing off the branch it sits on:
for(int c = 0; c < mySudoku[celli][cellj].getPossibleValues().size() - 1; c++) {
...
mySudoku[celli][cellj].setValue(mySudoku[celli]cellj].getPossibleValues().get(c));
...
}
Apart from that, you are missing one of the values, it should be for(c=0; c!=size; ++c), i.e. not size - 1. Also, calling getPossibleValues() just once would make this code much more readable. Lastly, catching and ignoring a stack underflow is just stupid, because it hides errors in your algorithm, as far as I can tell. If you don't know how to handle an error, don't just silence it. Since java requires you to catch it, put it in the outermost place possible or at least abort or do something, but don't ignore it!
One more thing: You are recursing and passing the context data via mySodoku and myStack. This is completely missing the point of recursion (or at least the way it's typically used), because the function call stack is the only stack you need. Using these to pass parameters only makes things more complicated than necessary. Instead, the function should return a partial sodoku puzzle and return either the fully solved puzzle or null. Using is easier to distinguish than the exception you're using now, and it's a regular and expected thing, not really exceptional. Then, when trying different choices, you set the cell to the values in turn and recurse, until the call doesn't return null. If none of the choices returns a solution, you clear the cell and return null yourself.
solve(sodoku):
if sodoku is solved:
return true
if sodoku is invalid:
return false
c = some empty cell
for v in 1...9:
// set to a value and recurse
c = v
if solve(sodoku):
// found a solution
return true
// no solution found, clear cell and return failure
c = null
return false
BTW: This strategy is called "backtracking". Using a cell with the least amount of possible values is called "pruning", which allows you to cut off whole branches from the search tree. Actually determining the possible values also helps avoiding a few futile attempts.
I'm having some problems debugging my code as I can't work out where an array is getting updated. I have looked through all my class files and I'm completely stumped as to what is happening.
At the moment I have a setup whereby I read in a csv file and store the contents in a 2D array (public static double[][] myArray). I then pass this array into a method whenever a user presses a button.
The weird thing is that it works fine the first time, however on all subsequent clicks of the button the data has changed and I can't work out why. I have searched through the code and there are absolutely no references to the original array (i.e. myClass.myArray = newArray) apart from where I pass it into the method.
Is there a reason this is happening? Alternatively please could someone suggest a way to track when the variable gets updated/changed?
Here is a brief overview of the code...
Read in the csv dataset and save it in a variable (ClassA):
public static double[][] myDataset;
// ...
private static void readdDataset(String filePath)
{
CsvReader reader = new CsvReader();
myDataset = reader.readDataset(filePath, true);
}
This is the code used to set up the buttons' action:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
new RunProgram().execute(); // create a swing worker to run the code in bg
}
});
Here is a condensed down version the code in the SwingWorker class:
protected Void doInBackground()
{
Config cfgFile = someClass.createConfigFile();
someOtherClass.runMyProgram(cfgFile, ClassA.myDataset);
return null;
}
Finally here is the code to run the program:
public static void runRegression(Config cfgFile, double[][] dataset)
{
// Print out the first line in the array to see if it is the same every time (it should be!)
for(double value : dataset[0])
{
System.out.print( value + " ");
}
System.out.println();
// Do some other stuff....
}
Every method you pass this array to has the opportunity to change its contents. Your array is not immutable.
From the outline or project view, right-click on the variable, and select "Toggle Watchpoint".
(You can also set conditional breakpoints, which is handy.)
There doesn't need to be a reference to the original array, any reference to a static (mutable) object can manipulate its contents.
So I can't really be sure what is going on for sure since you seem to be dealing with 2d object and classes and I have a very basic understanding on them.
However it sounds like your problem aren’t really the 2d aspects but the storage of the data it uses. It also sounds like your button is the problem or it's before the button gets pressed and since you haven't given us the code I don't think anyone can help you.
Try making a temp bypass for the button so it just auto fires once and see what happens.
As for the debugging the normal way is to say
System.out.println("Array changed " + myArray[0] +" "+ myArray[1] );
This will print in a line on the console
Array changed 1 4 (if myArray[0] == 0 and myArray[1] == 4)
I can't help you anymore without seeing some code and I don't think anyone else can help.