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?
Related
in an android app i have 4 buttons for which i've given the tags 1,2,3 and 4 respectively, and i want to use for loop to change the text in each button if it matches (or not) a certain value in my code, "i" in the for loop goes from 1 to 4 and i of course convert it into a string..but when i run the code it gives me null object reference and the app crashes
the error occurs when the app calls ans.setText(); or any other method..
**i did try to initiate an object and find it by it's tag outside a loop and it worked with no problems
for(int i=1;i<=4;i++){
Button ans=(Button) view.findViewWithTag(String.valueOf(i));
if(i==correct()){
ans.setText(x+y+"");
}else{
int z=rand.nextInt(100)+rand.nextInt(100);
if(z==x+y){
ans.setText(z+rand.nextInt(100));
}
else{
ans.setText(z);
}
}
}
error given :
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setText(java.lang.CharSequence)' on a null object reference
at com.example.braintrainer.MainActivity.go(MainActivity.java:52)
Bind your layout and parse the views using the childCount instead of the tags.
Assuming it's a Linear Layout you have (but you can adjust it accordingly):
LinearLayout layout = (LinearLayout) findViewById(R.id.name_of_your_layout);
for (int i = 0; i < layout.getChildCount(); i++) {
View v = layout.getChildAt(i);
//add your checks here and set the text using v.setText("...");
}
NOTE: in your loop, you define i as an integer and then you check if i == correct(). Does your correct() method return an integer that's supposed to be equal to i? Maybe you have more issues on the code that you're not sharing here.
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
}
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.
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.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have to Write a program in Java that will take the dimensions of two different homes and calculate the total square footage. The program will then compare the two values and print out a line of text appropriately stating whether it is larger or smaller than the other one.
I am not sure where to even begin. I am new to Java and have only done a Hello World
The first thing you have to do is take input from your user of the length and width of the object. Then you must calculate the sqr ft using the formula :
Length * Width = # of Sqr ft
If you want to do this to two houses you will just need to take two inputs for the second house of the length and width and display that homes total area the same way we did to the first house.
import java.util.*;
public class SqrFoot {
public static void main(String[] args) {
//creates a scanner object
Scanner scan = new Scanner(System.in);
//takes input
System.out.println("Enter the length : ");
double length = scan.nextDouble();
System.out.println("Enter the width : ");
double width = scan.nextDouble();
//calculates and displays answer
System.out.println(length*width + " Sqr ft");
}
}
Does this program take input from the user? If it does, you'll want to use a Scanner to accept user input, as such:
Scanner input = new Scanner(System.in);
You can then use the nextDouble() method to input the house dimensions, like so:
double length1 = input.nextDouble();
Then you can calculate the area of each house:
double area1 = length1 * width1;
Finally, you can use an if-else block to compare the two areas. Here's an example of how you could do it:
if (area1 > area2) {
System.out.println("House 1 is larger than house 2.");
} else if (area1 < area 2) {
System.out.println("House 1 is smaller than house 2.");
} else {
System.out.println("House 1 is the same size as house 2.");
}
This sounds like homework, so I'm not going to do it for you, but I will help you with syntax and let you put it all together.
To store a number you need to declare a variable. Variables come in all different types. There is a:
String Which like the name suggests, is a string of characters like "Hello World". To declare a String named hello that contains "Hello World", type the following:
String hello = "Hello World";
Some important things: String is capitalized. You will learn why later, but just remember it for now. The stuff you were storing in hello started with and ended with a ". As you will see, this is only the case for Strings. Finally, like you may already know, almost every line ends with a ;.
char Which is short for character and stores a single letter (or symbol, but worry about that later). To store the letter 'P' in a variable named aLetter, type the following:
char aLetter = 'P';
Some important things: char like the rest of the variable names I will tell you about, is lowercase. Also, a char starts and ends with an '. Next, I stored a capital P which in Java's mind is completely different than a lowercase p (the point I'm trying to make is everything in Java is case sensitive). Finally, even though my variable name aLetter is two words, I didn't put a space. When naming variables, no spaces. ever.
int Which is short for integer. An int stores a whole number (no decimal places) either positive or negative (The largest number an int can hold is around 2 billion but worry about that later). To store the number 1776 in an int named aNumber, type the following:
int aNumber = 1776;
Some important things: this is pretty straightforward, but notice there aren't any "'s or ''s. In Java "1776" is NOT the same as 1776. Finally, I hope you are noticing that you can name variables whatever you want as long as it isn't a reserved word (examples of reserved words are: int, String, char, etc.)
double Which is pretty similar to int, but you can have decimal points now. To store the number 3.14 in a double named aDecimal, type the following:
double aDecimal = 3.14;
boolean Which is a little harder to understand, but a boolean can only have 2 values: true or false. To make it easier to understand, you can change in your head (not in the code) true/false to yes/no. To store a boolean value of true in a variable named isItCorrect, type the following:
boolean isItCorrect = true;
There are tons more, but that is all you have to worry about for now. Now, lets go to math. Math in Java is pretty self explanatory; it is just like a calculator except times is * and divide is /. Another thing to make sure of, is that you are storing the answer somewhere. If you type 5-6; Java will subtract 6 from 5, but the answer wont be saved anywhere. Instead, do the following:
int answer = 0;
answer = 5-6;
Now, the result (-1) will be saved in the int named answer so you can use it later.
Finally, we have decision making. In computer science, you change sentences like "If the person's age is at least 21, let them into the bar. otherwise, don't let them in." In decision making, you need to turn all of your questions into yes/no questions. When you need to decide a yes/no question, use what are called if statements. The way to write if statements are a little weird: you write the word if then you ask your question in parentheses and you don't but a ;. Instead you put a set of curly braces {}, inside which you write your code that will run if the question in the if statement is true. For example, the bar example above would be, in code, the following:
int age = 25;
boolean letHimIn = false;
if(age>=21)
{
letHimIn = true;
}
Now, the question is, how do you ask a question. To do so, you use the following: <,>,<=,>=,==,!=. These are called comparators because they the things on either side of them. They do the following: < checks if the number on the left is less than the number on the right, > checks if the number on the left is greater than the number on the right, <= checks less than or equal, >= checks greater or equal, == checks if the two numbers are equal, and != checks if the two numbers are not equal. So if(age>=21) asks the question, is the number stored in age greater or equal to 21? If so, do the code in curly braces below. If not, then skip the code. As one more example, the code checks if age is exactly equal to 21 and if so, set letHimInTheBar to true.
int age = 25;
boolean letHimInTheBar = false;
if(age==21)
{
letHimInTheBar = true;
}
Since age is equal to 25 not 21, the code to make letHimInTheBar true never ran which means letHimInTheBar. The final thing to know about decisions is you can use a boolean variable to ask a question directly. In the following example, we are only letting people whose age is NOT equal to 30 into the bar and if we let them into the bar we will print "Welcome to the bar." and if we didn't then we will print "Stay away.". As a reminder ! in Java means not. Meaning that it will flip true to false and false to true.
int age = 25;
int badAge = 30;
boolean letHimIn = false;
if(age!=badAge)
{
letHimIn = true;
}
if(letHimIn)
{
System.out.println("Welcome to the bar.");
}
if(!letHimIn)
{
System.out.println("Stay away.");
}