I'm trying to create a basic app in android to get a feel for android studio. I want it to produce a random number between 2 given inputs (high and low) and display that number in a list of the last 5. This is the code I have now, and as it currently works, it's setting 'low' to the high limit, I've racked my mind around this issue for a while and can't come up with an answer.
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
/**
* Create all instance variables
*/
int high, low, r;
ArrayList<Integer> numList = new ArrayList<>(5);
boolean firstNum = true;
Random random = new Random();
/**
* Bind the IDs made in the xml with the objects being used in main
* using butterknife
*/
@BindView(R.id.lowestNum) EditText min;
@BindView(R.id.highestNum) EditText max;
@BindView(R.id.currentRando) TextView rando;
@BindView(R.id.randoList) TextView randoList;
@OnClick (R.id.genBtn)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* Adds a given number to the list of numbers on the screen.
* If the list size gets over 5, it also gets rid of the oldest
* number in the list after adding the new number to it
*
* @param x - number to be added to the list
* @return the completed list after x is added
*/
private ArrayList<Integer> updateList(int x){
if(numList.size() <= 4) {
numList.add(x);
} else {
numList.remove(0);
numList.add(x);
}
return numList;
}
/**
* Takes in a list of numbers and formats them to be easily read
* by the user on the main screen
*
* @param myNums The list of numbers to be formatted
* @return The list in a formatted string to display on screen
*/
private String listHelper(ArrayList<Integer> myNums){
String l = "";
if(firstNum) {
l = "" + myNums.get(0);
firstNum = false;
} else {
for (int i = 0; i < myNums.size(); i++) {
if(i != myNums.size()-1)
l = l + myNums.get(i) + ", ";
else
l = l + myNums.get(i);
}
}
return l;
}
/**
* Generates the random number for the user
* @param view
*/
@OnClick(R.id.genBtn)
public void onClick(View view) {
high = Integer.parseInt(max.getText().toString());
low = Integer.parseInt(min.getText().toString());
r = random.nextInt(high - low + 1) + low;
rando.setText("" + random);
updateList(r);
randoList.setText("" + listHelper(numList));
}
}
Thanks in advance!
Aucun commentaire:
Enregistrer un commentaire