I'm trying to calculate the average based on user input. Now I've got the basics working, but I am only getting whole numbers as result. I want decimal numbers like 5.5
Any explanation is welcome!
final TextView averageView = findViewById(R.id.averageView);
final String averageText = getString(R.string.average);
final Button calculateButton = findViewById(R.id.calculateAverageButton);
calaculateButton.setOnClickListener(new View.onClickListener() {
#SupressLint("SetTextI18n")
public void onClick(View v) {
int grade[] = {Integer.parseInt(((EditText) findViewById(R.id.grade1)).getText().toString());
int weight[] = {Integer.parseInt(((EditText) findViewById(R.id.weight1)).getText().toString());
int weightTotal = weight[0];
int sum = grade[0] * weight[0]
int average = sum / weightTotal
averageView.setText(averageText + Integer.toString(average));
EDIT:
I have experimented with a answer and got a solution for my problem.
final TextView averageView = findViewById(R.id.averageView);
final String averageText = getString(R.string.average);
final Button calculateButton = findViewById(R.id.calculateAverageButton);
calaculateButton.setOnClickListener(new View.onClickListener() {
#SupressLint("SetTextI18n")
public void onClick(View v) {
double grade[] = {Double.parseDouble(((EditText) findViewById(R.id.grade1)).getText().toString());
double weight[] = {Double.parseDouble(((EditText) findViewById(R.id.weight1)).getText().toString());
double weightTotal = weight[0];
double sum = grade[0] * weight[0]
double average = sum / weightTotal
averageView.setText(averageText + " " + Double.toString(average));
Ok You can do it like this
final TextView averageView = findViewById(R.id.averageView);
final String averageText = getString(R.string.average);
final Button calculateButton = findViewById(R.id.calculateAverageButton);
calaculateButton.setOnClickListener(new View.onClickListener() {
#SupressLint("SetTextI18n")
public void onClick(View v) {
int grade = {Integer.parseInt(((EditText)
findViewById(R.id.grade1)).getText().toString());
int weight = {Integer.parseInt(((EditText)
findViewById(R.id.weight1)).getText().toString());
double sum = grade * weight
double average = sum / weight
averageView.setText(averageText +" "+ average);
The division operator / means integer division if there is an integer
on both sides of it. If one or two sides has a floating point number,
then it means floating point division. The result of integer division
is always an integer. Integer division determines how many times one
integer goes into another. The remainder after integer division is
simply dropped, no matter how big it is.
Change the type of variable average to float and typecast one of the sum or weight to float:
float average = (float)sum / weightTotal;
Also change Integer.toString(average) to Float.toString(average)
You are getting integers because you are only using integers !!.
That's normal, If you like average as decimal you have to declare it as Float or Double instead of int.
Note that even if you use such casting (Float.parseFloat....) it wont work because the variable average can only hold integers.
float x = (float) y / z
text.setText("your avarage is : " + x );
also you should use try/catch while get data from edittext for convert Integer. otherwise you can get crash
Related
i deveoped a program to generate random quadratic equations and show their solutions. i took integers from an array containing numbers from -9 to 9, avoiding 0. I chose index by using Random object. but, i get invalid equations a lot , as square of B becomes more than 4AC, the solution is not a real number and i get "NaN" as my solutions. I want to set a condition such as square of B will always be greater than 4AC and the numbers will be taken from the array in such a manner.
my codes are:
import java.util.Random;
class number{
String equation, result;
public void set(){
int[] n = {-9,-8,-7,-6,-5,-4,-3,-2,-1,1,2,3,4,5,6,7,8,9};
Random r = new Random();
int x = r.nextInt(17);
int xx = r.nextInt(17);
int xxx = r.nextInt(17);
int a = n[x];
int b = n[xx];
int c = n[xxx];
double b1 = 0-b; double ac = 4*a*c ; double b2 = b*b; double rt1 = b2-ac;
double rt = Math.sqrt(rt1); double px1 = b1 + rt ; double px2 = b1 - rt;
double a1 = 2*a; double x1 = px1/a1; double x2 = px2/a1;
equation = String.format("The equation is (%d)X^2 + (%d)X + (%d) ",
a,b,c):
result = String.format("Roots are %.3f and %.3f" , x1, x2);
}
public String geteq(){
return equation; }
public String getres(){
return result; }
then in another class I just assigned them in JTextField in actionListener class of JButton.
Is there any way that, upon clicking the buttton, it will automatically repeat the set() method until square of B is greater than 4AC ?
You can try this:
do {
a = n[r.nextInt(17)];
b = n[r.nextInt(17)];
c = n[r.nextInt(17)];
} while (b*b<=4*a*c);
This way, you can only have real solutions
I am trying to convert my two answers text1 and text2 into a decimal format. How is this possible?
int number1, number2, answer, answer2;
EditText edit1 = (EditText)findViewById(R.id.aNum);
EditText edit2 = (EditText)findViewById(R.id.bNum);
TextView text1 = (TextView)findViewById(R.id.answerNum);
TextView text2 = (TextView)findViewById(R.id.answerNum2);
number1 = Integer.parseInt(edit1.getText().toString());
number2 = Integer.parseInt(edit2.getText().toString());
answer = (number2 / (number1 * 1000)) * 60;
answer2 = answer/60;
text1.setText(Integer.toString(answer));
text2.setText(Integer.toString(answer2));
The first issue is the ints are whole numbers, i.e. no decimal places so if you had:
int a = 3;
int b = 2;
int result = a / b;
The result would be 1 not 1.5. If you need to preserve the floating point values cast them to doubles or floats instead. Then you can then use String.format to display the value correctly:
text1.setText(String.format("%.2f",answer));
Which will display the answer to two decimal places.
You can use BigDecimal:
i.e.:
new BigDecimal(theInputString);
Use float variable type instead of int, and Float class instead of Integer class:
float number1, number2, answer, answer2
EditText edit1 = (EditText)findViewById(R.id.aNum);
EditText edit2 = (EditText)findViewById(R.id.bNum);
TextView text1 = (TextView)findViewById(R.id.answerNum);
TextView text2 = (TextView)findViewById(R.id.answerNum2);
number1 = Float.parseFloat(edit1.getText().toString());
number2 = Float.parseFloat(edit1.getText().toString());
answer = (number2 / (number1 * 1000)) * 60;
answer2 = answer / 60;
text1.setText(Float.toString(answer));
text2.setText(Float.toString(answer2));
Within my Activity I am attempting to divide two values then multiply them by 100 in order to give a percentage score.
My issue is that the percentage score is always zero, even though this is impossible with the values I am using.
What am I doing wrong?
Declaring the 2 variables at start of activity:
int score = 0;
int totalQuestions=0;
Onclick logic showing how they are calculated:
public void onClick(View v) {
if (checkForMatch((Button) v)) {
//increment no of questions answered (for % score)
totalQuestions++;
//increment score by 1
score++;
} else {
//increment no of questions answered (for % score)
totalQuestions++;
}
}
public void writeToDatabase() {
// create instance of databasehelper class
DatabaseHelper db = new DatabaseHelper(this);
int divide = (score/ totalQuestions );
int percentageScore = (divide * 100);
Log.d("Pertrace", "per score "+ percentageScore);
Log.d("divide", "divide "+ divide);
// Adding the new Session to the database
db.addScore(new Session(sessionID, "Stroop", SignInActivity
.getUserName(), averageMedLevel, medMax, averageAttLevel,
attMax, percentageScore, myDate, "false", fileNameRaw, fileNameEEGPower, fileNameMeditation, fileNameAttention));
// single score, used for passing to next activity
single = db.getScore(sessionID);
}
Note: from my Trace logs i can see that is it the int divide that is zero, why would this be the case considering that score and totalQuestions are always greater than zero? E.g. 20 and 25.
The reason is this line
int divide = (score/ totalQuestions);
You are dividing the numbers and storing in an int.
You need to store in a double
double divide = (double)score / totalQuestions;
If you want the result as int
double divide = (double)score / totalQuestions;
int percentageScore = (int) Math.ceil(divide * 100);
You are saving them in int. Save values in float or double.
Also, when division occurs, the intermediate result is saved in one of the variable that is used in division. If that is an int, it will be truncated before being saved in double. So do something like double divide = (double)score * totalQuestions
You are performing integer division. First cast score to a double (so you get floating point math), then I would use Math.round() to round the result of the multiplication. For example,
int score = 3;
int totalQuestions = 4;
double divide = ((double) score / totalQuestions);
int percentageScore = (int) Math.round(divide * 100);
System.out.println(percentageScore);
Output is the expected
75
The operands need to be float or double, and so does the variable you put it in:
double divide = (double) score/ totalQuestions;
I would like to display the proportion of an initial value in a JProgressBar.
private void updateProgressBars() { //Update the progress bars to the new values.
int p1 = 0, p2 = 1; //Player numbers
double p1Progress = (intPlayer1Tickets/intInitialPlayer1Tickets) * 100;
double p2Progress = (intPlayer2Tickets/intInitialPlayer2Tickets) * 100;
progressbarPlayerTickets[p1].setValue((int) p1Progress);
progressbarPlayerTickets[p1].setString("Tickets left: " + Integer.toString(intPlayer1Tickets));
progressbarPlayerTickets[p2].setValue((int) p2Progress);
progressbarPlayerTickets[p2].setString("Tickets left: " + Integer.toString(intPlayer2Tickets));
}
In this code, the intention was to calculate the percentage of the amount of tickets left a player has. intInitialPlayer1Tickets and intInitialPlayer2Tickets were both set to 50. intPlayer1Tickets and intPlayer2Tickets were then set to their respective initial tickets value (i.e. both set to 50 as well). When I subtract any number from intPlayer1Tickets or intPlayer2Tickets (e.g. intPlayer1Tickets = 49, intInitialPlayer1Tickets = 50), their respective progress bars' value would be set to 0, which is not my intention. Both progress bars have their min and max values set to 0 and 100.
So how would I make it so it would reflect the proportion of tickets left as a percentage?
You are doing integer math and then converting it to a double. In integer math when you divide a number with a number that is bigger, the answer is always 0.
You want to get Java to do your math with floating point numbers rather than with integers. The easiest way to do this is to make your divisor a double.
When you run this code
public class Numbers{
public static void main(String []args){
int five = 5;
int ten = 10;
System.out.println(five/ten);
System.out.println(five/(double)ten);
System.out.println((five/(double)ten)*100);
}
}
You get this as the output
0
0.5
50.0
So, to answer your question what you want is something like this
double p1Progress = (intPlayer1Tickets/(double)intInitialPlayer1Tickets) * 100;
But you'd be just fine using float for this instead of doubles.
Cast the value of intPlayer1Tickets, intPlayer2Tickets, intInitialPlayer1Tickets and intInitialPlayer2Tickets to double before you calculate. As in:
double p1Progress = (((double) intPlayer1Tickets)/((double) intInitialPlayer1Tickets)) * 100;
double p2Progress = (((double) intPlayer2Tickets)/((double) intInitialPlayer2Tickets)) * 100;
I created an app that generate random number between 2 given values and and its working good it dose what it say but if i entered 11 digit number in the max value (or min value) the app crashes how can I fix it is there another way to generate random number to support big values here is the code
Button gen = (Button)findViewById(R.id.button);
final EditText mini = (EditText)findViewById(R.id.mini);
final EditText maxi = (EditText)findViewById(R.id.maxi);
final TextView res = (TextView)findViewById(R.id.result);
final Random r = new Random();
final int[] number = {0};
gen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int minn = Integer.parseInt(mini.getText().toString());
int maxx = Integer.parseInt(maxi.getText().toString());
if (minn>=maxx){
maxi.setText(String.valueOf(minn));
mini.setText(String.valueOf(maxx));
maxx = Integer.parseInt(maxi.getText().toString());
minn = Integer.parseInt(mini.getText().toString());
number[0] = minn + r.nextInt(maxx - minn + 1);
res.setText(String.valueOf(number[0]));
}else{
number[0] = minn + r.nextInt(maxx - minn + 1);
res.setText(String.valueOf(number[0]));
}
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
});
}
You have to use long or double instead of Integer. Because Integer doesn't support that much large value.
long minn = Long.parseInt(mini.getText().toString());
long maxx = Long.parseInt(maxi.getText().toString());
or
double minn = Double.parseInt(mini.getText().toString());
double maxx = Double.parseInt(maxi.getText().toString());
This is occuring because the Integer class doesn't support values that large. Try using Longs or Floats. That should work.
The max value of int is 2,147,483,647
use long if you need higher values
Set minn and maxx variables to long.
Integer:
MAX VALUE = 2147483647
MIN VALUE = -2147483648
Long:
MAX VALUE = 9223372036854775807
MIN VALUE = -9223372036854775808
Find out more:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
If you want to operate on really big numbers, use BigInteger instead.Integer can't handle big numbers and that's the reason why it's failing for you.