Making JRadioButton random - java

my data comes from query like this to my radio buttons:
radio1.setText(Question.get(i).getChoiceOne()) // assign ist choice to ist radio button
radio2.setText(Question.get(i).getChoiceTwo()) // assign second choice to second radio
radio3.setText(Question.get(i).getcorrectchoice()) // assign correct choice to third radio button
In this case each time the correct answer is assigned to third radio button which makes the quiz predictable.. Can I do it in some way where the correct choice some times assign to first radio, some times to second and so on?

You could do following:
String one = Question.get(i).getChoiceOne();
String two = Question.get(i).getChoiceTwo();
String three = Question.get(i).getcorrectchoice();
// construct list from questions.
List<String> choices = Arrays.asList(one, two, three);
// give random order to list
Collections.shuffle(choices);
// set radio button texts
radio1.setText(choices.get(0));
radio2.setText(choices.get(1));
radio3.setText(choices.get(2));

int i = (Math.random() * 1000)%3;// generate a values between 0-2
String[] answers = new String[3];
answers[i] = Question.get(i).getcorrectchoice();// i is the index of right answer
// insert the 2 other answers, what ever i you chose (i+1)%3 will put them in the remaining 2 places
answer[(i+1)%3] = Question.get(i).getfirstchoice();
answer[(i+1)%3] = Question.get(i).getsecondchoice();
i = (i+1)%3;// the original value of i
// insert radios
radio1.setText(answers[0]);
radio2.setText(answers[1]);
radio3.setText(answers[2]);
// get the right answer; get the text of the selected radio
if(textOfselectedRadio.quals(answers[i])){
// correct
}

Related

Displaying Content w/ Button Clicks

I have ten buttons, 0-9 and when one is pressed I want to display its value into a TextView. So the initial display looks like this:
0.00
If I press the 2 button then it should be displayed to the TextView like this:
0.02
Now if I pressed 5 then the new value should be:
0.25
and so on. I've never done anything like this so I'm not exactly sure where to begin. So my question is, whats the best way to implement something like this?
EDIT: I know how to display content when a button is pressed, however, I'm not sure how to transition the each number when a new button is pressed into its new position.
Store an int with the value you are displaying and as you input the number multiply that value by 10 and add the new number on.
Something like:
public void updateValue(int buttonPressed){
currentValue = (currentValue*10) + buttonPressed;
}
then where you're updating the TextView make sure you format the string in a suitable way:
public String formatNum(){
String valueAsString = Integer.toString(currentValue);
while(valueAsString.length()<3){
valueAsString = '0' + valueAsString;
}
char[] stringBuilding = new char[valueAsString.length()+(((valueAsString.length())-2)/3)+1];
int valueAsStringPtr = valueAsString.length()-1;
int stringBuildingPtr = stringBuilding.length-1;
while(stringBuildingPtr>=0){
if(stringBuildingPtr==stringBuilding.length-3){
stringBuilding[stringBuildingPtr--] = '.';
} else if((stringBuilding.length-stringBuildingPtr-3)%4==0){
stringBuilding[stringBuildingPtr--] = ',';
} else {
stringBuilding[stringBuildingPtr--] = valueAsString.charAt(valueAsStringPtr--);
}
}
String returnVal = String.copyValueOf(stringBuilding);
return returnVal;
}
All this assumes you have an integer field currentValue.
Also try to do this on a worker thread ideally to avoid lagging out UI, it shouldn't really take too long, but still a good idea.
Note: for anyone wondering why I elected to use ints instead of float/double is because then we will introduce error displaying a binary representation as a decimal.

for loop jumps to last number in java android development

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.

How to retain newly added values on a two-dimensional array (JAVA)

I'm stuck at this part of my program. These are 2 options for my Student Information System (not using GUI/JOption and without linking to a database. I already have a 2-dimensional array (String records[][] = new String [5][3];) that has the first 2 "rows" ([0][0] to [0][2] and [1][0] to [1][2]) filled up with pre-assigned data (First Name, Last Name, Course).
If you look below, the part where "b" or "B" option is selected, this is for adding new values to a new array (incremented so that when option B is used, it will assign first [2][0], then [3][0]
and so on). It seemed to work since it does show that all the data I've entered was added and is displayed in the proper order. THE PROBLEM IS: when I choose 'Y" to return to the top menu and select option A to VIEW the newly added record (using ID number 2), it shows that it contains all "null". Is there something I've missed? This is the missing step I need in order to finish this program. Thanks ahead for the help.
if("a".equals(option1)|| "A".equals(option1)){
System.out.println("Please enter the Student ID for the record to view.");
String a = reader1.readLine();
idcheck = Integer.parseInt(a);
x1=idcheck;
for(int y=0;y<3;y++){
System.out.print(records[x1][y] + " ");
}
System.out.println("\nReturn to Main Menu or Exit? (Y/N)");
cont1= reader1.readLine();
}
else if("b".equals(option1)||"B".equals(option1)){
arr_count++;
for (int y = 0; y<3;y++){
System.out.println("Enter Value for "+ option [y]+":" );
String X = reader1.readLine();
records[arr_count][y] = X;
}

Passing and incrementing Java variables across methods

EDIT: I changed setChoice(i++) to setChoice(++i). It works.
I want to make a drag/drop activity that loads three TextViews to be dragged to three ImageViews, like this:http://i.imgur.com/dsphSFO.png. I want to make 5 levels where the text changes, the pictures won't.
So I have an activity that has a main method(onCreate), onLongClickListener, onDragListener, a method to set three TextViews(setChoice(int i)), and a method to check the values of the TextViews(checkAll).
In public class I declare a 2d string[], choice, and an int i, along with the TextViews and ImageViews.
int i is what this question is about. In onCreate I initialize everything and:
i = 0;
setChoice(i);
setChoice checks the value of i, if it's less than 5 it matches the TextViews randomly to 1,2,3 and sets the text from the 2d[]:
int num = (int)(Math.random()*3);
tvOne.setText(choice[i][num]);
int num2 = (int)(Math.random()*3);
if(!(num == num2)){
tvTwo.setText(choice[i][num2]);
}else{
do{
num2 = (int)(Math.random()*3);
}while(num == num2);
tvTwo.setText(choice[i][num2]);
}
And then return.
At this point, the TextViews are filled with choice[0][], and the user should drag the words "Truck", "Helicopter", and "Boat" to the images. Each onDrag compares the TextView string to a string from choice[][], which I get like this:
String choiceOne = choice[i][0];
If the strings match, the TextView text gets changed to "Correct". Each time a TextView is changed to "Correct" I call checkAll.
checkAll compares all three TextViews to the string "Correct". If not all match, it returns, otherwise I want to call setChoice(i++) and load the next row from choice[][] (i.e. choice[1][]).
I guess the i that I pass from checkAll(), which should be one higher, isn't incremented, because the TextViews are filled with chioce[0][] again.
What am I doing wrong?

JComboBox item listener

I have two combo boxes. The first contains some operator (+ , - ,* ,/) and the second one contains some value from 0 to 10. When user select (/) in first combo box I want the second one to show a value from 2 to 10 instead of 0 to 10.
I've tried this:
String[] operators = {"+","-" ,"*", "/"};
String[] number = {"0","1","3"....."10"};
divisionModel= new DefaultComboBoxModel(new String[]{"2","3","4","5".."10"});
operatorCombo = new JComboBox(operators);
numberCombo = new JComboBox(number);
operatorCombo.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (operatorCombo .getSelectedItem().equals("/")){
numberCombo .setModel(divisionModel);
}
my problem is when I select ("/") the numberCombo works fine and show me numbers from 2 to 10 but when I click on another operator it still show me the numbers from 2 to 10 instead 0 to 10.How can I solve this problem?!
Thanks
// always compare objects using equals()
if (operatorCombo.getSelectedItem().equals("/")) {..
As to updating the 2nd combo, create a new model for it and call setModel(ComboBoxModel).
You might look at this example that shows how the selection made in one JComboBox can change the appearance of related JComboBox by using a different DefaultComboBoxModel.

Categories

Resources