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.
Related
I have written an app which helps organize home bills. The problem is that in one home can live more than one person, and one person can have more than one home (e.g. me - in both cases :) ). So I've decided to give the user a possibility to bind a contractor (payment receiver) to multiple users and multiple homes.
In my data base there are concatenation tables between accounts and contractors and between homes and contractors. Great, isn't it?
Now, the point is that I'm getting a list of related users (or houses) as sql array, and I finally keep it as Integer[] array. I've made some dummy database entries, so I can test the functionality and it works fine.
But... I have completely no idea how should I properly store changed values in database. The structure of my tables are:
Users
id | username | ....
1 | user1 | ...
2 | user2 | ...
Contractors
id | name | ...
1 | contractor1 | ...
users_contractors
user_id | contractor_id | is_deleted
1 | 1 | false
1 | 2 | false
etc .....
So what I have is: an array of users related to contractor and the second array of users related to contrator (the modified one). Now I need to store the values in DB. When user + contractor does not exists - i need to insert that relation. If it already exists in database, but does not exist in my array (e.g. the connection was deleted) - i need to update the relation table and marked as deleted=true.
I've found some solutions on how to compare two arrays, but they all assume that the arrays are the same length, and they compare values with the same index only.
So what I need is to compare not arrays as we speak, but the array values (if one array contains values from another array, or the opposite). Can this be achieved without forloop-in-forloop ?
Thank you in advance.
Tom
Is there any reason why you are using arrays instead of Lists/Collections? These can help you search for items and make it easier to compare two of them.
I don't have an IDE at hand now, so here is some pseudocode:
// Create a list with all the values (maybe use a hashset to prevent duplicates)
List<int> all = new List();
all.addAll(A);
all.addAll(B);
//for each loop
for (int i : all) {
boolean inA = A.contains(i);
boolean inB = B.contains(i);
if (inA && inB) {
// You can figure out the rest of these statements I think
}
}
Thanks to #DrIvol - I've managed to solve the issue using the code:
List<Integer> allUsers = new ArrayList<Integer>();
allUsers.addAll(bean.getUserId());
allUsers.addAll(bean.getNewUserId());
for(Integer i : allUsers) {
Boolean oldValue = bean.getUserId().contains(i);
Boolean newValue = bean.getNewUserId().contains(i);
if(oldValue && newValue) {
System.out.println(i + " value in both lists");
// Nothing to do
} else if (oldValue && !newValue) {
System.out.println(i + " value removed");
// Set value as deleted
} else if(!oldValue && newValue) {
System.out.println(i + " value added");
// Insert new value to concat table
}
}
It has one problem: If the value was on the first list, and it still is in the second list (no modification) - it's checked twice. But, since I don't need to do anything with this value - it's acceptable for now. Someday, when I'll finish beta version - I'll be doing some optimisations, so I'll make some deduplicator for the list :)
Thank you very much!
Tom
Bit of context...
In my project I have one embedded for loop that outputs data whereby for each category show the item and within each item show its property so in reality the output I generated is 3 columns of data in the console (headings: Category/Item/Property) The for loop to show this data looks like this (Variables are set earlier on in the method):
for... (picks up each category)
for...(picks up items in category)
for (String propertyName : item.getPropertyNames()) {
out.println(category.getName() + "\t"
+ itemDesc.getName() + "\tProperty:"
+ propertyName);
}
}
}
The purpose of the project is to provide a more dynamic documentation of the properties of set components in the system. (The /t making it possible to separate them in to individual columns on a console and even in a file in say an excel spreadsheet should I choose to set the file on the printstream (Also at the start of this method.))
The Problem
Now for the problem, after the for loops specified above I have generated another for loop separate from the data but shows the list of all the functions and operators involved in the components:
//Outside the previous for loops
for (Function function : Functions.allFunctions) {
out.println(function.getSignature());
}
What I want is to set this list as the 4th column but the positioning of the for loop and the way it is set leaves it fixed on the first column with the categories. I cant add it after property names as the functions are more generic to everything in the lists and there maybe repetitions of the functions which I am trying to avoid. Is there a way to set it as the forth column? Having trouble finding the sufficient research that specifies what I am looking for here. Hope this makes sense.
One solution, if the total amount of output is small enough to fit in memory, is to simply save all the data into an ArrayList of String, and output it all at the very end.
List<String> myList = new ArrayList<String>();
for... (picks up each category)
for...(picks up items in category)
for (String propertyName : item.getPropertyNames()) {
myList.add(category.getName() + "\t"
+ itemDesc.getName() + "\tProperty:"
+ propertyName);
}
}
}
int i = 0;
// Here we assume that the total lines output by the previous set of loops is
// equal to the total output by this loop.
for (Function function : Functions.allFunctions) {
out.println(myList.get(i) + "\t" + function.getSignature());
i++;
}
public class P4 {
public static void main( String[ ] args ){
// Create maze
String fileName = args[0];
Maze maze = new Maze(fileName);
System.out.println("Maze name: " + fileName);
// Get dimensions
int mazeWidth = maze.getWidth();
int mazeHeight = maze.getHeight();
System.out.println("Maze width: " + mazeWidth);
System.out.println("Maze height: " + mazeHeight);
I asked this question earlier, but I do not think I added enough detail. The exact instructions for this part of the project are:
Add code to print "Success" or "Failure" based on the return value from each move.
The maze object also has a method called maze.isDone() that returns a boolean.
The boolean is true when the student has found the Java icon, otherwise it is false.
Add enough calls to maze.moveRight() to make the student find the Java icon.
Add a call maze.isDone() before and after the last move, and print the result.
I entered an "if (true)" statement and then had it print out the word "Success", but I do not think that is correct because it is not printing "Failure" if a move is not legal in the maze (ie. entering a move that would move out of the boundaries of the maze). So when I enter "maze.moveRight(); to move the little person in the maze, it prints "Success", but it prints it after all of my moves, like if I input "maze.moveRight(); and then "maze.moveLeft();" it prints "success" after both moves rather than after each, how do I get it to print after each? Also, it prints the word "Success" the line after it states what row the character moved to, like
Moved to row 0, column 1
Moved to row 0, column 0
Success
how do I get it to print something like "Moved to row 0, column 0: Success"?
I appreciate all the help, you do not have to give me answers because I want to understand this, so helpful tips would be more appreciated. Thank you!
Unfortunately, without seeing how your maze class operates, it's not really possible to tell What you're doing.
However, if you're referring to how to make it all on one line. Look into java's System.Out.print() function. If you're simply using #println() every time, it is creating a new line on each call so it wont append it to the end of your line.
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?
First of all I just begun learning Java and i can say it more challenging then C or python. I'm not very keen on programming to so I have hard time understanding how some codes works. This one in particular
public class Pseudo
{
final int a = 2;
final int c = 3;
int address;
String list[][] = new String [100][6];
public void AddRecord(String ID, String Name, String Course, String Address, String Email, String Contact)
{
address = (a * Integer.parseInt(ID) + c) % list.length;
if((Integer.parseInt(ID)<100000||Integer.parseInt(ID)>999999)||ID.length()==0 || Name.length()==0 || Course.length()==0 || Address.length()==0)
{
showMessageDialog(null,"The ID number should be in six digit and the particular field should not be empty","",ERROR_MESSAGE);
}
else{
if(list[address][0]!=null){
showMessageDialog(null,"Collison is occur, the same address is get. Recalculating...............","",WARNING_MESSAGE);
while(list[address][0]!=null)
{
address = (a * address + c) % list.length;
}
}
list[address][0] = ID;
list[address][1] = Name;
list[address][2] = Course;
list[address][3] = Address;
list[address][4] = Email;
list[address][5] = Contact;
showMessageDialog(null,"Student Information " + ID + " will be saved in address: " + address,"",INFORMATION_MESSAGE);
}
}
The confusion come when
address = (a * Integer.parseInt(ID) + c) % list.length;
if((Integer.parseInt(ID)<100000||Integer.parseInt(ID)>999999)||ID.length()==0 || Name.length()==0 || Course.length()==0 || Address.length()==0)
What does it mean. From what I understand from this code is that inside an IF statement you can have more then 1 condition. I'm no very sure since this is my first time seeing such a code.
The second is this
if(list[address][0]!=null){
showMessageDialog(null,"Collison is occur, the same address is get. Recalculating...............","",WARNING_MESSAGE);
while(list[address][0]!=null)
{
address = (a * address + c) % list.length;
}
}
list[address][0] = ID;
list[address][1] = Name;
list[address][2] = Course;
list[address][3] = Address;
list[address][4] = Email;
list[address][5] = Contact;
showMessageDialog(null,"Student Information " + ID + " will be saved in address: " + address,"",INFORMATION_MESSAGE);
If collision occurs the address of which it is stored should be altered using a psedorandom number generator again but what I can't grasped is
list[address][0]!=null.I am just baffle with this line. I know its job is change the address if collision happens but i don't know the exact mechanics of how this part is executed.
From what I understand from this code is that inside an IF statement you can have more then 1 condition.
Well, yes and no. You can construct complex conditions based on many smaller conditions, but ultimately the whole thing has to resolve to a single boolean true/false result.
Consider the condition in this case:
(Integer.parseInt(ID)<100000||Integer.parseInt(ID)>999999)||ID.length()==0 || Name.length()==0 || Course.length()==0 || Address.length()==0
Let's break that down into its components:
(
Integer.parseInt(ID)<100000 ||
Integer.parseInt(ID)>999999
) ||
ID.length()==0 ||
Name.length()==0 ||
Course.length()==0 ||
Address.length()==0
It's really just chaining together a bunch of comparisons into one big true/false statement. You can essentially read something like this as:
If (something) or (something else) or (another thing) then...
And each something can itself contain small somethings, etc. You can build as complex a logical condition as you want, grouping sub-conditions with parentheses, as long as the whole thing resolves to a single true/false result.
what I can't grasped is list[address][0]!=null
That is just checking if a particular value is null. That value is part of a nested (jagged) array. So you have a variable called list. That variable is an array. Each element in that array is, itself, also an array. So you end up with a kind of 2-dimensional array (but a jagged one, where any given sub-array doesn't have to be the same length as any other).
That specific piece of code looks into the list array, at the address index, and looks at the 0 index of that sub-array, and checks if that value is null.
First of all, understanding any code is much easier if it's properly formatted. All good IDEs have such a function, e.g. for Eclipse the shortcut is Ctrl+Shift+F, for IntelliJ IDEA Ctrl+Alt+L.
The most important part, which might resolve your first confusion: || is the logical OR in Java, meaning the ID must be a number between 100000 and 999999 and the attributes must not be empty. Or literally, if the ID is smaller than 100000 or larger than 999999 or any of the values are empty, there will be an error message and nothing will be done.
For the second part: null means that a variable is not set, so to prevent overwriting an entry you can check if it's already set, i.e. not equal to null. So the code changes the address variable until an address is found for which no data is set yet and then uses it to store the given data.
There are several potential problems in this code, among which:
several calls to the relatively slow Integer.parseInt(String) where it could be called once and stored into a variable
potential NumberFormatException if ID isn't a number (or is empty, or has some excess white spaces)
potential infinite loop if the array is full
But as it looks like some CS homework it shouldn't matter.
Thank You so much Mr David. I understand the first part where if u have a condition u can stack it on each other and from what i can understand it only works with the ||(OR) statement since using this will guarantee either a true or false ending.
while(list[address][0]!=null)
But I'm still a little confuse for part 2 of my problem. Since that line is to check the array is null meaning no value right.This is my understanding of the situation.That particular part of the code is suppose to resolve any collision if the user enters the same ID number right so shouldn't it be checking the value that's causing the collision. But the line seems to be doing is as long as a null value is detected the corresponding procedure would be implemented.