How can I display back to the user a basic popup with a saying based on a random number generated. I wanted to use a switch statement, but that just displays all the sayings, ie:
int random = (int) Math.ceil(Math.random() * 5);
switch(random){
case 1:
showToast(this, "Saying 1.");
case 2:
showToast(this, "Saying 2.");
}
etc....
Like I said, this displays all 5 case statements, is there a better way to random generate and display based on the number, or am I doing it all wrong?
Thanks!
The case statements inside a switch "fall through" if you don't break out of them.
It should be like this:
switch(random) {
case 1:
statement;
break;
case 2:
statement;
break;
...
}
The break statement jumps to the next line after the switch statement.
You can also try some thing like
String[] sayings = {"Saying 1.", "Saying 2.", "Saying 3.", "Saying 4.", "Saying 5."};
int random = (int) Math.ceil(Math.random() * 5);
showToast(this, sayings[random]);
and if you have more items then you can prepare the string array dynamically before use.
If there are many sayings... you can also put a .txt file in your assets folder with numerous sayings (one per line), read it and display the saying from a randomly generated line number..
Activity.getAssets().open("sayingsfile.txt");
Related
I want to convert a few strings into numeric values using parse. Can I put all strings being tested in the try and then output an error depending on where the error occurred?
try{
intOne = Integer.parseInt(editTextOne.getText()...
intTwo = Double.parseDouble(editTextTwo.getText()...
intThree= Double.parseDouble(editTextThree.getText()...
}catch(NumberFormatException e){
//if intOne threw an error display this text
//if intTwo threw an error display this different text
//if intThree threw an error display some more different text
}
I've looked around and all I really found was that I can test multiple lines and output an error with a toast in the catch, but I want the error to be specific to where the error occurred. End state is 'user enters letters in a numeric field, toast says specifically which edittext the invalid data occurred in.'
I know I could accomplish this with multiple try/catch, one for each line. I'm just trying to be more efficient/compact. Thanks.
You can define an int variable before the try block and assign it a different value before each line inside the try block and then check its final value in the catch block to determine where the exception was exactly occurred (see the following code)
int state = 1;
try{
intOne = Integer.parseInt(editTextOne.getText()...
state = 2;
intTwo = Double.parseDouble(editTextTwo.getText()...
state = 3;
intThree= Double.parseDouble(editTextThree.getText()...
}
catch(NumberFormatException e){
switch(state){
case 1: //if intOne threw an error display this text
break;
case 2: //if intTwo threw an error display this different text
break;
case 3: //if intThree threw an error display some more different text
break;
}
}
When I'm comparing an EditText's value with a String var in java, it is going to else part.
case 2 is not executing, every time default case is executing
sem=(EditText)findViewById(R.id.csem);
sem1=sem.getText().toString();
switch (sem1) {
case "2":
c = 1;
i.putExtra("fees", c);
startActivity(i);
break;
default:
Toast.makeText(details.this, "Enter valid current sem", Toast.LENGTH_SHORT).show();
break;
Since it is a String, you should compare it using equals method
// Gets the value of the EditText
String value = ((EditText) findViewById(R.id.csem)).getText().toString();
if(value.equals("2")) {
// Do your things
}
switch statement on String objects is a new feature introduced in Java 1.7. Unfortunatelly Android requires version 1.6 or 1.5. This is why you have to forget for some time about such constructions.
You can avoid using if-statements-chain by storing the map of methods which will be executed for certain String: Map. You can always encapsulate Method it with some Handler object. Look here for more info: How to remove large if-else-if chain
and
why-cant-i-switch-on-a-string
I've been searching for hours and I can't seem to find my error, in fact it doesn't make any sense at all.
I have a android app which has a class that is responsible for parsing an XML document using the XmlPullParser. The result is a list of school days that holds some information about the day and also a list of lessons for each day. I am able to extract all those information correctly but for some reason I end up having the same list of lessons for every day in the end (the other 'header' information of that element remain correct though).
Complete method can be found here(too long to paste it here): http://pastebin.com/AwxqwxQb
I just post the outline here:
List<SubstitutionDay> parseReturnSubstitution() {
SubstitutionDay currentSubstitutionDay = new SubstitutionDay();
List<SubstitutionDay> results = new ArrayList<>();
Substitution currentSubstitution = new Substitution();
List<Substitution> currentSubstitutionList = new ArrayList<>();
int multipleClasses = 0, multiplePeriods = 0;
String text = "";
try {
// all the XmlPullParser set up
int eventType = xmlPullParser.getEventType();
while (eventType != END_DOCUMENT) {
String tag;
String[] tempStringArray;
tag = xmlPullParser.getName();
switch (eventType) {
case TEXT:
text = xmlPullParser.getText();
break;
case START_TAG:
switch (tag) {
case "kopf":
// reset the school day
currentSubstitutionDay = new SubstitutionDay();
break;
case "haupt":
// empty the list before new elements are added
currentSubstitutionList.clear();
break;
case "aktion":
// reset values for each new substitution
currentSubstitution = new Substitution();
multipleClasses = 0;
multiplePeriods = 0;
break;
}
break;
case END_TAG:
switch (tag) {
// iterate over xml elements that contain header information about the day
// iterate over the individual lessons
case "klasse":
break;
case "stunde":
break;
case "lehrer":
break;
case "raum":
break;
case "info":
break;
case "aktion":
break;
case "haupt":
// add the list of lessons to the day
// the number of lessons is correct here
currentSubstitutionDay.setSubstitutionList(currentSubstitutionList);
// add the whole day to the result set
// number of lessons is still correct
results.add(currentSubstitutionDay);
break;
}
break;
}
eventType = xmlPullParser.next();
}
} // catch statements follow here
// when I check for the size of results.get(i).getSubstitutionList().size() the size is the same for all elements
return results;
}
I'm really helpless right here as this shouldn't happening at all. Does anyone have an explanation for that? Any help is appreciated. If there's further information needed, just let me know!
Edit: The XML that is parsed can be found here: http://vplankl.gymnasium-beetzendorf.de/Vertretungsplan_Klassen.xml
The results I'm expecting are basically the number of rows from each table. However if one row is for let's say two periods (column name: Stunde) (4-5 for example) the result is increased by one because I store each Substitution/Lesson in one element of the list.
The lesson count for the last day is 5 - which is the number that is copied to all the other days.
The problem is that you only create one List<Substitution> object and keep clearing it out. Instead you should create a brand new list for each day.
Additionally, you should make a defensive copy when you add the list to a SubstitutionDay.
An easy way to make an android calculator would be to have 3 separate edit text boxes and have the user in put a number, a function, and then another number like 3 + 3. This would make it easier for the app dev to store the number(s) and function(s) and perform a calculation.
Now... my calculator app has the ability to out put all the input real-time, the down side is that when I retrieve what's in the input box, i retrieve it as string (to make sure i include all the functions input-ed). I know how to retrieve numbers (by using int parse) but how do I retrieve the functions such as + - / * ? (They're the main bit!! :O). Any help would me much appreciated thanks :)
Try to use a switch that analyze and identify the correct operation. Something like this:
(I suppose the content of function EditText in a string named functionSign
...
switch(functionSign)
{
case "+": return op1+op2;
case "-": return op1-op2;
...
EDIT 2:
I suppose that user can put only the functions simbols + - / * and the operations are organized in a method:
public double calculate()
{
String operations= inputEditText.getText().toString();
StringTokenizer st= new StringTokenizer(operations);
//to calculate in input must have at last one operation and two operands
//the first token must be a number (the operation scheme is (number)(function)(numeber)...)
double result=Double.parseDouble(st.nextToken());
while(st.hasMoreTokens())
{
String s=st.nextToken();
if(s.equals("+"))
result += Double.parseDouble(st.nextToken());
else if(s.equals("-"))
result -= Double.parseDouble(st.nextToken());
else if(s.equals("*"))
result *= Double.parseDouble(st.nextToken());
else if(s.equals("/"))
result /= Double.parseDouble(st.nextToken());
else
throw new Exception();
}
return result;
}
This code is a really simple example, you must be sure that the user don't try to calculate something incomplete like:
3 + 3 -
/ 3 * 5
and similar. What the user should be able to do is your decision
You can get the operator as a string and use if statements to determine what to do:
String operator=operatorEditText.getText().toString();
if (operator.equals("+")){
//addition code here
}
else if (operator.equals("-")){
//subtraction code here
}
...
I'm still pretty new to this, but I'm trying to make a calculator for myself to use at work; similar to a resistor calculator.
I am hope to change a textview and imageview according to the last two digits entered into a edittext box. For example, if I were to type in "9,000,011", I would want to display a certain color of image and text that corresponds with "11" and the same color and text for say 1,000,011. Also different for 12, 13, and so on. this way No matter what number I type it only looks at the last two digits. Does anyone know the way to do this or maybe can just point me in the right direction?
here is how I'm
private void calculate() {
number = Double.parseDouble(inputnumber.getText().toString());
ImageView iv = (ImageView) this.findViewById(R.id.pairimage);
if (number == 6000001) {
iv.setImageResource(R.drawable.white);
txtnumber.setText("White");
} else if (number == 6000002) {
iv.setImageResource(R.drawable.red);
txtnumber.setText("Red");
}
//*and so on, all the way up to 99*
}
If you want just the last two, then I would use
String wholeNumber = inputnumber.getText().toString();
int n = Integer.valueOf(wholeNumber.subString(wholeNumber.length()-2, wholeNumber.length()-1);
and then a switch block:
switch(n) {
case 1:
iv.setImageResource(R.drawable.white);
txtnumber.setText("White");
break;
case 2:
iv.setImageResource(R.drawable.red);
txtnumber.setText("Red");
break;
}
etc.
Maybe convert the number to a String and then look at that e.g.
String theNumber = String.valueOf(number);
String lastTwoDigits =
theNumber.substring(theNumber.length() -2, theNumber.length());
Then you can have your if statements to read the lastTwoDigits. Or convert back to int (Integer.valueOf(lastTwoDigits); and use a switch statement. Or put the values 0-99 into a Map and have a Command object or something as the value which gets executed.
Obviously you'll need some validation here on the user input.
You have a couple of options. The easiest one is to use the modulus operator like:
number = number % 100;
switch (number) {
case 1:
// do stuff;
break;
case 2:
// do stuff;
break;
}
For this to work, though, "number" will have to be an integer. It's an integer in your examples, so that may work for you; otherwise you can try some math tricks like:
int number2 = (int)(number * 100) % 100;
Go with the sub-string approach. I've found that some number combinations don't multiply/divide well in java.