I have this code which applies a counter to each item on the list. When the item reaches a certain number it is moved from jList3 to jList 1.
public Map<Object, Integer> buttonMap = new HashMap<Object, Integer>();
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
Integer counter = null;
int[] selection = jList3.getSelectedIndices();
for (int i = 0; i < selection.length; i++){
Object selString = jList3.getModel().getElementAt(selection[i]);
counter = buttonMap.get(selString);
if(counter == null ) {
buttonMap.put(selString, new Integer(1));
}
else {
buttonMap.put(selString, new Integer(counter.intValue() + 1));
}
System.out.println(selString + " has been clicked " + buttonMap.get(selString) + " times.");
try{
if (counter == 4){
listModel2.removeElement(selString);
listModel.addElement(selString);
}
}
catch (NullPointerException npe1) {
npe1.getMessage();
}
}
}
The behavior comes in the if counter == 4 section.
It works fine but here is the weird part that I need help understanding
If I am counting up two items at the same time and they both reach the number that moves them on the same button click.
-It moves 1 of the items
-It does not count up on the other
-Instead it adds +1 to the counter of a non highlighted item
Example:
I am counting on list item 1 and 2, they both reach the max number, 1 gets moved 2 stays put(no increase in count) and item 3 gets +1 to counter
When you remove an element from jList3, the elements that follow are shifted.
I would sort the selection array and scan it in reverse order.
...
int[] selection = jList3.getSelectedIndices();
Arrays.sort(selection);
for (int i = selection.length; --i >= 0; ){
...
UPDATE: the sorting is not required, because the array returned by getSelectedIndices() already is
The problem is that you are modifying one of your model lists in the same loop as in which you are querying it. If you were using an iterator you would actually get a concurrent modification exception, but as it is you are using specific indexing. In either case your logic is now wrong because the indexes you were relying on to query the list have changed. You can sort your selection array in descending order and keep your code the way it is, but I think it will be cleaner and more maintainable to modify your source array after the loop is done, like so:
...
System.out.println(selString + " has been clicked " + buttonMap.get(selString) + " times.");
if (counter == 4) {
listModel.addElement(selString);
}
}
for(Object o : listModel) {
listModel2.removeElement(o);
}
Related
I am not experienced in Java, but I need to create Java snippet node in KNIME.
I am trying to write a short Loop that creates a counter/iterator based on a specific condition. I managed to write the IF THEN ELSE part but I wonder how to put it inside the Loop:
out_user_session_counter = 1;
if (c_session_end.equals("session end")) {
out_user_session_counter = out_user_session_counter + 1;
} else {
out_user_session_counter = out_user_session_counter + 0;
}
The idea is: each time c_session_end.equals("session end")
then out_user_session_counter should be augmented by 1
UPD.: Here is screenshot of data model with loop result (not correct result):
Correct expected result would be 1 1 1 1 2 2 3 3 3 3 3
instead of 1 1 1 1 11 1 11 1 1 1 1
You need the loop counter to persist between rows in the Java Snippet. To do that, you define it in the //Your custom variables: part of the snippet:
int sessionCounter=0;
Then in the //Enter you code here: part:
if("session end".equalsIgnoreCase(c_column2)){
sessionCounter++;
}
out_user_session_counter = sessionCounter;
As shown, the row with 'session end' will contain the incremented counter. If you want it to contain the old counter, change the snippet so that the final line above is before the if statement.
You don't need to put this in a loop in KNIME - the expression part of the snippet is already calculated sequentially for each input row. Shown below in the snippet dialog for clarity
You need to work with for/while loops to achieve that.
int out_user_session_counter = 1; //Step 1
while(c_session_end.equals("session_end")) { //Step 2
out_user_session_counter++; //Step 3
//Step 4 Other code to modify c_session_end.equals("session_end")
}
Step 1. In this step we initialize the variable to 1
Step 2. While the variable is equal to session_end
Step 3. increment the variable by 1 ( note that this is the same as out_user_session_counter = out_user_session_counter + 1; )
Step 4. Code to modify the c_session_end value must be placed so loop exits as some point or the loop will never stop.
What happens in your code is the following => if(c_session_end.equals("session end")) increment the variable by one, otherwise increment it with 0.
If you want it to run multiple times you have to use while or for loops.
You need a simple loop and this will take care of your else part itself.
int out_user_session_counter = 1;
while(c_session_end.equals("session end")){
out_user_session_counter++;
}
Hope this helps.
Well, we don't know what you are looping, but I assume you are looping some Strings.
This example shows how to loop a List<String> containing session events while counting the ones that equal "session end":
public static void main(String[] args) {
// create a data structure for sample data
List<String> sessionEvents = new ArrayList<String>();
// add some sample data
sessionEvents.add("session start");
sessionEvents.add("session somthing");
sessionEvents.add("session end");
sessionEvents.add("session start");
sessionEvents.add("session something");
sessionEvents.add("session something");
sessionEvents.add("session something");
sessionEvents.add("session end");
sessionEvents.add("session start");
sessionEvents.add("session something");
sessionEvents.add("session end");
// define a counter variable (considering Java naming conventions)
int outSessionCounter = 0;
// use an enhanced for loop (aka for-each loop)
for (String sessionEvent : sessionEvents) {
// every time the event is "session end"...
if (sessionEvent.equals("session end")) {
// ... increment the counter
outSessionCounter++;
}
}
// print the result
System.out.println("Amount of session ends is " + outSessionCounter);
}
This just counts occurrences of "session end", but you would have to tell us if you are using a different data structure or maybe even a stream.
Im not exactly sure what you're trying to achieve, but I think I have something
class Result{
public int out_user_session_counter = 1;
public String c_session_end;
}
Result r = new Result();
r.c_session_end = /*[whatever you want it to be];*/ "";
Thread thread = (new Thread(new Runnable() {
int out_user_session_counter = 1;
public void run() {
out_user_session_counter = 1;
while (!Thread.interrupted()) {
if (r.c_session_end.equals("session end")) {
out_user_session_counter++;
r.out_user_session_counter = out_user_session_counter;
}
//code to modify the r.c_session_end
}
}
}));
thread.start();
//to get the result do
int result = r.out_user_session_counter;
this will keep looping indefinitely.(this can go within a method)
you can edit the result object to influence the
Try something like this:
out_user_session_counter = 1;
int loopCycles = 10
for(int i = 0; i < loopCycles; i++){
if (c_session_end.equals("session end")) {
out_user_session_counter = out_user_session_counter + 1;
}
}
You can simply do something like:
out_user_session_counter = 1;
int loop_counter =0;
int rows = 10 //or some other variable that contains the number of rows
while(loop_counter < rows) {
if (c_session_end.equals("session end")) {
out_user_session_counter = out_user_session_counter++;
loop_counter++;
}
System.out.println(out_user_session_counter);
}
All you need to do is add a loop to the outer portion of you code. Any loop will do, I used a while loop. You could use a for loop as well.
for(int i = 0; ii < rows; ii++){
if (c_session_end.equals("session end")) {
out_user_session_counter = out_user_session_counter++;
}
System.out.println(out_user_session_counter);
}
Or, you can use a do-while loop:
int index = 0;
do{
if (c_session_end.equals("session end")) {
out_user_session_counter = out_user_session_counter++;
index++;
}
System.out.println(out_user_session_counter);
} while (index < rows);
It should be noted that with the do-while loop, you will alway enter the loop, even if there are no rows available (the rows are 0).
Also, you don't need the else portion, as there is no point in adding 0 to your value, you can simply skip it.
public static void main(String[] args){
........................
for(int i = 0; i<play.size(); i=i+1){
System.out.println("the Winner is; " +Winners(play).get(i).name);
}
}
This is the main method. i didnt write down Everything here, because its unnecesary. basically what i am doing, is that i am Calling Winners method that takes ArrayList<Game> as argument. play is of type ArrayList<Game>. on that i want to get the elements stored inside and get their name. so that the winners name is shown on screen. i for loop it because there can be several winners. depends on how many shares the same score.
private static ArrayList<Game> Winners(ArrayList<Game> gamers){
ArrayList<Game> winner = new ArrayList<Game>();
for(int i = 1; i==gamers.size(); i=i+1){
if(gamers.get(i).getPoints()>gamers.get(i-1).getPoints()){ winner.clear();
winner.add(gamers.get(i));
}
else if(gamers.get(i).getPoints()<gamers.get(i-1).getPoints()){ winner.clear();
winner.add(gamers.get(i-1));
}
else if(gamers.get(i).getPoints()==gamers.get(i-1).getPoints()){ winner.clear();
winner.add(gamers.get(i));
winner.add(gamers.get(i-1));
}
}
return winner;
}
the Winners method returns an Arraylist<Game>, which is where the gamer or gamers with top score are stored.
i loop through each on of the gamers and compare their points to each other. the one who has the most score gets stored in the Winner arraylist.
i clear the winner arraylist all the time some elements goes inside, because i only want the top Points stored there.
My issue is, i dont know if i am doing it correct. because i am getting error on
on the System.out.println("the Winner is; " +Winners(play).get(i).name);.
it says index 0 size 0 (indexoutofboundsexception)
for(int i = 1; i==gamers.size(); i=i+1)
It means the loop will terminate when i==gamers.size() is false. At the first time when i=1, but gamers.size() is greater than 1. It never enters the loop. And returns empty list. When you trying to get one element from an empty list, you are getting the exception.
But I think you want to check i < gamers.size(). It might be:
for(int i = 1; i < gamers.size(); i++)
Again, you don't need winner.clear() in each if block. Rather you could:
private static ArrayList<Game> Winners(ArrayList<Game> gamers) {
ArrayList<Game> winner = new ArrayList<Game>();
for (int i = 1; i < gamers.size(); i++) {
winner.clear();
if (gamers.get(i).getPoints() > gamers.get(i - 1).getPoints()) {
winner.add(gamers.get(i));
} else if (gamers.get(i).getPoints() < gamers.get(i - 1).getPoints()) {
winner.add(gamers.get(i - 1));
} else { // last check when points are equal
winner.add(gamers.get(i));
winner.add(gamers.get(i - 1));
}
}
return winner;
}
N.B: There is an issue in the approach of your Winners() method. You are iterating over gamers and adding a winner to the list. But every time you are clearing the list. That means you will get only the winner from last two players. Previous winners will be cleared. I think you need to recheck it.
As you are clearing the list, the size of winner list won't be same as the size of play. As a result, you will also get exception in this code.
for(int i = 0; i < play.size(); i=i+1) {
System.out.println("the Winner is; " + Winners(play).get(i).name);
}
One fix could be:
ArrayList<Game> winnersList = Winners(play);
for(int i = 0; i < winnersList.size(); i++) {
System.out.println("the Winner is; " + winnersList.get(i).name);
}
public void actionPerformed(ActionEvent e)
{
int clicked = 0;
if(arg == "Enter")
{
clicked++;
}
if (clicked == 0)
{
names[0] = nameField.getText();
numbers[0] = numberField.getText();
}
if( clicked == 1)
{
names[1] = nameField.getText();
numbers[1] = numberField.getText();
}
if(arg == "Print")
{
String name = nameField.getText();
String number = numberField.getText();
JOptionPane.showMessageDialog(null,names[0] + numbers[0] + names[1] + numbers[1] + numbers[2] + names[2],"Info",JOptionPane.INFORMATION_MESSAGE);
}
My program must take multiple names and numbers and be able to enter them into an array. After all of the data is entered, it must be able to be printed. I am having trouble under the Enter method because it continues to reset everytime instead of remaining constant. It only allows me to print the last typed name/number instead of saving all of the content. I am unsure of how to fix this and would be grateful for any suggestions at this point.
You could start by moving int clicked out of this function.
Right now your actionPerformed function each time its called reset your clicked to 0 since you are setting it to 0 at the beggining of it.
public void actionPerformed(ActionEvent e)
{
int clicked = 0; //HERE is your problem
if(arg == "Enter");
...
Making it a variable of class instead of function should help.
EDIT:
You can do something like this:
int clicked = 0
public void actionPerformed(ActionEvent e)
{
if(arg == "Enter"){
names[clicked] = nameField.getText();
numbers[clicked] = numberField.getText();
clicked++;
}
As it was mentioned you could also use List, since it would save problems if you don't know how big of an array u need.
List<String> names = new ArrayList<String>();
List<String> numbers = new ArrayList<String>();
And in use
if(arg == "Enter"){
names.add(nameField.getText());
numbers.add(numberField.getText());
}
Instead of an array, you could use an ArrayList, it will allow you to add elements without having to supply an index.
Without givening away too much, like this:
ArrayList<String> names = new ArrayList<String>();
...
names.add("Johnny"); // Adds to the end of the list
names.add("Frank");
That way you don't need to keep the 'clicked' count.
You can use .get(i) to get the element at index i. Or just loop over the entire list using a for each loop:
for(String name : names) { // i.e. for each 'name' in 'names'
System.out.println(name);
// Or do something else with 'name'
}
I am processing elements of an ArrayList in random order, generally by printing them out. I would like to detect when the randomly selected index is 0 or 1 so as to perform special handling for those cases, where the handling for index 0 is partially dependent on whether index 1 has previously been processed. Specifically, nothing is immediately printed when index 1 is processed, but if it is processed then when index 0 is subsequently processed, both the index 1 and the index 0 values are printed. In any event, the loop is exited after ten iterations or after processing index 0, whichever comes first.
I tried to implement this using if statements, but there where obvious flaws with that one. I have searched everywhere for any examples but found none. I have begun to consider using sorting algorithms or threads to hold the first value found then continue looping until it sees the second the print it out. I would appreciate any help possible.
Here is my code:
public static void random_sortType(){
types = new ArrayList<String>();
types.add("Start");
types.add("Starting");
types.add("Load");
types.add("Loading");
types.add("End");
ran = new Random();
int listSize = types.size();
String tempEventType;//the temp variable intended to hold temporary values
for(int i = 0; i < 10; i++){ //the loop goes round the ArrayList 10 times
int index = ran.nextInt(listSize);//this produces the random selection of the elements within the list
if(index == 0){
out.println(types.get(index));
out.println();
break;
}
if(index == 1){
tempEventType = types.get(index);
if(index == 0){
tempEventType = types.get(0) + " " + types.get(1);
out.println(tempEventType);
break;
}
}/*if(index == 0){
tempEventType = types.get(0) + " " + types.get(1);
out.println(tempEventType);
break;
}*/
//out.print("Index is " + index + ": ");
//out.println(types.get(index));
}
}
You need to store the random generated index into a global variable and update it everytime a random number is generated. It should be something like this.
public static void random_sortType(){
types = new ArrayList<String>();
types.add("Start");
types.add("Starting");
types.add("Load");
types.add("Loading");
types.add("End");
` int previousIndex;
ran = new Random();
int listSize = types.size();
String tempEventType;//the temp variable intended to hold temporary values
for(int i = 0; i < 10; i++){ //the loop goes round the ArrayList 10 times
int index = ran.nextInt(listSize);//this produces the random selection of the elements within the list
previous_index =index;
if(index == 0){
out.println(types.get(index));
out.println();
break;
}
if(index == 1){
tempEventType = types.get(index);
if(previousIndex == 0){
temp EventType = types.get(0) + " " + types.get(1);
out.println(tempEventType);
break;
}
According to your description, these are the basic requirements for your application:
Process ArrayList in random order
Processing = printing value at randomly selected index
Make 10 attempts to process items in the list.
Detect when random index is 1 or 0.
if 1
don't process, but flag it was selected.
if 0 && 1 is flagged
process 0 and 1
exit
If these requirements are correct, here is the implementation I came up with:
import java.util.ArrayList;
import java.util.Random;
import static java.lang.System.*;
public class RandomSort {
private static final int MAX_ATTEMPTS = 10;
private static boolean wasOneSelected = false;
public static void main(String[] args) {
ArrayList<String> types = new ArrayList<>(5);
types.add("Start");
types.add("Starting");
types.add("Load");
types.add("Loading");
types.add("End");
random_sortType(types);
}
public static void random_sortType(ArrayList<String> types) {
Random ran = new Random();
int lastIndex = types.size() - 1; // index range is from 0 to 4
for (int i = 0; i < MAX_ATTEMPTS; i++) {
int index = ran.nextInt(lastIndex);
if ( (index == 0) && wasOneSelected) {
process(types.get(index) + " " + types.get(index + 1));
break;
} else if (index == 1) {
wasOneSelected = true;
} else {
process(types.get(index));
}
}
}
public static void process(String str) {
out.println("Processing: " + str);
}
}
The key here is the inclusion of the boolean wasOneSelected initialized to false. Once it is set to true, it will never be false again for the duration of the application. The if-else block handles all branching within the loop, and I favored wrapping the println call into a method called "process" for readability purposes to align it more closely with your description.
Feedback appreciated :)
Im working on an Digital Technology assessment. It's a Program to store a customers Pizzas, Extras and information at a Pizza store. In my confirmation window, I need to print all the pizzas he is ordering. Here are my hashmaps:
private HashMap<Integer, String> pizzas = new HashMap<Integer, String>();
private HashMap<String, Integer> pizzas_count = new HashMap<String, Integer>();
And my addPizza method, aswell as my getOrder method
public void addPizza(String name){
if(pizzas.containsValue(name)){
int count = pizzas_count.get(name);
pizzas_count.remove(name);
pizzas_count.put(name, count++);
}else{
pizzas.put(pizzas.size(), name);
pizzas_count.put(name, 1);
}
}
public String getOrder(){
String order = "";
System.out.println(pizzas.toString());
int i;
for(i = 0; i < 12; i++){
if(pizzas.get(i) != null){
System.out.println(pizzas.get(i));
order = order + pizzas_count.get(pizzas.get(i)) + " x " + pizzas.get(i) + "\n";
}
}
return order;
}
My console is showing "{0=bbq}", even after adding multiple pizzas.
The getOrder method is returning (After adding 1 pizza and 1 extra):
PIZZAS
null x null
EXTRAS
1 x pasta
Any help would be much appreciated.
After first insertion of bbq pizza to pizza map, any subsequent insertion will just increment "bbq"'s counter as the following code suggest:
if(pizzas.containsValue(name)){ // if "bbq" already exist, increment its counter
// but is it really happening?
int count = pizzas_count.get(name);
pizzas_count.remove(name);
pizzas_count.put(name, count++);
// this line is not having any effect why?
}else{
pizzas.put(pizzas.size(), name);
pizzas_count.put(name, 1);
}
in your code pizzas_count.put(name, count++); is not having any effect at all. This line is actually equivalent to:
{
int count = pizzas_count.get(name);
pizzas_count.put(name, count); // count wasn't changed
count = count + 1;
}
Instead do pizzas_count.put(name, ++count);. Rest of the things are working correctly as you have written. After fixing it, the following input code:
addPizza("pizza");
addPizza("extra");
addPizza("pizza");
System.out.println(getOrder());
produces following output:
{0=pizza, 1=extra}
pizza
extra
2 x pizza
1 x extra