What is the best way to verify if a specific combination of two symbols is already selected in a several couples of jcomboboxes? This question is refered to a situation in which I have e. g. 10 options and for each of those I can assign a combination of two symbols where first one is from [ALT, CTRL, SHIFT] vector and second one is from [letters and numbers] vector. Both vectors are visualized in JComboBoxes (for each option are two combo boxes).
Put couples of jcomboboxes into different buckets. Those couples that have ALT selected in first combobox go to the 1st one, those who have CTRL selected - to the 2nd one, SHIFT - to the 3rd one. Then see whether the same option in the second combobox is selected within the buckets.
Thank you everyone for answers. Finally I manage this problem this way:
// Method For KeyGroup 1
public boolean isAlreadyKeyEvent(int index) {
int vector[] = {combo_1_group1.getSelectedIndex(), combo_2_group1.getSelectedIndex(), combo_n_group1.getSelectedIndex()};
int x = 0;
for (int i : vector) {
if (i == index) {
x++;
}
}
if (x > 1) {
return true;
} else {
return false;
}
}
// Method For KeyGroup 2
public boolean isAlreadyInputEvent(int index) {
int vector[] = {combo_1_group2.getSelectedIndex(), combo_2_group2.getSelectedIndex(), combo_n_group2.getSelectedIndex()};
int x = 0;
for (int i : vector) {
if (i == index) {
x++;
}
}
if (x > 1) {
return true;
} else {
return false;
}
}
combo_1_group2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean one = isAlreadyKeyEvent(combo_1_group2.getSelectedIndex());
boolean two = isAlreadyInputEvent(combo_1_group1.getSelectedIndex());
if (one) {
if (two) {
JOptionPane.showMessageDialog(null, "Such shortcut already exists! \n" +
"Choose something else.");
combo_1_group2.setSelectedIndex(Settings.combo_1_group2);
} else {
Settings.combo_1_group2 = combo_1_group2.getSelectedIndex();
}
} else {
Settings.combo_1_group2 = combo_1_group2.getSelectedIndex();
}
}
});
So basically I've wrote two quite similar methods and also I've created a new class with static fields for values store. All works great :)
Related
I'm currently working on a search method in school and I'm stuck in a newbie mistake.
I havent been programming for long and I tried searching the internet for solutions but couldnt find any. I would need to get a number range from 1-10 from the textfield and then put it as an int. Once I've done that I would have to send it to my search method which I am working on. Thanks in advance peeps.
String Value = txfSort.getText();
int NumberValue = Integer.valueOf(Value);
Probably you should first limit the input of textFields to nummeric values. You can help your self with question here: What is the recommended way to make a numeric TextField in JavaFX?
public class NumberTextField extends TextField
{
#Override
public void replaceText(int start, int end, String text)
{
if (validate(text))
{
super.replaceText(start, end, text);
}
}
#Override
public void replaceSelection(String text)
{
if (validate(text))
{
super.replaceSelection(text);
}
}
private boolean validate(String text)
{
return text.matches("[0-9]*");
}
}
Code by: Burkhard
Above code would automaticly check on entry if input is ok. So then you just check, if value is > 0 and < 10. If that is true you just call your method and use value of textField.
One way of doing described would be this:
int value = Integer.valueOf(txfSort.getText());
if(value > 0 && value < 10)
{
myMethod(value);
}
try that one:
textField.addKeyListener(new KeyAdapter(){
public void keyTyped(KeyEvent e) {
char caracter = e.getKeyChar();
if (((caracter < '0') || (caracter > '9')) // for numbers only
&& (caracter != '\b')) {
e.consume();
}
if (Integer.valueOf(textField.getText() + caracter) > 10) {
e.consume(); // if on the text field the numbers are bigger
// than 10, consumes the last number typed
}
}
});
Note: I came across the question below and I wanted to generalize the problem and implement it, but it turns out that it is not easy. This question is making me crazy. This is NOT a Homework question just a curiosity.
Question
There are three containers whose sizes are 10 pints, 7 pints and 4 pints respectively. The 7-pint and 4-pint containers start out full of water, but the 10-pint container is initially empty.
Since there are no marks on the containers, you can pour the contents of one container into another and stop under the following conditions:
the source container is empty
the destination container is full
What sequence of moves should you make if you want to isolate exactly 2 pints of water?
Source: page 102, Question 3.8
Solution
Answering that question is easy using directed graph data structure where nodes contain tuples to represent a certain state.
We start from the initial state (node), and then we create a node representing a possible next state, and we connect it to initial node, and then run BFS to find the shortest path.
Pattern of each state (or node): <10-pint container, 7-pint container, 4-pint container>
Initial state or node: <0, 7, 4>.
The nodes connected to the initial state (or node): <7, 0, 4>, <4, 7, 0>, as you can see from the picture.
Generalised Question
But suppose if want to generalized the problem, suppose we have three containers whose sizes are x, y and z pints respectively such that x >= y >= z.
The y-pint and z-pint containers start out full of water but the x-pint container is initially empty.
What sequence of moves should you make if you want to isolate exactly a pints of water?
Suggesting a Solution to Generalised Version
Here (DropBox, GitHub) is my source code so far.
Here are two important method in main class. They fill the graph based on all possibilities, and it also makes sure there is no duplicate node.
public static void fillGraph(int x, int y, int z) {
TupleContainer initialState = new TupleContainer(x, y, z);
TupleContainer currentState = initialState;
Iterator<TupleContainer> it, it_1, it_2, it_3;
Graph.addNode(initialState);
it = addAdjacentEdgesToTuple(currentState).iterator();
while (it.hasNext()) {
it_1 = addAdjacentEdgesToTuple(it.next()).iterator();
while (it_1.hasNext()) {
it_2 = addAdjacentEdgesToTuple(it.next()).iterator();
while (it_2.hasNext()) {
it_3 = addAdjacentEdgesToTuple(it.next()).iterator();
while (it_3.hasNext()) {
addAdjacentEdgesToTuple(it.next()).iterator();
}
}
}
}
public static Collection<TupleContainer> addAdjacentEdgesToTuple(
TupleContainer currentState) {
TupleContainer tempTupleContainer;
Collection<TupleContainer> CollectionLevel;
Iterator<TupleContainer> it;
CollectionLevel = currentState.MixUpContainers();
it = CollectionLevel.iterator();
while (it.hasNext()) {
tempTupleContainer = it.next();
if (graphContains(tempTupleContainer) != null)
Graph.addNode(tempTupleContainer);
else
tempTupleContainer = graphContains(tempTupleContainer);
Graph.addEdge(currentState, tempTupleContainer);
}
return CollectionLevel;
}
My Question
My code just fills the graph to depth of 4, but how can I set depth and make it run recursively or how make it run until all possibilities are taken to consideration without going into infinite loop. What is the algorithm to this generalized question?
Hm ... there may be better algorithms, but if you simply want arbitrarily deep recursion without going into endless loops, you can use a breadth first search that visits each node only once, i.e. if it hasn't already been visited:
public class Test {
public static void main(String[] args) throws Exception {
State initialState = new State(null, 0, 7, 4);
Set<State> reached = new HashSet<>();
Queue<State> pending = new ArrayDeque<>();
pending.add(initialState);
while (!pending.isEmpty()) {
State state = pending.remove();
if (isGoal(state)) {
printPathTo(state);
return;
}
for (State s : state.adjacentStates()) {
if (!reached.contains(s)) {
reached.add(s);
pending.add(s);
}
}
}
System.out.println("There appears to be no solution.");
}
private static boolean isGoal(State state) {
for (int a : state.content) {
if (a == 2) {
return true;
}
}
return false;
}
private static void printPathTo(State state) {
if (state != null) {
printPathTo(state.previous);
System.out.println(state);
}
}
}
class State {
final static int[] capacity = { 10, 7, 4 };
final int[] content;
final State previous;
public State(State previous, int... content) {
this.content = content;
this.previous = previous;
}
Iterable<State> adjacentStates() {
List<State> result = new ArrayList<>();
for (int i = 0; i < content.length; i++) {
for (int j = 0; j < content.length; j++) {
if (i != j) {
int[] newContent = Arrays.copyOf(content, content.length);
int movedQuantity = Math.min(content[i], capacity[j] - content[j]);
newContent[i] -= movedQuantity;
newContent[j] += movedQuantity;
result.add(new State(this, newContent));
}
}
}
return result;
}
#Override
public int hashCode() {
return Arrays.hashCode(content);
}
#Override
public boolean equals(Object obj) {
return Arrays.equals(content, ((State) obj).content);
}
#Override
public String toString() {
return Arrays.toString(content);
}
}
You can also try iterative deepening search, we were given a demonstration of it working on the same problem in uni and it worked well.
I have two arraylist name preBusinessList, businessList. In business List I have data from server, and in preBusinessList is the local one. In lists I have id, count value Betterly demonstrate as below
Now I wanted to make a newBusinessList like this
How can I do it in java, please help me to solve this
Then I would use a map to do the merge using id as the key and convert it back to your list of (id,value) pairs
You can use:
Collections.sort(new ArrayList<...>(preBusinessList).addAll(businessList), comparator)
Where comparator is a class that implements Comparator interface (will be responsible for sorting as you wish)
assumming i understood your problem correctly (big if...):
also, i assume each element in the lists is a Pair - as it looks from your data (just a dumb wrapper class that holds 2 integers). if its some other class you'll need to adjust this code.
private Map<Integer,Integer> finalValues = new HashMap<Integer,Integer>();
for (Pair<Integer,Integer> entry : preBusinessList) {
finalValues.put(entry.getFirst(), entry.getSecond());
}
//2nd list overwrites values from 1st (anything not overwritten remains)
for (Pair<Integer,Integer> entry : businessList) {
finalValues.put(entry.getFirst(), entry.getSecond());
}
ArrayList<Pair<Integer,Integer>> finalList = new ArrayList<>();
for (Map.Entry<Integer,Integer> entry : finalValues) {
finalList.add(new Pair(entry.getKey(), entry.getValue());
}
//and now sort the list
Collections.sort(finalList, new Comparator<Pair<Integer,Integer>> {
int compare(Pair<Integer,Integer> a, Pair<Integer,Integer>b) {
return a.getFirst.compareTo(b.getFirst()); //compare by 1st number in pair only
}
});
Assuming something like:
public class Info {
public int id;
public int info;
}
You could merge them on the basis of wanting the keep the one with higher info field as follows:
// Assumes:
// - that the ArrayLists are sorted to have id in order going up
// - no repeated ids in a or in b (but same id can be in both a and b)
ArrayList<Info> merge(ArrayList<Info> a, ArrayList<Info> b) {
int aLength = a.size();
int bLength = b.size();
int ai = 0;
int bi = 0;
ArrayList<Info> result = new ArrayList<Info>();
while ((ai < aLength) && (bi < bLength))
Info aInfo = a.get(ai);
Info bInfo = b.get(bi);
if (aInfo.id == bInfo.id) {
if (aInfo.info >= bInfo.info) result.add(aInfo);
else result.add(bInfo);
ai++;
bi++;
}
else if (aInfo.id < bInfo.id) {
result.add(aInfo);
ai++;
}
else {
result.add(bInfo);
bi++;
}
}
// Add the remaining terms - only one of the loops will actually do anything
for (; ai<aiLength; ai++) {
result.add(a.get(ai));
}
for (; bi<biLength; bi++) {
result.add(b.get(bi));
}
}
Pseudocode :
Iterate over preBusinessList.
Fetch key and see if this key(1,2,3,4,5,6) exists in businesslist
If yes conitnue
Else If no, then add it to businesslist
for(Map.Entry<Integer, Integer> keyValue : preBusinessList.entrySet()) {
if(!businesslist.containsKey(keyValue.getKey())) {
businesslist.put(keyValue.getKey(), keyValue.getValue());
}
}
Updated Answer as per new requirements
boolean ifExists = false;
for(PlaceItems itemPreBusinessList : preBusinessList) {
ifExists = false;
for(PlaceItems itemBusinessList : businessList) {
if(itemBusinessList.businessId == itemPreBusinessList.businessId) {
// Already exists
ifExists = true;
break;
}
}
if(!isExists) {
businessList.add(itemPreBusinessList);
}
}
I'm trying to learn Java and basically my approach has been to take the procedural style I learned with python, and apply it to Java. So I never use classes and just put everything in a single class with many methods(which I just use as python functions). I think I've hit a problem, and need to bite the bullet and use classes, but I'm having trouble wrapping my head around how to do it.
To simplify my problem(ignore the poor design- it's just to illustrate the point), I have a program that takes a list and within a for loop does some math on each item(in this case adds 1 to the value of the list). I only want it to do work on 2 items on the list and then stop(in this example it's the first 2 items but in my real program it could be anywhere in the list). Here's the working code that is similar to how I'm already doing it:
No Classes:
public class LearningClasses {
public static void main(String[] args) {
int[] list = new int[]{1,2,3,4,5,6,7,8,9,10};
int[] data_list = new int[list.length];
for (int current_location = 0; current_location<list.length;current_location++) {
for (int i =0; i<100; i++){
if (check_size(data_list) == false ) {
break;
}
data_list[current_location] = (list[current_location]+1);
}
}
//its done now lets print the results
for (Integer item : data_list) {
System.out.println(item);
}
}
private static boolean check_size(int[] data_list) {
// TODO Auto-generated method stub
int count = 0;
for (int item : data_list) {
if (item != 0) {
count++;
if (count>=2) {
break;
}
}
}
if (count>=2) {
return false;
} else {
return true;
}
}
}
The problem with this code is although it works it's inefficient because it calculates the count on every iteration of the second for loop. In my program I cannot put anything above the first for loop but I can put anything below it, so I thought instead of doing the count every time maybe I could use a class to somehow maintain state and just increment the number as oppose to recalculating every time.
With classes:
public class LearningClassesCounter {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] list = new int[]{1,2,3,4,5,6,7,8,9,10};
int[] data_list = new int[list.length];
for (int current_location = 0; current_location<list.length;current_location++) {
//can only put commands in here. Nothing above.
Counter checker = new Counter(data_list);
System.out.println(checker.check_data());
for (int i =0; i<100; i++){
data_list[current_location] = (list[current_location]+1);
}
}
//its done now lets print the results
for (Integer item : data_list) {
System.out.println(item);
}
}
}
class Counter {
private int count; // current value
private boolean continue_or_not;
private int[] data_list;
// create a new counter with the given parameters
public Counter(int[] data_list) {
data_list = this.data_list;
count = 0;
continue_or_not = true;
}
public boolean check_data() {
// TODO Auto-generated method stub
int count = 0;
for (int item : data_list) {
if (item != 0) {
count++;
if (count>=3) {
break;
}
}
}
if (count>=3) {
return false;
} else {
return true;
}
}
// increment the counter by 1
public void increment() {
count++;
}
// return the current count
public int value() {
return count;
}
}
This doesn't work because it thinks the data_list is a null pointer(I know I'm declaring it null, but if I make it private int[] data_list = data_list it doesn't compile either). My ultimate goal is to have some kind of controls, in this case its limiting it to 2 items but I want to also add other limits like total value of al items cannot exceed X or cannot be lower than X and want to save CPU power by not having to do full calculations every time. So I think I need to be able to increment the values and then need to check that those increments haven't exceeded thresholds.
Can anyone help me understand what I'm doing wrong? Am I only wrong with syntax; or am I designing this wrong?
//can only put commands in here. Nothing above.
Counter checker = new Counter(data_list);
System.out.println(checker.check_data());
When you are calling checker.check_data(), its trying to parse through the data_list, but its empty. So, it throws a NullPointerException. The data_list is empty because inside your constructor, you may need to initialize like this this.data_list = data_list instead of data_list = this.data_list (here this.data_list has no reference so NULL)
If you avoid that call, the output will be 2,3,4,5,6,7,8,9,10,11.
Trying to add objects to a ArrayDeque at random intervals. This is what I have
for (int i = 0; i <= 100; i ++) {
if (window.isEmpty()) {
Customer customer = new Customer(r.nextInt(10)+1);
q.add(customer);
window.beginService();
}
else {
Customer customer = new Customer(r.nextInt(10)+1);
q.add(customer);
window.beginService();
totalCustomers++;
totalServiceTime += window.serviceTime;
totalWaitTime += customer.getArrivalTime();
}
}
The other methods being used are
public boolean isEmpty() {
if (serviceTime == 0) {
return true;
}
else
return false;
}
public void beginService() {
if (isEmpty()) {
serviceTime = r.nextInt(10)+1;
}
else
serviceTime += r.nextInt(10)+1;
}
public Customer(int arrivalTime) {
this.arrivalTime = arrivalTime;
}
public int getArrivalTime() {
return arrivalTime;
}
When I print out my customer count it is equal to my clock time, which should not be as customers are added at random intervals of 1-10. Any ideas?
Are you defining your "clock time" as the value of i? If so, I'm not sure why you would expect it and totalCustomers to be different.
In your for loop, you add a customer regardless of whether or not the windows is empty. After the first time around, the window will never be empty because you are always beginning service which always increments the serviceTime by at least 1.
So after the first iteration of the loop, the else branch of your if will exclusively be executed and totalCustomers will always increment alongside of i.
I think you have bigger logic gaps in your code but you haven't been very clear with how you've framed your question or shown your code. It is unclear how serviceTime is declared or what the code is supposed to be doing. You never seem to take an item off of the queue. If you need more help than this you need to put some more effort into your question.