Adding Fractions (Java) [duplicate] - java

This question already has answers here:
How to convert decimal to fractions?
(10 answers)
Closed 3 years ago.
In this program, the user is asked for 4 integers that represent two fractions.
First ask for the numerator of the first and then the denominator.
Then ask for the numerator and denominator of the second.
The program should add the two fractions and print out
the result.
I can't figure out how to add the fractions together
public class AddFractions extends ConsoleProgram
{
public void run()
{
int nffraction = readInt("What is the numerator of the first fraction?: ");
int dffraction = readInt("What is the denominator of the first fraction?: ");
int nsfraction = readInt("What is the numerator of the second fraction?: ");
int dsfraction = readInt("What is the denominator of the second fraction?: ");
int sum =
System.out.print(nffraction + "/" + dffraction + " + " + nsfraction + "/" + dsfraction + "=" + sum);
}
}
This is the expected output "1/2 + 2/5 = 9/10" but i can't figure out the "= 9/10" part.

To get the sum of two franctions a/b + c/d you need to do (a*d + c*b)/b*d.
So for your example:
int numerator = (nffraction * dsfraction + nsfraction * dffraction)
int denominator = dsfraction * dsfraction
System.out.print(nffraction + "/" + dffraction + " + " +
nsfraction + "/" + dsfraction + "=" + numerator + "/" + denominator);
This wont reduce to the simplest form of the fraction though.

Related

WAP in java to input a three digit number and calculate each digit's frequency

I made a program for the question and it's working fine, but in some cases it's not working like when I enter 656, it's showing like this:
The error
The code is showed below:
public static void main(String[] args) {
Scanner rx = new Scanner(System.in);
int ui,uiy,troll3,troll1;
float uix,uis,uiz,uit;
System.out.println("Enter a valid three digit number to calculate the frequency of the digits in it. \n");
ui = rx.nextInt();
if(ui>99&&ui<=999) {
uis = (float) ui;
//System.out.println(uis+" uis");
uix = uis / 10;
//System.out.println(uix+" uix");
uiy = (int) uix;
//System.out.println(uiy+" uiy");
troll3 = (int) ((uix - uiy) * 10); //1st digit
//System.out.println("3d " + troll3);
uiz = uix / 10;
//System.out.println(uiz+ " uiz");
troll1 = (int) uiz;
//System.out.println("1d " + troll1);
uit = (uiz - troll1) * 10;
//System.out.println(uit+" uit");
int troll2 = (int) uit;
//System.out.println("2d " + troll2);
if (troll1 == troll2 && troll1 == troll3) {
System.out.println("The number " + troll1 + " appears three times.");
} else if (troll1 != troll2 && troll2 != troll3 && troll1 != troll3) {
System.out.println("The number " + troll1 + " appears one time.");
System.out.println("The number " + troll2 + " appears one time.");
System.out.println("The number " + troll3 + " appears one time.");
} else if (troll1 == troll2) {
System.out.println("The number " + troll1 + " appears two times.");
System.out.println("The number " + troll3 + " appears one time.");
} else if (troll1 == troll3) {
System.out.println("The number " + troll3 + " appears two times.");
System.out.println("The number " + troll2 + " appears one time.");
} else if (troll2 == troll3) {
System.out.println("The number " + troll2 + " appears two times.");
System.out.println("The number " + troll1 + " appears one time.");
}
}
else{
System.out.println("The entered number is invalid");
}
}
It mostly gives an error when it consists of digit 5 in the middle. It shows an increment in values and swap in values. Please do help.
Thanks in advance! :-)
Why are you converting to float? float and double attempts to represent an infinite infinity of numbers (there are an infinite amount of integers. Between 2 integers, there are an infinite amount of numbers too: An infinite amount of infinities)... using only 32 bits. This is obviously impossible so instead only a few numbers are representable, and anything else is silently rounded to one of the select few. This means float and double introduce rounding errors.
After any math done to any double or float, == is broken. You can't use those; at best, you can try 'delta equality' (not a == b, but Math.abs(a - b) < 0.00001) but making the claim that your code works for all possible inputs becomes very difficult indeed, it's not going to be very fast, and the code readability isn't great either. So, don't.
Stop using floats, problem solved.
Your 'math' to get the individual digits is a bit circumspect and isn't going to just work if you replace things with int either. What you're missing is the % operator: Module (a.k.a. remainder).
Given, say, 656:
int in = 657;
int digit1 = in % 10;
in = in / 10;
System.out.println(in); // 65
System.out.println(digit1); // 7
int digit2 = in % 10;
in = in / 10;
System.out.println(in); // 6
System.out.println(digit1); // 5
int digit3 = in;

Print statement [duplicate]

This question already has answers here:
How do I concatenate two strings in Java?
(23 answers)
Closed 8 months ago.
New to Java.
Does anyone know how I can print the following output:
The sum of the digits is 3 + 0 + 4 + 5 + 8 = 20
This is my print line:
System.out.print("The sum of the digits is: " + num1 + num2 + num3 + num4 + num5 + sum);
I want to get the + sign to display, but for some reason I get errors.
Any assistance is appreciated.
There is a difference between + and "+". The first is used to combine Strings in this case and the second is a String with the value of a plus sign.
So a simple plus in a String would look like this:
num1 + " + " + num2 + " = " + solution

Using a average to get probability of a single occurance in a range of numbers

So this is a interesting statistic related question.
What I have
Average
Range of possible occurrences
What I'm after
The probability of a single occurrence in my range happening
A example would be a average of 10.3 . range of 1-20. Whats the chance 4 occurs? I need to use 10.3 as a sort of weight because if not each occurrence has a 1/20 chance of happening
Is there a statistical formula for something like this?
Coding
public void ReboundFormula(double TeamRebound, double OTeamRebound, double OffensiveRebound, double DefensiveRebound,
double ShotsTotalAverage, double OShotsTotalAverage, double TeamShotAveragePercent, double OTeamShotAveragePercent,
double PlayerORebound, double PlayerDRebound, double PlayerOPercentRebound, double PlayerDPercentRebound)
{
//Possible rebounds using amount of shots that "miss" which result in a rebound chance. Note fouls, ball going out of bounds
//, or other event that causes a rebound to not occur on a missed shot
predictedPossibleRebounds = (ShotsTotalAverage*(1 -(double) TeamShotAveragePercent/100)) + OShotsTotalAverage*(1 - (double) TeamShotAveragePercent/100);
Temp = (double) TeamRebound/(TeamRebound+OTeamRebound);
Temp2 = (double) OTeamRebound/(TeamRebound+OTeamRebound);
System.out.println("Percent of Team 1 Rebounds: " + Temp + " | Percent of Team 2 Rebound: " + Temp2);
System.out.println();
//Predicted rebounds a team will grab of the amount of rebounds they will likely get
predictedTeamRebound = (double) predictedPossibleRebounds*Temp;
predictedOTeamRebound = (double) predictedPossibleRebounds*Temp2;
System.out.println("Amount of Rebounds to Team: " + predictedTeamRebound + " | Amount of Rebounds to OTeam: " + predictedOTeamRebound);
System.out.println();
//Rebounds predicted to be grabbed by teams
Oratio = ((double) OffensiveRebound/TeamRebound)*predictedTeamRebound;
Dratio = ((double) DefensiveRebound/TeamRebound)*predictedTeamRebound;
System.out.println("Amount of Offensive Rebounds: " + Oratio + " | Amount of Defensive Rebounds: " + Dratio);
System.out.println();
System.out.println("Predicted Rebounds: " + predictedPossibleRebounds + " | Player Offensive Percent: " + PlayerOPercentRebound + " | Player Defensive Percent: " + PlayerDPercentRebound);
//Player data time
Temp = (Oratio*(PlayerOPercentRebound/100)) + (Dratio*(PlayerDPercentRebound/100));
System.out.println();
System.out.println("Player Predicted Rebound Total: " + Temp + " | Player Rebound Total Average: " + (PlayerORebound+PlayerDRebound) );
System.out.println();
System.out.println( " " + (int) Math.round((Temp) - (Temp*0.75)) + " " + (int) Math.round((Temp) - (Temp*0.5)) + " " + (int) Math.round((Temp) - (Temp*0.25)) + " " + (int) Math.round((Temp) - (Temp*0.1)) + " " + (Temp)
+ " " + (int) Math.round((Temp) + (Temp*0.1)) + " " + (int) Math.round((Temp) + (Temp*0.25)) + " " + (int) Math.round((Temp) + (Temp*0.5)) + " " + (int) Math.round((Temp) + (Temp*0.75)));
System.out.println("-75% -50% -25% -10% Predicted Average +10% +25% +50% +75%");
System.out.println();
Feeding data
run.ReboundFormula(54, 48.2, 13.662, 40.338, 89.86, 87.06, 45.2, 45.7, 3.7, 6.2, 12.9, 22.8);
You would need to specify the distribution of outcomes. Merely to specify the average and range does not suffice. For example, an unbalanced die with a 1/12 chance of reading 1 and a 3/12 chance of reading 5, other outcomes having equal probability, averages 3.83. However, other unbalanced dice are also possible with the same average, for example a die with a 1/12 chance of reading 2 and a 3/12 chance of reading 6.
I suspect that what you want is a binomial distribution. The binomial distribution results from a finite number of discrete trials (as your program's rebounds), each of which either succeeds or fails, each trial of equal weight.
If you follow the link, you will see many formulas, probably more than you wanted, but a principle underlies the formulas and the principle is what you mainly want to grasp. That won't be so easy, but once you have grasped the principle the chief formulas will naturally follow.

I'm not sure what to do with my code. fraction conversions [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm not sure what to add to //Sample 3, can anyone help me out and tell me what I'm doing wrong? I'm writing to write the final part where else if the improper fraction converts to a whole integer, but i don't know how to write that
package ch2_project;
import java.util.Scanner;
public class Ch2_project {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a numerator: ");
int numerator = input.nextInt();
System.out.print("Enter a denominator: ");
int denominator = input.nextInt();
if (numerator < denominator)
{
System.out.println(numerator + " / " + denominator + " is a proper fraction"); // Sample 2
}
else
{
int mix = numerator / denominator;
int remainder = numerator % denominator;
System.out.println(numerator + " / " + denominator + " is a improper fraction and it's mixed fraction is " + mix + " and " remainder + " / " + denominator);// Sample 1
}
else if ()
{
int whole = numerator / denominator
System.out.println(numerator + " / " + denominator + " is an improper fraction and it can be reduced to " + whole);//Sample 3
}
}
}
You're missing an addition operator before remainder causing the compiler to throw an error about an unexpected symbol. Your concatenation isn't working due to the error here:
System.out.println(numerator + " / " + denominator + " is a improper fraction and it's mixed fraction is " + mix + " and " remainder + " / " + denominator);// Sample 1
^
It should be changed to:
System.out.println(numerator + " / " + denominator + " is a improper fraction and it's mixed fraction is " + mix + " and " + remainder + " / " + denominator);// Sample 1
Notice the added + to remedy the problem, which was a missing symbol causing concatenation to fail.
Working example: Here
Edit
Seeing that you've edited the code, the else and else if statements are backwards. Also, the else if has no condition. To detect if fractions can be simplified to a whole number, do this:
else if(numerator%denominator == 0)
This will evaluate if numerator is divisible by denominator, yielding a whole number.

System.out.println( number1 + "score" + (number1 + number2) + number1 ) result explanation (string vs. numeric addition operator)

public class Test {
public static void main(String[] args) {
int number1 = 4;
int number2 = 5;
System.out.println( number1 + "Score:" + (number1 + number2) + number1 );
}
}
The output of the above is:
4Score: 94
Why is this? If there is no "score" in there, I understand the result from it, but this I don't know why. number1 and Score: outputs individually first, so then why is it effecting the result to be 94?
You have:
public static void main(String[] args) {
int number1 = 4;
int number2 = 5;
System.out.println( number1 + "Score:" + (number1 + number2) + number1);
}
This is outputting exactly what you told it to output, essentially:
"4" + "Score:" + "9" + "4"
The + operator when used with a string will convert the non-String operands to strings and concatenate the strings together. When + is used with all numeric operands, it is an arithmetic + and just adds the values together.
By putting (number1 + number2) in parentheses, you cause that to be evaluated first, and since both operands are integers, it behaves as an arithmetic + thats adds those two numbers together (producing 9). That result is then converted to a string and concatenated to everything else. It's essentially a shortcut for:
int number1 = 4;
int number2 = 5;
System.out.println( Integer.toString(number1) +
"Score:" +
Integer.toString(number1 + number2) +
Integer.toString(number1) );
If you remove "Score:", then all of the operands are integers, and so all of the + operators are arithmetic addition, and it just sums all the numbers -- i.e. a shortcut for:
System.out.println( Integer.toString(number1 + (number1 + number2) + number1) );
If you want more technical details of the + operator as related to strings vs. numbers, see Section 15.18 of the JLS (15.18.1 describes behavior for strings, 15.18.2 describes behavior for numeric types).
As an aside, the + operator is always left-associative no matter what types the operands are (described in 15.18.1). So the result of the following may surprise you:
System.out.println(1 + 2 + "string" + 1 + 2);
Spoiler (mouse over):
3string12
See http://ideone.com/P11aMI for some more working examples.
It's to do with operator precedence and the overloading of the + operator. If both sides are numbers, then the + operator performs addition:
number1 + number2
results in 9, which is evaluated first (as it's in brackets).
Then as the rest of it has the same precedence, it is overloaded to string concatenation, in left to right order. If one or all of the arguments to the operator are not numbers, they will all be implicitly converted into strings. We start off with:
4 + "Score:" + (4 + 5) + 4
As the brackets are evaluated first, we then get this:
4 + "Score:" + 9 + 4
Which becomes
"4Score:" + 9 + 4
Then
"4Score:9" + 4
And your final result will be
"4Score:94"
just as you got.
the subterm number1 + number2 is treated as an integer. So the sum could be calculated: 9. Using it as a string parameter results in an automatic cast to String, therefore the concatenation of strings is used: number1 + "Score:" + "9" + number1
System.out.println( number1 + "Score:" + (number1 + number2) + number1))
This prints out the following values (the one in the bracket results in an arithmetic sum :
4 + "Score:" + (4+5) + 4
which is
4Score:94
System.out.println( number1 + "Score:" + (number1 + number2) + number1));
it will be step by step as
1) System.out.println( 4 + "Score:" + 9 + 4));
2) System.out.println( "4Score:" + 9 + 4));
3) System.out.println( "4Score:9" + 4));
Then it shows output as
"4Score:94"

Categories