I would like to iterate through a list every time a button is pressed, using JButton, JTextField and event's ActionListener. So every time the "next" button is pressed the next item in the array should be displayed in a JTextField. I have already created the getters, setters and constructor, it's literally only the following piece I'm having trouble with.
#Override
public void actionPerformed(ActionEvent evt){
Object source = evt.getSource();
String[] item = getThing();
for(int i = 0; i < 3; i ++){
String currentI = item[i];
}
if(source.equals(btnNxt)){
txtDisplayField.setText(currentI);
}
}
In the if statement I receive an error "Cannot find symbol", referring to currentI.
The currentI variable went out of scope at the end of the loop. You should declare it outside of the for loop.
By the way, the code still won't work properly, because you set the value to the last item of the array every time. You should step only once, and if you are at the last item, jump to the first one.
You're initializing your currentI String within your for loop's scope.
The variable is therefore inaccessible outside your for loop.
Move your equality check and assignment inside the loop.
for(int i = 0; i < 3; i ++){
String currentI = item[i];
if(source.equals(btnNxt)){
txtDisplayField.setText(currentI);
// stop iteration as you already found a match
break;
}
}
I don't see why you need a for loop at all.
Simply :
int ctr = 0;
public void actionPerformed(ActionEvent evt){
ctr++;
if(ctr<item.length)
txtDisplayField.setText(iter[ctr]);
}
That should solve your problem
Related
I wrote a for loop that is supposed to determine if there is user input. If there is, it sets the 6 elements of int[] valueArr to the input, a vararg int[] statValue. If there is no input, it sets all elements equal to -1.
if (statValue.length == 6) {
for (int i = 0; i < 6; i++) {
valueArr[i] = statValue[i];
}
} else {
for (int i : valueArr) {
i = -1;
}
}
I am using Visual Studio Code, and it is giving me a message in for (int i : valueArr) :
"The value of the local variable i is not used."
That particular for loop syntax is still new to me, so I may be very well blind, but it was working in another file:
for(int i : rollResults) {
sum = sum + i;
}
I feel that I should also mention that the for loop giving me trouble is in a private void method. I'm still fairly new and just recently started using private methods. I noticed the method would give the same message when not used elsewhere, but I do not see why it would appear here.
I tried closing and reopening Visual Studio Code, deleting and retyping the code, and other forms of that. In my short experience, I've had times where I received errors and messages that should not be there and fixed them with what I mentioned, but none of that worked here.
for (int i : valueArr) {
.... CODE HERE ...
}
This sets up a loop which will run CODE HERE a certain number of times. Inside this loop, at the start of every loop, an entirely new variable is created named i, containing one of the values in valueArr. Once the loop ends this variable is destroyed. Notably, i is not directly the value in valueArr - modifying it does nothing - other than affect this one loop if you use i later in within the block. It does not modify the contents of valueArr.
Hence why you get the warning: i = -1 does nothing - you change what i is, and then the loop ends, which means i goes away and your code hasn't changed anything or done anything, which surely you didn't intend. Hence, warning.
It's not entirely clear what you want to do here. If you intend to set all values in valueArr to -1, you want:
for (int i = 0; i < valueArr.length; i++) valueArr[i] = -1;
Or, actually, you can do that more simply:
Arrays.fill(valueArr, -1);
valueArr[i] = -1 changes the value of the i-th value in the valueArr array to -1. for (int i : valueArr) i = -1; does nothing.
I have an array of Strings and when the user taps the button inside my app I generate a random number and use it to select a random String from my facts[] array. However, I tried improving my code so that the same random number would "never" occur(leading to the same String been shown to the user). Despite my efforts, my "Check" blocks doesn't seem to work since it generates a random fact when I click the button for the first time and then it does nothing. Please help me figure out the correct logic behind this and maybe write a more efficient code-block.
My current logic: check if the random number that has been generated already exists in my int[] factsCheck array and if it does create another one.If it doesn't add it to the array so that the program knows it has already been created once.
int[] factsCheck = new int[facts.length];
boolean isNotNewRandomNumber = true;
int count = 0;
int randomNumberToReturn;
private void initFactsCheck() {
for(int i=0; i<=factsCheck.length;i++) {
factsCheck[i] = -1;
}
}
String getFact() {
// Randomly select a fact
Random randomGenerator = new Random();
while(isNotNewRandomNumber) {
randomNumberToReturn = randomGenerator.nextInt(facts.length);
for(int i = 0; i<factsCheck.length; i++) {
if(factsCheck[i] == randomNumberToReturn) {
break;
} else {
count++;
}
}
if (count == factsCheck.length) {
// Doesn't exist
isNotNewRandomNumber = false;
}
count = 0;
}
return facts[randomNumberToReturn];
}
In the beginning of getFacts(), add this:
isNotNewRandomNumber = true;
The problem is that you isNotNewRandomNumber to false the first time you call getFacts(), then you never set it to true again, so you will never go into the while loop again.
I'm not sure that's all you need to do. There might be other errors too. It seems unnecessary to have a for loop inside the while loop. There must be a better way. And you probably want to set factsCheck[x] to some appropriate value just before the return statement.
I want write program who in t1(TextField) enter how many numbers user want enter and confirm by b1(Button). In t2(TextField) user give a first value and enter it by b2(Button), in next time user give a second value and again enter it by b2(Button). It happens so much times as high is n (from first listener).
How must I change code that program to do it?
Now when i give to t2 first value and hit the button then b2 is still pressed and user can't do anything.
final AtomicInteger n = new AtomicInteger();
ActionListener lis5 = new ActionListener(){
public void actionPerformed(ActionEvent e) {
String a = t1.getText();
n.set(Integer.parseInt(a));
}
};
b1.addActionListener(lis5);
ActionListener lis6 = new ActionListener(){
public void actionPerformed(ActionEvent e) {
//String b = t2.getText(); ??
//n.set(Integer.parseInt(b)); ??
int nn = n.get();
int [] tab = new int[nn];
for(int i=0;i<nn;i++){
tab[i] = in.nextInt();
}
}
};
b2.addActionListener(lis6);
First of all, get rid of the for loop in the ActionListener. For loops work for linear console programs where you enter data using a Scanner but not for event-driven GUI's. Here instead of the for loop use a counter int variable that you increment within the ActionListener and that you use to help you decide where to place the data. Also get the int array out of the ActionListener and into the class so that it can be available to the rest of the class. In pseudocode:
in the class
int array declared here BUT not initialized here.
first Actionlistener
get total count value
initialize array using this value
end first action listener
second ActionListener
int counter variable set to 0.
action performed method
if counter < total count
get value from text field
convert it to an int
place value into intArray[counter]
increment counter
end if
end action performed
end second ActionLisener
I have multiple buttons containing some information.
Now I want that the information written on the buttons are appended when i press them i.e when i press the first button
- the information gets printed into text field
When I press second button
- the information written on button gets appended or added into the text field with the older information (data in button 1).
code for what I am trying is:
private void EActionPerformed(java.awt.event.ActionEventevt) {
String x = ans.getText();
for(int i = 0; i < x.length(); i++) {
ans.setText("H");
}
}
private void FActionPerformed(java.awt.event.ActionEvent evt) {
String x = ans.getText();
for(int i = 0; i > x.length(); i++) {
ans.setText("A");
System.out.println("completed");
}
}
Simply:
ans.setText(ans.getText() + newString);
There are a few ways to this, setText is one, but it's not particularly efficient (it's easier to type though), as you are creating additional temporary objects though the process
If you need to update the field often, you might consider using something more like...
Document doc = userNameField.getDocument();
doc.insertString(doc.getLength(), newString, null);
There are 20 buttons in an Activity .
The ids are R.id.ButtonR1C1; R.id.ButtonR1C2 .. and so on ie. Row 1, Col 1..
now earlier I had created 20 buttons.
private Button b1,b2,b3...;
and then
b1=(Button)findViewbyId(R.id.ButtonR1C1);
b2=(Button)findViewbyId(R.id.ButtonR1C2);
.... and so on.
Finally
b1.setOnClickListener(this);
b2.setOnClickListener(this);
... 20
so I thought I'd create a Button Array
Button barray[][]=new Button{4][5];
for(int i=1;i<=4;i++) {
for (int j=1;j<=5;j++) {
String t="R.id.ButtonR"+i+"C"+j;
barray[i-1][j-1]=(Button)findViewbyId(Integer.parseInt(t));
}
}
Gives an error..
Any help??
If you have copied your code directly, your syntax is wrong.
Button barray[][]=new Button{4][5];
should be
Button barray[][]=new Button[4][5];
Note the curly bracket instead of square bracket before the 4.
Your next problem, is that you are trying to get the value of R.id.something, but you only have the string representation of it. So, the only way I know to do this is using reflection.
What you need to do is,
Button barray[][]=new Button{4][5];
for(int i=1;i<=4;i++) {
for (int j=1;j<=5;j++) {
Class rId = R.id.getClass();
// this gets the id from the R.id object.
int id = rId.getField("ButtonR"+i+"C"+j).getInt(R.id);
barray[i-1][j-1]=(Button)findViewbyId(id);
}
}
String t="R.id.ButtonR"+i+"C"+j;
Integer.parseInt(t);
This part of your code will definitly throw a runtime exception, because t does not contain a numeric value.
I don't know the format/value of your ID values, but this might work:
Button barray[][]=new Button[4][5]; // type corrected
for(int i=1; i<4; i++) { // changed the for loop...
for (int j=1; j<5; j++) { // changed the for loop...
String t="R.id.ButtonR"+i+"C"+j;
barray[i-1][j-1]=(Button)findViewbyId(t); // t *is* the id (?)
}
}
The Problem is here:
String t="R.id.ButtonR"+i+"C"+j;
barray[i-1][j-1]=(Button)findViewbyId(Integer.parseInt(t));
You're trying to convert a String t to an Integer (while the String is not numeric at all).
This will result in NumberFormatException. You should make sure that t is absolutely numeric.
I used this code:
Class c = Class.forName("com.test.R$id");
Integer i = new Integer(c.getField("ToolsbuttonR3C4").getInt(new R.id()));
System.out.println("HEXA="+i.toHexString(i));
and the ids are in sequential order. so it can be done.
Thanks ppl
So you are trying to convert the String "R.id.ButtonR1C1" to a NUMBER...
That will most certainly give you a NumberFormatException since it is CLEARLY NOT A NUMBER! :)