Value of 1 array equals the value of another in Android - android

I have two arrays :
String []myExpressions = {"20+10","50+50","25+25","10+15"};
String []answers = {"30#","100#","50#","25#"};
When the user clicks the generate button it generates an expression from the array myExpressions and displays it in text-field. Then I require the user to enter the answer using the buttons provided. The answer is displayed in a EditText. When the user enters an answer they should enter a #(like a submit button) and if is the correct answer it should display correct in a text-field. So if the position in the expression array is 1, the correct answer is in the answer array in the same position. How would i check if they are in the same position?
For example: myExpressions[1] correct answer to this is answers[1].
Here is my code:
package com.gamesup.braingame;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Easy extends Activity implements OnClickListener{
EditText display;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.easy);
display = (EditText)findViewById(R.id.displayText);
display.setText("?");
final String []myExpressions = {"20+10","50+50","25+25","10+15"};
final String []answers = {"30#","100#","50#","25#"};
final TextView displayExpression = (TextView) findViewById(R.id.expression);
Button generate = (Button) findViewById(R.id.random_gen);
generate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Random ranGenerate = new Random ();
int random = ranGenerate.nextInt(4) ;
displayExpression.setText(myExpressions[random]);
}
});
}
static boolean isEmpty = true;
public void num_Clicked(View v){
Button btn = (Button) findViewById(v.getId());
//getting the button object and using a view to get the id of the buttons
if (v.getId()== R.id.del_button){
String s = display.getText().toString();
s = s.substring(0, s.length() - 1);
display.setText(s);
return;
}
if(isEmpty){
display.setText(btn.getText());
isEmpty = false;
}
else{
display.append(btn.getText().toString());
// storing the existing number into editText and current text is set
//to current button value
//display.setText(number+btn.getText().toString());
//the total in the editText
}
if (v.getId()== R.id.hash_button){
String userAns = display.getText().toString();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}

For starters arrays in Java Begin at Index 0 so therefore , to compare the first items of the Array you should be using something like this to check if things are equal:
EditText myAnswer = (EditText) findViewById(R.id.myAnswer);
String answer = myAnswer.getText().toString();
// Notice my loop starts at 0 because the first index of an array is 0
for(int i = 0 ; i < answers.length; i++)
{
if(answers[i].equals(answer))
{
// Congratulate the User for getting it Right
}
}
It seems as though you have a little bit of a shaky logic. IMHO you should be using a multidimensional Array.
With a multidimensional Array you can essentially set up keys and values.
This is how I think your application should be configures
// This Array says , I am an array that holds arrays
String [][] multiArray = {{"4 + 5", "9"},
{"20 * 3","60"},
{"99 - 9","90"}};
// Fetch your random question, since we know our questions are the first item in out Array we can use the index [x][0] depending on the index you pull from
String question = multiArray[0][0];
// To do this randomly
Random ranGenerate = new Random ();
int random = ranGenerate.nextInt(4) ;
String question = multiArray[random][0];
// Get the Answer from yout EditText
String answer = myAnswer.getText().toString();
// Using a for loop iterate on the base index
for(int i = 0; i < multiArray.length ; i++)
{
// if the answer is in position 1 of Array [i]
if(answer.equals(mutliArray[i][1])
{
// We have found the answer, Congratulate the User
}else{
// Tell them how bad they are since they can't solve simple equations!
// ....joking obviously we would be nice and let them know its not the answer
}
}

In this line
int random = ranGenerate.nextInt(4) ;
why don't you make random an instance variable inside your class? This way you would preserve the index, and you would know which index to use to compare the answer.

Related

Android, Reading blank values

I'm new to android development, I trying to create a simply Pythagorean Calculator, I need help with reading if a lines blank, but still calculates instead of failing.
Here is my code
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private EditText sideAObj;
private EditText sideBObj;
private EditText sideCObj;
private EditText outputObj;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sideAObj = (EditText) findViewById(R.id.SideAInput);
sideBObj = (EditText) findViewById(R.id.SideBInput);
sideCObj = (EditText) findViewById(R.id.SideCInput);
outputObj = (EditText) findViewById(R.id.OutputText);
}
public void calculateClick(View v){
try {
double sideA = Double.parseDouble(sideAObj.getText().toString());
double sideB = Double.parseDouble(sideBObj.getText().toString());
double sideC = Double.parseDouble(sideCObj.getText().toString());
if (sideAObj.getText().toString().equalsIgnoreCase("0")) {
double pt = Math.sqrt((sideC * sideC) - (sideB * sideB));
outputObj.setText(String.format("%.2f", pt));
}
}
catch (NumberFormatException ex){
Toast errMess = Toast.makeText(getApplicationContext(),"Enter Numbers Only",Toast.LENGTH_SHORT);
errMess.show();
outputObj.setText(String.format("%2.f",0.00));
return;
}
}
public void clearClick(View v){
sideAObj.setText("");
sideBObj.setText("");
sideCObj.setText("");
outputObj.setText("");
sideAObj.requestFocus();
}
}
My program will calculate if their is a Zero on 1 line, but if I leave it blank the program fails entirely, whats the best way to prevent that.
It will obviously fail as it doesn't know how to parse a blank value into a double. Just use something like this during instantiation itself:
double sideB = (sideBObj.getText().toString() == "") ? 0 : (Double.parseDouble(sideBObj.getText().toString()));
double sideC = (sideCObj.getText().toString() == "") ? 0 : (Double.parseDouble(sideCObj.getText().toString()));
Basically, you will be assigning the value 0 if the edit text field is 0 else, you will parse the value entered to a double.
Assuming you want to consider a 0 if there is a blank edit text field.
========================================================================
UPDATE
if(sideAObj.getText().toString() != ""){
double sideA = Double.parseDouble(sideAObj.getText().toString());
}
The simple solution for this problem would be to check each edittext whether they are blank or not and then perform the task.
Get the value of each Edittext to a int variable and then use loop and with the help of edittext.length() method verify if it is equal to 0, if yes, then assign a value to 0 to a new global variable, else assign the exact value to global variable.
and then perform the calculation with the new variables.
Sample code for better understanding :-
String a = et.getText().toString();
int l = a.length();
if (l == 0){
// set the value of global variable = 0;
} else {
// set the value of global variable = a {Actual Digit}
}

Android- Cannot increment a counter on first correct attempt

I'm trying to add mod this so that each time a player guesses the flag on the first attempt, increment a counter. This value will then be displayed at the end when 10 flags is completed. So far i've only gotten it to display the number of guesses and correct answer percentage.
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.AssetManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class FlagQuizGame extends Activity
{
// String used when logging error messages
private static final String TAG = "FlagQuizGame Activity";
private List<String> fileNameList; // flag file names
private List<String> quizCountriesList; // names of countries in quiz
private Map<String, Boolean> regionsMap; // which regions are enabled
private String correctAnswer; // correct country for the current flag
private int totalGuesses; // number of guesses made
private int correctAnswers; // number of correct guesses
private int guessRows; // number of rows displaying choices
private Random random; // random number generator
private Handler handler; // used to delay loading next flag
private Animation shakeAnimation; // animation for incorrect guess
private TextView answerTextView; // displays Correct! or Incorrect!
private TextView questionNumberTextView; // shows current question #
private ImageView flagImageView; // displays a flag
private TableLayout buttonTableLayout; // table of answer Buttons
private int counter;
// called when the activity is first created
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState); // call the superclass's method
setContentView(R.layout.main); // inflate the GUI
fileNameList = new ArrayList<String>(); // list of image file names
quizCountriesList = new ArrayList<String>(); // flags in this quiz
regionsMap = new HashMap<String, Boolean>(); // HashMap of regions
guessRows = 1; // default to one row of choices
random = new Random(); // initialize the random number generator
handler = new Handler(); // used to perform delayed operations
counter = 0;
// load the shake animation that's used for incorrect answers
shakeAnimation =
AnimationUtils.loadAnimation(this, R.anim.incorrect_shake);
shakeAnimation.setRepeatCount(3); // animation repeats 3 times
// get array of world regions from strings.xml
String[] regionNames =
getResources().getStringArray(R.array.regionsList);
// by default, countries are chosen from all regions
for (String region : regionNames )
regionsMap.put(region, true);
// get references to GUI components
questionNumberTextView =
(TextView) findViewById(R.id.questionNumberTextView);
flagImageView = (ImageView) findViewById(R.id.flagImageView);
buttonTableLayout =
(TableLayout) findViewById(R.id.buttonTableLayout);
answerTextView = (TextView) findViewById(R.id.answerTextView);
// set questionNumberTextView's text
questionNumberTextView.setText(
getResources().getString(R.string.question) + " 1 " +
getResources().getString(R.string.of) + " 10");
resetQuiz(); // start a new quiz
} // end method onCreate
// set up and start the next quiz
private void resetQuiz()
{
// use the AssetManager to get the image flag
// file names for only the enabled regions
AssetManager assets = getAssets(); // get the app's AssetManager
fileNameList.clear(); // empty the list
try
{
Set<String> regions = regionsMap.keySet(); // get Set of regions
// loop through each region
for (String region : regions)
{
if (regionsMap.get(region)) // if region is enabled
{
// get a list of all flag image files in this region
String[] paths = assets.list(region);
for (String path : paths)
fileNameList.add(path.replace(".png", ""));
} // end if
} // end for
} // end try
catch (IOException e)
{
Log.e(TAG, "Error loading image file names", e);
} // end catch
correctAnswers = 0; // reset the number of correct answers made
totalGuesses = 0; // reset the total number of guesses the user made
quizCountriesList.clear(); // clear prior list of quiz countries
// add 10 random file names to the quizCountriesList
int flagCounter = 1;
int numberOfFlags = fileNameList.size(); // get number of flags
while (flagCounter <= 10)
{
int randomIndex = random.nextInt(numberOfFlags); // random index
// get the random file name
String fileName = fileNameList.get(randomIndex);
// if the region is enabled and it hasn't already been chosen
if (!quizCountriesList.contains(fileName))
{
quizCountriesList.add(fileName); // add the file to the list
++flagCounter;
} // end if
} // end while
loadNextFlag(); // start the quiz by loading the first flag
} // end method resetQuiz
// after the user guesses a correct flag, load the next flag
private void loadNextFlag()
{
// get file name of the next flag and remove it from the list
String nextImageName = quizCountriesList.remove(0);
correctAnswer = nextImageName; // update the correct answer
answerTextView.setText(""); // clear answerTextView
// display the number of the current question in the quiz
questionNumberTextView.setText(
getResources().getString(R.string.question) + " " +
(correctAnswers + 1) + " " +
getResources().getString(R.string.of) + " 10");
// extract the region from the next image's name
String region =
nextImageName.substring(0, nextImageName.indexOf('-'));
// use AssetManager to load next image from assets folder
AssetManager assets = getAssets(); // get app's AssetManager
InputStream stream; // used to read in flag images
try
{
// get an InputStream to the asset representing the next flag
stream = assets.open(region + "/" + nextImageName + ".png");
// load the asset as a Drawable and display on the flagImageView
Drawable flag = Drawable.createFromStream(stream, nextImageName);
flagImageView.setImageDrawable(flag);
} // end try
catch (IOException e)
{
Log.e(TAG, "Error loading " + nextImageName, e);
} // end catch
// clear prior answer Buttons from TableRows
for (int row = 0; row < buttonTableLayout.getChildCount(); ++row)
((TableRow) buttonTableLayout.getChildAt(row)).removeAllViews();
Collections.shuffle(fileNameList); // shuffle file names
// put the correct answer at the end of fileNameList
int correct = fileNameList.indexOf(correctAnswer);
fileNameList.add(fileNameList.remove(correct));
// get a reference to the LayoutInflater service
LayoutInflater inflater = (LayoutInflater) getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
// add 3, 6, or 9 answer Buttons based on the value of guessRows
for (int row = 0; row < guessRows; row++)
{
TableRow currentTableRow = getTableRow(row);
// place Buttons in currentTableRow
for (int column = 0; column < 3; column++)
{
// inflate guess_button.xml to create new Button
Button newGuessButton =
(Button) inflater.inflate(R.layout.guess_button, null);
// get country name and set it as newGuessButton's text
String fileName = fileNameList.get((row * 3) + column);
newGuessButton.setText(getCountryName(fileName));
// register answerButtonListener to respond to button clicks
newGuessButton.setOnClickListener(guessButtonListener);
currentTableRow.addView(newGuessButton);
} // end for
} // end for
// randomly replace one Button with the correct answer
int row = random.nextInt(guessRows); // pick random row
int column = random.nextInt(3); // pick random column
TableRow randomTableRow = getTableRow(row); // get the TableRow
String countryName = getCountryName(correctAnswer);
((Button)randomTableRow.getChildAt(column)).setText(countryName);
} // end method loadNextFlag
// returns the specified TableRow
private TableRow getTableRow(int row)
{
return (TableRow) buttonTableLayout.getChildAt(row);
} // end method getTableRow
// parses the country flag file name and returns the country name
private String getCountryName(String name)
{
return name.substring(name.indexOf('-') + 1).replace('_', ' ');
} // end method getCountryName
// called when the user selects an answer
private void submitGuess(Button guessButton)
{
String guess = guessButton.getText().toString();
String answer = getCountryName(correctAnswer);
++totalGuesses; // increment the number of guesses the user has made
// if the guess is correct
if (guess.equals(answer))
{
++correctAnswers; // increment the number of correct answers
// display "Correct!" in green text
answerTextView.setText(answer + "!");
answerTextView.setTextColor(
getResources().getColor(R.color.correct_answer));
disableButtons(); // disable all answer Buttons
// if the user has correctly identified 10 flags
if (correctAnswers == 10)
{
// create a new AlertDialog Builder
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.reset_quiz); // title bar string
// set the AlertDialog's message to display game results
builder.setMessage(String.format("%d %s, %.02f%% %s",
totalGuesses, getResources().getString(R.string.guesses),
(1000 / (double) totalGuesses),
getResources().getString(R.string.correct)));
builder.setCancelable(false);
// add "Reset Quiz" Button
builder.setPositiveButton(R.string.reset_quiz,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
resetQuiz();
} // end method onClick
} // end anonymous inner class
); // end call to setPositiveButton
// create AlertDialog from the Builder
AlertDialog resetDialog = builder.create();
resetDialog.show(); // display the Dialog
} // end if
else // answer is correct but quiz is not over
{
// load the next flag after a 1-second delay
handler.postDelayed(
new Runnable()
{
#Override
public void run()
{
loadNextFlag();
}
}, 1000); // 1000 milliseconds for 1-second delay
} // end else
} // end if
else // guess was incorrect
{
// play the animation
flagImageView.startAnimation(shakeAnimation);
// display "Incorrect!" in red
answerTextView.setText(R.string.incorrect_answer);
answerTextView.setTextColor(
getResources().getColor(R.color.incorrect_answer));
guessButton.setEnabled(false); // disable the incorrect answer
} // end else
} // end method submitGuess
// utility method that disables all answer Buttons
private void disableButtons()
{
for (int row = 0; row < buttonTableLayout.getChildCount(); ++row)
{
TableRow tableRow = (TableRow) buttonTableLayout.getChildAt(row);
for (int i = 0; i < tableRow.getChildCount(); ++i)
tableRow.getChildAt(i).setEnabled(false);
} // end outer for
} // end method disableButtons
// create constants for each menu id
private final int CHOICES_MENU_ID = Menu.FIRST;
private final int REGIONS_MENU_ID = Menu.FIRST + 1;
// called when the user accesses the options menu
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
// add two options to the menu - "Choices" and "Regions"
menu.add(Menu.NONE, CHOICES_MENU_ID, Menu.NONE, R.string.choices);
menu.add(Menu.NONE, REGIONS_MENU_ID, Menu.NONE, R.string.regions);
return true; // display the menu
} // end method onCreateOptionsMenu
// called when the user selects an option from the menu
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// switch the menu id of the user-selected option
switch (item.getItemId())
{
case CHOICES_MENU_ID:
// create a list of the possible numbers of answer choices
final String[] possibleChoices =
getResources().getStringArray(R.array.guessesList);
// create a new AlertDialog Builder and set its title
AlertDialog.Builder choicesBuilder =
new AlertDialog.Builder(this);
choicesBuilder.setTitle(R.string.choices);
// add possibleChoices's items to the Dialog and set the
// behavior when one of the items is clicked
choicesBuilder.setItems(R.array.guessesList,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
// update guessRows to match the user's choice
guessRows = Integer.parseInt(
possibleChoices[item].toString()) / 3;
resetQuiz(); // reset the quiz
} // end method onClick
} // end anonymous inner class
); // end call to setItems
// create an AlertDialog from the Builder
AlertDialog choicesDialog = choicesBuilder.create();
choicesDialog.show(); // show the Dialog
return true;
case REGIONS_MENU_ID:
// get array of world regions
final String[] regionNames =
regionsMap.keySet().toArray(new String[regionsMap.size()]);
// boolean array representing whether each region is enabled
boolean[] regionsEnabled = new boolean[regionsMap.size()];
for (int i = 0; i < regionsEnabled.length; ++i)
regionsEnabled[i] = regionsMap.get(regionNames[i]);
// create an AlertDialog Builder and set the dialog's title
AlertDialog.Builder regionsBuilder =
new AlertDialog.Builder(this);
regionsBuilder.setTitle(R.string.regions);
// replace _ with space in region names for display purposes
String[] displayNames = new String[regionNames.length];
for (int i = 0; i < regionNames.length; ++i)
displayNames[i] = regionNames[i].replace('_', ' ');
// add displayNames to the Dialog and set the behavior
// when one of the items is clicked
regionsBuilder.setMultiChoiceItems(
displayNames, regionsEnabled,
new DialogInterface.OnMultiChoiceClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked)
{
// include or exclude the clicked region
// depending on whether or not it's checked
regionsMap.put(
regionNames[which].toString(), isChecked);
} // end method onClick
} // end anonymous inner class
); // end call to setMultiChoiceItems
// resets quiz when user presses the "Reset Quiz" Button
regionsBuilder.setPositiveButton(R.string.reset_quiz,
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int button)
{
resetQuiz(); // reset the quiz
} // end method onClick
} // end anonymous inner class
); // end call to method setPositiveButton
// create a dialog from the Builder
AlertDialog regionsDialog = regionsBuilder.create();
regionsDialog.show(); // display the Dialog
return true;
} // end switch
return super.onOptionsItemSelected(item);
} // end method onOptionsItemSelected
// called when a guess Button is touched
private OnClickListener guessButtonListener = new OnClickListener()
{
#Override
public void onClick(View v)
{
submitGuess((Button) v); // pass selected Button to submitGuess
} // end method onClick
}; // end answerButtonListener
} // end FlagQuizGame
Create another variable that keeps track of the attempts on the current question. Each time the correct answer is guessed, if number of guesses = 1, increment another counter of how many answers were correctly guessed in one try. Also, after each correct answer, reset the current guesses counter back to 0.

Output not able to show at UI

I'm currently trying to write an app to calculate BMI and calories needed by a person (male / female).
My apps have 2 parts:
1. BMI calculation
2. Calories needed
The first part works well (so I excluded the code for this part), but for the 2nd part, calories needed calculation, it is not able to show up the result as expected (after I click on 'calories needed' button). Probably something is still missing but I cant find it so far.
Everything looks fine in the code, no error.
Can anyone help to have a look on it? :) thanks in advance.
Code as below:
package com.example.caloriescalculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.RadioButton;
public class BMIcalculation extends Activity
{
EditText weightE;
EditText heightE ;
EditText ageE ;
TextView caloriesresult ;
RadioButton male;
RadioButton female;
Button calories;
EditText weightText ;
EditText heightText ;
EditText ageText;
TextView resultText;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.bmilayout_main);
weightE = (EditText)findViewById(R.id.weightText);
heightE = (EditText)findViewById(R.id.heightText);
ageE = (EditText)findViewById(R.id.ageText);
caloriesresult = (TextView)findViewById(R.id.caloriesText);
male = (RadioButton) findViewById(R.id.maleradio);
female = (RadioButton) findViewById(R.id.femaleradio);
Button calories = (Button) findViewById(R.id.caloriesButton);
calories.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
int caloriesneed = 0, weight = 0, height = 0, age = 0;
try {
if ((!weightE.equals("")) && (!heightE.equals("")) && (!ageE.equals("")))
{
weightE = (EditText) findViewById(R.id.weightText);
weight = Integer.parseInt(weightE.getText().toString().trim());
heightE = (EditText) findViewById(R.id.heightText);
height = Integer.parseInt(heightE.getText().toString().trim());
ageE = (EditText) findViewById(R.id.ageText);
age = Integer.parseInt(ageE.getText().toString().trim());
if (male.isSelected())
{
caloriesneed = (int) Math.round (655 + 9.6*weight + 1.8*height - 4.7*age);
caloriesresult.setText(caloriesneed);
}
else if (female.isSelected())
{
caloriesneed = (int) Math.round (66 + 13.7*weight + 5*height - 6.8*age);
caloriesresult.setText(caloriesneed);
}
}
}
catch (Exception k)
{ System.out.println(k);
}
}
});
}
caloriesresult.setText(caloriesneed);
This is problem. In Android if you assign pure int variable to some TextWidget, error will be thrown because Android will interpret it as resouce id of stored String in strings.xml.
So for this reason you need explicit casting. You can achieve it with concentation or an usage of String.valueOf(int value) or Integer.toString(int value) method:
textWidget.setText(Integer.toString(value)); // best approach
textWidget.setText(String.valueOf(value));
textWidget.setText("" + value);
Note: This is absolutely normal behaviour since if you are developing comercial application, usually you want to have support for more languages - and this feature requires localised Strings stored in proper XML file(s).
I guess it's because you try to input an integer to settext() which requires a string for input parameter, so you can try:
caloriesresult.setText("" + caloriesneed);
or
caloriesresult.setText(Integer.toString(caloriesneed));
or
caloriesresult.setText(String.valueOf(caloriesneed));

how do i get the product of the inputted values in two edittext?

I want to get the product of the inputted values in two editTexts.
For example I will input [1,2,3,4,5] in xValues then I will input also [6,7,8,9,10] in freqValues then it will multiply (1*6),(2*7),(3*8),(4*9),(5*10). How will i do that? Please help me. Thank you in advance:)
final AutoCompleteTextView xValues = (AutoCompleteTextView) findViewById(R.id.x_Values);
final AutoCompleteTextView freqValues = (AutoCompleteTextView) findViewById(R.id.frequency_Values);
Button btnCalculate = (Button) findViewById(R.id.btncalculate);
btnCalculate.setOnClickListener(new OnClickListener(){
public void onClick(View arg0)
{
String[]x = ( xValues.getText().toString().split(","));
String []freq = ( freqValues.getText().toString().split(","));
int[]convertedx=new int[x.length];
int[]convertedfreq=new int[freq.length];
}
});
You'll have to do some error catching to make sure only numbers are inputted but once you get that figured out, do something like this:
...
String[]x = ( xValues.getText().toString().split(","));
String []freq = ( freqValues.getText().toString().split(","));
int product = 0;
for(int i = 0; i < x.length(); i++) {
int tempX = Integer.parseInt(x[i]);
int tempFreq = Integer.parseInt(freq[i]);
product += (tempX * tempFreq);
}
Assuming that the arrays are split correctly and only contain integers, this loop will grab the first int from X[] and Freq[] and then multiply them together, and add it to product, then grab the 2nd int from these arrays, parse the string into an int, and then multiply those and loop through until the end of the array.

Android: Array of dynamically generated ImageButtons only returns info from last one created when clicked

I have an activity that generates and displays a GridLayout of custom ImageButtons called MapCells (It's a game map, surprise.) The MapCells are randomly generated and contain some variables that relate to terrain type as well as looking different (the image). What happens when I run my code is that I get my lovely random map, and when I click on the cells they should toast up their id on the screen (a diagnostic aid) as well as getting their stored variables and setText-ing them to some TextViews in the same activity. How it actually works when I click on the MapCells is that they toast the unique id (as expected) and have their unique appearances, but the terrain values that display are of the last MapCell that was generated in all cases. I thought this was the result of my 'for' loop creating all of the MapCells as the variable q (visible in commented out code) which I was just overwriting every loop, so I rewrote it to the code below, however, I am getting the same problem. Other questions I have looked at seemed to indicate that giving them the ids would solve this. Any ideas?
package com.<redacted>
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
public class MapScreen extends Activity implements OnClickListener{
private static int dimen = 110; //the side length of map cells
private int currentFood;
private String currentName;
private MapCell[] storage = new MapCell[18];//keep the cells in here
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_screen); //the xml
//It's Randy the randomizer!
Random randy = new Random();
//Generate 6 random MapCells per row for use in our map.
//MapCell q; -this is old and unused now
for(int i=0; i<=5; i++){
//q = new MapCell(randy.nextInt(4), this); //create and randomize
//q.setId(i); //issue identity
storage[i] = new MapCell(randy.nextInt(4), this); //shove it in the array
storage[i].setId(i);
storage[i].setOnClickListener((OnClickListener) this);
//q.setOnClickListener((OnClickListener) this);
((TableRow)findViewById(R.id.mapRow01)).addView(storage[i], dimen, dimen); //add cell to display
}
for(int j=0; j<=5; j++){
//q = new MapCell(randy.nextInt(4), this);
//q.setId(j+6);
//storage[q.getId()] = q; //shove it in the array
//q.setOnClickListener((OnClickListener) this);
storage[j+6] = new MapCell(randy.nextInt(4), this); //shove it in the array
storage[j+6].setId(j+6);
storage[j+6].setOnClickListener((OnClickListener) this);
((TableRow)findViewById(R.id.mapRow02)).addView(storage[j+6], dimen, dimen); //add cell to display
}
for(int k=0; k<=5; k++){
//q = new MapCell(randy.nextInt(4), this);
//q.setId(k+12);
//storage[q.getId()] = q; //shove it in the array
//q.setOnClickListener((OnClickListener) this);
storage[k+12] = new MapCell(randy.nextInt(4), this); //shove it in the array
storage[k+12].setId(k+12);
storage[k+12].setOnClickListener((OnClickListener) this);
((TableRow)findViewById(R.id.mapRow03)).addView(storage[k+12], dimen, dimen); //add cell to display
}
}
public void displayCell(MapCell view){
//get the cell name view and then set its text to be the name of the clicked cell
try{ //we need to try in case it feeds in a non-MapCell view
currentName = storage[view.getId()].getName();
((TextView)findViewById(R.id.mapDisplayName)).setText(currentName);
currentFood = storage[view.getId()].getFood();
((TextView)findViewById(R.id.mapDisplayFood)).setText(String.valueOf(currentFood));
Toast.makeText(this, "Cell " + String.valueOf(view.getId()), Toast.LENGTH_SHORT).show(); //diagnostic line
}
catch (Exception x){
//frowny time
Toast.makeText(this, "Something Broke on cell " + String.valueOf(view.getId()) + " :(", Toast.LENGTH_SHORT).show();
}
}
public void onClick(View v){//when we click a MapCell
displayCell((MapCell)v);// feed it in
}
}
That's the relevant class. I can show you MapCell if you ask, but it's just an ImageButton with a few added variables along for the ride with getters. These variables are set by switch case using the random integer provided in the constructor.
As I see nothing wrong with your code, I'll take a shot in the dark. In your MapCell class, is the variable that holds terrain values defined using the static modifier?

Categories

Resources