Fraction adding java program not working right - java

Having trouble with this final program for my Java class. We have to only use concepts we have learned so far so I cannot use other classes. Basically just loops and arrays and methods.
So for this program we have to add any five sets of fractions entered and give the GCD and the results in the lowest form. I have to show all data in the first table and then a second table with the original data and the GCD and the results in the lowest form. It has to be tested with this data:
1/4 + 1/2
2/3 + 1/3
7/8 + 1/8
2/9 + 4/27
7/25 + 2/5
Here is the code I have so far. (Be gentle, I'm still new at this)
import java.util.Scanner;
public class HelloWorld{
public static void main(String[] args) throws Exception{
int[] num1Array = new int[5];
int[] num2Array = new int[5];
int[] deno1Array = new int[5];
int[] deno2Array = new int[5];
Scanner input = new Scanner(System.in);
for(int x=0;x<5;x++) { //Get all data from user
System.out.println("Enter data for problem " + (x+1));
System.out.println("Enter numberator for fraction 1");
num1Array[x] = input.nextInt();
System.out.println("Enter denominator for fraction 1");
deno1Array[x] = input.nextInt();
System.out.println("Enter numberator for fraction 2");
num2Array[x] = input.nextInt();
System.out.println("Enter denominator for fraction 2");
deno2Array[x] = input.nextInt();
System.out.println("********************");
}
System.out.println("*****ORIGINIAL DATA ******"); //Output all entered data
System.out.println("First Fraction \t Second Fraction");
for(int y=0;y<5;y++) {
System.out.printf("%1d/%1d \t\t %1d/%1d\n", num1Array[y], deno1Array[y], num2Array[y], deno2Array[y]);
}
System.out.println("*******FRACTIONS SHOWING ADDED RESULTS*********"); //Display results
System.out.println("First Fraction \t Second Fraction GCD Results");
for(int z=0;z<5;z++){
int finalgcd = gcdfinal(num1Array[z], num2Array[z], deno1Array[z], deno2Array[z]);
int addFrac = fracAdd(num1Array[z], num2Array[z], deno1Array[z], deno2Array[z]);
System.out.printf("%1d/%1d \t\t %1d/%1d\t\t %1d \t %1d", num1Array[z], deno1Array[z], num2Array[z], deno2Array[z], finalgcd, addFrac);
System.out.println();
}
}
public static int fracAdd(int num1, int num2, int deno1, int deno2)
{
int e = lcm(deno1, deno2); //denominator
int f1 = e / deno1;
int f2 = e / deno2;
int g1 = num1 * f1;
int g2 = num2 * f2;
int adding = g1 + g2;
int k = gcd(adding, e);
int final_num = adding / k;
int final_deno = e / k;
if(final_num == final_deno){
return 1;
}
else {
return (final_num, final_deno);
}
}
public static int gcd(int a, int b) //Calculate GCD
{
while (b > 0)
{
int temp = b;
b = a % b;
a = temp;
}
return a;
}
public static int gcdfinal(int num1, int num2, int deno1, int deno2)
{
int e = lcm(deno1, deno2); //Calculate the GCD for display
int f1 = e / deno1;
int f2 = e / deno2;
int g1 = num1 * f1;
int g2 = num2 * f2;
int end = g1 + g2;
int k = gcd(end, e);
return k;
}
public static int lcm(int a, int b) //Calculate LCM
{
return a * (b / gcd(a, b));
}
}
How can I approach doing this? Am I on the right track?

Try with this, hopefully it helps you. :)
import java.util.Scanner;
public class AddingFraction {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("please enter a fraction number in a/b format: ");
String fraction1 = sc.nextLine();
System.out.println("please enter another fraction number in a/b format: ");
String fraction2 = sc.nextLine();
addFractions(fraction1, fraction2);
}
public static void addFractions(String fractionNum1, String fractionNum2) {
int numResult = 0;
String resultFraction;
String[] frcNum1 = fractionNum1.split("/");
int numerator1 = Integer.parseInt(frcNum1[0]);
int Denomenator1 = Integer.parseInt(frcNum1[1]);
String[] frcNum2 = fractionNum2.split("/");
int numerator2 = Integer.parseInt(frcNum2[0]);
int Denomenator2 = Integer.parseInt(frcNum2[1]);
if (Denomenator1 == Denomenator2) {
numResult = numerator1 + numerator2;
resultFraction = numResult + "/" + Denomenator1;
System.out.println("Resultant Fraction is : "+resultFraction);
} else {
int denLcm = Denomenator1 * (Denomenator2 / gcd(Denomenator1, Denomenator2));;
numResult = numerator1 * (denLcm / Denomenator1) + numerator2
* (denLcm / Denomenator2);
resultFraction = numResult + "/" + denLcm;
System.out.println("Resultant Fraction is : "+resultFraction);
}
}
private static int gcd(int a, int b) {
while (b > 0) {
int temp = b;
b = a % b; // % is remainder
a = temp;
}
return a;
}
}

Related

?: in Java: How to combine res and resString more rationally?

I want output(mix of double res and String resString) is assigned a single variable.
import java.util.Scanner;
public class Lab3Task02_08 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("х = ");
int x = in.nextInt();
System.out.print("y = ");
int y = in.nextInt();
double arithm = (x+y)/2;
double geom = Math.sqrt(Math.abs(x*y));
//////////////////////////////////////////////////////////////
double res = x>y? arithm:geom;
String resString = x>y? "Arithm.average = ":"Geom.average = ";
//////////////////////////////////////////////////////////////
System.out.print(resString + res);
in.close();
}
}
You could do something like this:
String format = "%s.average = %d";
String res = x > y
? String.format(format, "Arithm", arithm)
: String.format(format, "Geom", geom);
— But, really, I question the logic of having two different averages conflated in this way in the first place.
As I understand you want to output two different values depending on the same condition. One of the option, it could be done with String.format(), Double.compare() and x ? y : x.
public static void main(String... args) throws ParseException {
Scanner scan = new Scanner(System.in);
System.out.print("х = ");
int x = scan.nextInt();
System.out.print("y = ");
int y = scan.nextInt();
double arithmetic = (x + y) / 2.;
double geometric = Math.sqrt(Math.abs(x * y));
int res = Double.compare(arithmetic, geometric);
System.out.format(Locale.ENGLISH, "%s average = %.2f\n",
res > 0 ? "Arithmetic" : "Geometric",
res > 0 ? arithmetic : geometric);
}
Output:
х = 3
y = 5
Arithmetic average = 4.00
х = -4
y = 3
Geometric average = 3.46
If i understand the question , is this what you want ?
import java.util.Scanner;
public class Lab3Task02_08 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("х = ");
int x = in.nextInt();
System.out.print("y = ");
int y = in.nextInt();
double arithm = (x+y)/2;
double geom = Math.sqrt(Math.abs(x*y));
//////////////////////////////////////////////////////////////
double res = x>y? arithm:geom;
String resString = x>y? "Arithm.average = ":"Geom.average = ";
//////////////////////////////////////////////////////////////
String combinedRes = resString + res;
System.out.print(combinedRes);
in.close();
}
}

Nothing being stored in array/Method not functioning correctly

Purpose: "Write a payroll class using the following arrays as fields:
employeeID: An array of seven integers to hold employee identification numbers. The array should be
initialized with the following numbers: 568845, 4520125, 7895122, 8777541, 8451277, 1302850,
7580489
hours: An array of seven integers to hold the number of hours worked by each employee.
payRate: An array of seven double to hold each employee's hourly pay rate
wages: An array of seven doubles to hold each employee's gross wages.
The class should relate the data in each array throught he subscipts. The class should have a method
that accepts an employee's identification number as an argument and returns the gross pay for that
employee."
Set/Get Methods with Grosspay Method:
public class Payroll{
private int [] employeeID ={5658845, 4520125, 7895122, 8777541, 8451277, 1302850, 7580489};
private int [] hours = new int [7];
private double [] wages = new double [7];
private double [] payRate = new double [7];
public void setEmployeeID(int a, int emp){
employeeID[a] = emp;
}
public void setHours(int a, int hr){
hours[a] = hr;
}
public void setWages(int a, int wgs){
wages[a] = wgs;
}
public void setPayrate(int a, int prt){
payRate[a] = prt;
}
public int getEmployeeID(int a){
return employeeID[a];
}
public int getHours(int a){
return hours[a];
}
public double getWages(int a){
return wages[a];
}
public double getPayrate(int a){
return payRate[a];
}
public void Grosspay(){
for(int a = 0; a < 7; a++){
wages[a] = hours[a] * payRate[a];
}
}
}
Where everything is executed:
import java.util.Scanner;
public class TestPayroll{
public static void main(String [] args){
Scanner in = new Scanner(System.in);
Payroll pr = new Payroll();
int hr;
double prt;
for (int a = 0; a < 7; a++){
System.out.println("Enter in the hours worked by employee " + pr.getEmployeeID(a));
hr = in.nextInt();
pr.setHours(a,hr);
while(hr < 0){
System.out.println("Enter in a number greater than 0");
hr = in.nextInt();
pr.setHours(a,hr);
}
System.out.println("Enter in the pay rate for employee " + pr.getEmployeeID(a));
prt = in.nextDouble();
while(prt < 6.00){
System.out.println("Enter in a payrate greater than 6.00");
prt = in.nextDouble();
}
}
pr.Grosspay();
for(int a = 0; a < 7; a++){
System.out.println("Employee " + pr.getEmployeeID(a) + " has a gross pay of " + pr.getWages(a));
}
}
I run the program and everything works fine except when it prints out wages. Instead of the wages being the result of hours[a] * payRate[a], it prints out 0.0. I'm thinking that Grosspay method may not be functioning the way I think it should be functioning. Or it could be that I set wages[a] = wgs but wgs is not being used in the code so nothing gets stored in the wages array. So what is wrong with my code that 0.0 is being printed out? Any help is appreciated.
Try this
Payroll.class
private int [] employeeID ={5658845, 4520125, 7895122, 8777541, 8451277, 1302850, 7580489};
private int [] hours = new int [7];
private double [] wages = new double [7];
private double [] payRate = new double [7];
public void setEmployeeID(int a, int emp){
employeeID[a] = emp;
}
public void setHours(int a, int hr){
hours[a] = hr;
}
public void setWages(int a, int wgs){
wages[a] = wgs;
}
public void setPayrate(int a, double prt){
payRate[a] = prt;
}
public int getEmployeeID(int a){
return employeeID[a];
}
public int getHours(int a){
return hours[a];
}
public double getWages(int a){
return wages[a];
}
public double getPayrate(int a){
return payRate[a];
}
public void Grosspay(){
for(int a = 0; a < 7; a++){
wages[a] = hours[a] * payRate[a];
}
}
Main.class
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Payroll pr = new Payroll();
int hr,wgs = 0;
double prt;
for (int a = 0; a < 7; a++){
System.out.println("Enter in the hours worked by employee " + pr.getEmployeeID(a));
hr = 1;
pr.setHours(a,hr);
while(wgs <= 0){
System.out.println("Enter in a number greater than 0");
wgs = 1;
pr.setWages(a,wgs);
}
System.out.println("Enter in the pay rate for employee " + pr.getEmployeeID(a));
prt = 1;
while(prt < 6.00){
System.out.println("Enter in a payrate greater than 6.00");
prt = 7;
pr.setPayrate(a,prt);
}
}
pr.Grosspay();
for(int a = 0; a < 7; a++){
System.out.println("Employee " + pr.getEmployeeID(a) + " has a gross pay of " + pr.getWages(a));
}
}

Factorial of a number display issues

I know how to code to find the factorial of a number:
public static void factorialcalculations()
{
int usernumber, calculation, fact = 1;
System.out.println("Enter an integer to calculate it's factorial");
Scanner in = new Scanner(System.in);
usernumber = in.nextInt();
if ( usernumber < 0 )
System.out.println("Number should be non-negative.");
else
{
for ( calculation = 1 ; calculation <= usernumber ; calculation++ )
fact = fact*calculation;
System.out.println("Factorial of "+usernumber+" is = "+fact);
{
But what I need is for is to display what numbers it is being multiplied by for example if it was 5
I need it to display the factorial is: 5*4*3*2*1=120
Use recursion. The value you want to display for n=1 is "1=". For any other n, it's "n*" + display(n-1).
display(2) => "2*" + display(1) => "2*1="
display(3) => "3*" + display(2) => "3*2*1="
and so on.
There is lot of ways to do it. With your existing code you can print it within your existing loop. Recursive will be the elegant way to find the factorial.
public static int factorial(int n) {
System.out.print("factorial is : ");
int result = 1;
for (int i = n; i >= 1; i--) {
result = result * i;
System.out.print(i!=1 ? (i+"*"): (i+"="));
}
System.out.println(result);
return result;
}
PS: As a best practice you need to handle the all scenarios in here. (String/negative/.. inputs)
Here is what you seem to be looking for man:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number whose factorial is to be found: ");
int n = scanner.nextInt();
int result = factorial(n);
System.out.println(getFactString(n,result));
}
public static int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result = result * i;
}
return result;
}
public static String getFactString(int n, int result){
String output= "";
int count = n;
for (int i = count; i > 0; i--) {
if (n==1) {
output = output + n +" = ";
break;
}
output = output + n+" * ";
n--;
}
return output + result;
}
It's also possible to do this will StringBuilder as well. With the getFactorString() method, it doesn't matter what n is, you will get the correct string returned to display.

recursive method multiplying without using operator

import java.util.Scanner;
public class LAB1201 {
static int multi(int a, int b){
int c = 0;
if (b == 0) {
c = 0;
}
if (b < 0) {
c = (-multi(a, -b));
}
if (b > 0) {
c = (a + multi(a, b-1));
}
return c;
}
public static void main(String[]args){
int aa;
int bb;
Scanner scanner = new Scanner(System.in);
System.out.println("Type in a integer");
aa = scanner.nextInt();
System.out.println("Type in another integer");
bb = scanner.nextInt();
multi(aa,bb);
}
}
I am coding
(Write a recursive function that multiplies two numbers x and y using recursion (do not
use the multiplication operator). Your main method should prompt the user for the two
numbers, call your function, and print the result)
It allows me to type in values but I am not sure why it is not returning any values
it returns nothing..
You forgot to output the value.
System.out.println(aa + " x " + bb + " = " + multi(aa,bb));
Output example:
Type in a integer
4
Type in another integer
8
4 x 8 = 32
Your code is fine. You just forgot to print the result returned by method static int multi(int a, int b). You can find working code here
You are missing a printing statement. Here is the code, please have a look.
import java.util.Scanner;
public class so {
static int multi(int a, int b){
int c = 0;
if(b<0){
return c=(-multi(a, -b));
}
if(b>0){
return c=(a+multi(a, b-1));
}
return c;
}
public static void main(String[]args){
int aa;
int bb;
Scanner scanner = new Scanner(System.in);
System.out.println("Type in a integer");
aa = scanner.nextInt();
System.out.println("Type in another integer");
bb = scanner.nextInt();
System.out.println(multi(aa,bb));
}

Fibonnaci sequence java with limit value

I need help with my java-program. This program is supposed to ask for the highest value fibonacci can have, and print out the number of series up to that value, but it doesn't work. Any suggestions?
import java.util.Scanner;
public class Fibonacci {
public static void main (String[] args){
Scanner in = new Scanner(System.in);
System.out.println("The largest number fibonacci can be: ");
int number = in.nextInt();
if (number < 0){
System.out.println("Wrong! Max-value has to be at least 0.");
}
int i;
int f0 = 0;
int f1 = 1;
int fn;
int value=0;
for (i = 0; i<=value; i++){
fn = f0 + f1;
System.out.println("Fibonacci-number " + i + " = " + f0);
f0 = f1;
f1 = fn;
value = number - f0;
}
}
}
If i put in number = 12, the program is supposed to print:
fibonacci-number 0 = 0
...
fibonnaci-number 12 = 144
Just change the loop to compare value of increment-er (i) to 'number ' variable
for (i = 0; i<=number; i++){
//.........
}
Also use double instead of int if you want to print higher number in the series correctly.
There is no use of the 'value' variable.
Also, the phrase 'the highest value fibonacci can have' is misleading.You have mentioned number denotes number of terms in the series in your example.
If you want 'number' to be the highest value in the series, use following approach,
do{
fn = f0 + f1;
System.out.println("Fibonnaci-tall " + i + " = " + f0);
f0 = f1;
f1 = fn;
i++;
}while(f0<=number);
Is this what you are looking for?
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int f0 = 0;
int f1 = 1;
int fn = 0;
System.out.println("The largest number fibonnaci can be: ");
System.out.println("Input your number: ");
int number = in.nextInt();
if (number < 0){
System.out.println("Wrong! Max-value has to be at least 0.");
} else {
System.out.println(f0);
System.out.println(f1);
while (fn < number){
fn = f0 + f1;
f0 = f1;
f1 = fn;
if (fn < number){
System.out.println(fn);
}
}
}
}
enter image description here
Use this program, it will solve your query.
Try this...It works!
public static void main (String[] args){
Scanner in = new Scanner(System.in);
System.out.println("The largest number fibonacci can be: ");
int number = in.nextInt();
if (number < 0){
System.out.println("Wrong! Max-value has to be at least 0.");
}
else{
int i=0;
int f0 = 0;
int f1 = 1;
int fn;
int value=0;
do{
//for (i = 0; i<=value; i++){
fn = f0 + f1;
System.out.println("Fibonacci-number " + i + " = " + f0);
f0 = f1;
f1 = fn;
value = number - f0;
i++;
}while(f0<=number);
}//else
}

Categories

Resources