Java Fraction Calculator - java

I don't know why my fractions won't reduce. I think it's because I didn't call it but I don't know where to call it. (sorry the spacing is so bad. they never check that at school)
import java.util.*;
public class FracCalc_Egg {
public static String f1;
public static String op;
public static String f2;
public static int w1;
public static int w2;
public static int n1;
public static int n2;
public static int d1;
public static int d2;
public static void main(String[] args) {
System.out.println("Welcome to the Fraction calculator!");
Scanner console = new Scanner(System.in);
System.out.print("Enter an expression (or \"quit\"): ");
//get the first fraction, or quit
f1 = console.next();
//test fraction1 to see if the user types "quit"
if(f1.equalsIgnoreCase("quit")){
System.out.println("Goodbye!");
}
while(!f1.equalsIgnoreCase("quit")){
op = console.next();
f2 = console.next();
processFractions(f1, op, f2);
System.out.print("Enter an expression (or \"quit\"): ");
f1 = console.next();
if(f1.equalsIgnoreCase("quit")){
System.out.println("Goodbye!");
}
}//end while loop
//while loop continues the calc until the user types "quit"
}//end of main
public static void processFractions(String f1, String op, String f2){
//get int variables from fractions
//testing fraction 1 to get int values
if(f1.contains("_")){ //testing for mixed number
w1=Integer.parseInt(f1.substring(0,f1.indexOf("_")));
n1=Integer.parseInt(f1.substring(f1.indexOf("_")+1,f1.indexOf("/")));
d1=Integer.parseInt(f1.substring(f1.indexOf("/")+1));
n1=(w1*d1)+n1; //making mixed number improper
} else if(f1.contains("/")) { //testing for fraction
n1=Integer.parseInt(f1.substring(0,f1.indexOf("/")));
d1=Integer.parseInt(f1.substring(f1.indexOf("/")+1));
} else {//testing for whole number
w1=Integer.parseInt(f1.substring(0));
n1=w1;
d1=1;
}//end if, else if, else method
//testing fraction 2 to get int values
if(f2.contains("_")){ //mixed fraction
w2=Integer.parseInt(f2.substring(0,f2.indexOf("_")));
n2=Integer.parseInt(f2.substring(f2.indexOf("_")+1,f2.indexOf("/")));
d2=Integer.parseInt(f2.substring(f2.indexOf("/")+1));
n2=w2*d2+n2;
} else if(f2.contains("/")) { //fraction
n2=Integer.parseInt(f2.substring(0,f2.indexOf("/")));
d2=Integer.parseInt(f2.substring(f2.indexOf("/")+1));
} else { //whole number
w2=Integer.parseInt(f2.substring(0));
n2=w2;
d2=1;
}//end if, else if, else method
dotheMath(n1, n2, d1, d2, op);
}//end processFraction method
//dotheMath detmerines the operator
public static void dotheMath(int n1, int n2, int d1, int d2, String op) {
if(op.equals("+")){
System.out.println(add(n1, n2, d1, d2));
} else if(op.equals("-")) {
n2=-1*n2;
System.out.println(add(n1, n2, d1, d2));
} else if(op.equals("*")) {
System.out.println(multiply(n1, n2, d1, d2));
} else {
int x = n2;
int y = d2;
d2=x;
n2=y;
System.out.println(multiply(n1, n2, d1, d2));
} //end the if, else if, else statement
}//end dotheMath method
public static String add(int n1, int n2, int d1, int d2) {
int newn = (n1*d2) + (n2*d1);
int newd = d1*d2;
int divisor = reduce(newn,newd);
newn/=divisor;
newd/=divisor;
String answer = newn+"/"+newd;
return answer;
}//end add method
public static String multiply(int n1, int n2, int d1, int d2) {
int newn = n1*n2;
int newd = d1*d2;
int divisor = reduce(newn,newd);
newn/=divisor;
newd/=divisor;
String answer = newn+"/"+newd;
return answer;
}//end multiply method
public static int lcd(int n1,int d1, int n2, int d2){
int dividend=(d1*n2)+(n1*d2);
int divisor = d1*d2;
int rem = dividend % divisor;
while (rem != 0){
dividend = divisor;
divisor = rem;
rem = dividend % divisor;
}
return divisor;
} //end lcd
public static int reduce (int newn, int newd) { //
int newn_abs = Math.abs (newn);
int newd_abs = Math.abs (newd); //
int min_num = Math.min (newn_abs, newd_abs);
int divisor = 1;
for (int i = 1; i <= min_num; i++) {
if (newn%i == 0 && newd%i == 0){
divisor = 1;
}//end if
}//end for
return divisor;
}//end reduce
}//end of class
example-
Welcome to the Fraction calculator!
Enter an expression (or "quit"): 1/4 + 1_1/2
14/8
the expected output is 1_3/4
and I'm stuck right at the reduce method. someone told me in class that I didn't call that method but I don't know what they mean. They told me to call it in the add and multiply method but how/where do you do that?

When you class mates tell you, that you didn't call the reduce method, they mean, that you never use the reduce method.
Your add-method should look somewhat like this:
public static String add(int n1, int n2, int d1, int d2) {
int newn = (n1*d2) + (n2*d1);
int newd = d1*d2;
int divisor = reduce(newn, newd);
newn/=divisor;
newd/=divisor;
int integerComponent=0;
while(newn >= newd) {
integerComponent++;
newn-=newd;
}
String answer ="";
if(integerComponent>0) {
answer += integerComponent +"_";
}
if(newn!=0) {
answer += newn+"/"+newd;
}
return answer;
}
and the multiply method should look like this:
public static String multiply(int n1, int n2, int d1, int d2) {
int newn = n1*n2;
int newd = d1*d2;
int divisor = reduce(newn, newd);
newn/=divisor;
newd/=divisor;
int integerComponent=0;
while(newn >= newd) {
integerComponent++;
newn-=newd;
}
String answer ="";
if(integerComponent>0) {
answer += integerComponent +"_";
}
if(newn!=0) {
answer += newn+"/"+newd;
}
return answer;
}
Remember that you also have to change your reduce method, as it always returns 1 right now!
Edit: Added code to print fraction as mixed fraction.

Before I get to my answer, I just have one request, please, please fix your indentation. By providing newly formatted, easy to code in your question, you're much more likely to get an answer and much more likely to get a high quality answer.
Now, for my answer. This is a school project, you're supposed to learn through it. On that note, I won't give you the full answer but I will try to guide you. So, a couple of things, firstly, your friend is right, and secondly, your reduce function is incorrect. You are generating a function in two places, in your add function and in your multiply function at the line:
String answer = newn+"/"+newd;
What you have to do instead at this step is call your reduce function in
String answer = reduce(newn, newd);
Now, it's up to you to change the reduce function to properly reduce the fraction and handle improper fractions.

Related

My code isn't displaying the required result for kaprekar number

I applied all of my brain but can't figure out what to do for making a program, that finds out whether a number is kaprekar or not by using only 2 functions int countdDigits(int ) and void check(int ) except main(), display the correct result
import java.util.*;
class kaprekar
{
private int countDigit(int a)
{
int count = 0;
while(a>0)
{
a/=10;
++count;
}
return count;
}
private void check(int n)
{
int a = countDigit(n);
int d = (int)Math.pow(10, a);
int sum = (a/d) + (a%d);
if(n==sum)
System.out.println("It is a kaprekar number");
else
System.out.println("It is not a kaprekar number");
}
public static void main()
{
Scanner sc=new Scanner(System.in);
kaprekar ob=new kaprekar();
System.out.println("Enter a number to check");
int num = sc.nextInt();
ob.check(num);
}
}
required result:
Enter a number to check
45
It is a kaprekar number
actual results:
Enter a number to check
45
It is not a kaprekar number
I think your problem is here
int a = countDigit(n);
int d = (int)Math.pow(10, a);
int sum = (a/d) + (a%d);
You divided the number of digits with d. I think you need to divide n with d, not a.
For Kaprekar you have to check if a sum of parts of the square number in question is the same as the number.
e.g. 45 --> 45²=2025 --> 20+25=45
following should do:
import java.util.Scanner;
public class KaprekarCheck {
private static boolean isKaprekar(int n)
{
String square = Long.toString(n*n);
for (int i=1; i< square.length(); i++) {
System.out.println("i="+i+" len="+square.length());
int num1 = Integer.parseInt(square.substring(0, i));
int num2 = Integer.parseInt(square.substring(i, square.length()));
System.out.println("i="+i+" len="+square.length()+" num1="+num1+" num2="+num2);
if (num1+num2==n) {
return true;
}
}
return false;
}
public static void main(String[] args) {
int num = 9;
if(isKaprekar(num))
System.out.println("It is a kaprekar number");
else
System.out.println("It is not a kaprekar number");
}
}

Get int variables within a String method Java

This is homework. Just going to put that out there. I feel it is best to show my code first and explain what I'm attempting to do
import java.util.Scanner;
public class Question1 {
public static void main(String[] args){
int length, odd, even, largest;
int n = getNumber();
length=odd=even=largest=initialize();
String sequence=createSequence(n, largest, odd, even, length);
displaySequence(sequence);
displayStatistics(largest, length, odd, even);
}
private static int getNumber(){
Scanner kb = new Scanner(System.in);
System.out.println("Enter the value of the number: ");
int number = kb.nextInt();
return number;
}
private static int initialize(){
return 0;
}
public static String createSequence(int n, int largest, int odd, int even, int length){
String sequence="";
sequence+=n+" ";
while (n!=1){
n = (n%2==0) ? n/2 : 3*n+1;
System.out.print(", "+n);
sequence+=n+" ";
if(n%2==0){ even++;
}else{ odd++;}
if(n>=largest){ largest = n;
}
length++;
}
return sequence;
}
private static void displaySequence(String sequence){
System.out.println(sequence);
}
public static String displayStatistics(int length, int even, int odd, int largest){
String nil = "";
System.out.println("The largest number in the sequence was "+largest);
System.out.println("The length of the sequence was "+length);
System.out.println("There were "+odd+" odd numbers");
System.out.println("There were "+even+" even numbers");
return nil;
}
}
I need attempting to display the largest number in the sequence, the length of the sequence, how many even numbers there were in the sequence and how many odd numbers there were in the sequence. But since I cannot return an int value in the createSequence method, I cannot get the new values for each statistic. Preventing me from displaying said statistics. How would I access these new variables to be used in the final method?
Note:
Requirements:
Declare variables in main
Initialize variables in Initialize()
createSequence (Create the sequence)
displaySequence (Then display the sequence in a separate method)
finally displayStatistics i.e. length, evens, odds, largest (in its own method), this is the one that's troubling me
Try reimplementing your code off of my basecode
public class Question{
public class NumberStats {
int len;
boolean isOdd;
}
private ArrayList<NumberStats> stats = new ArrayList<>();
public static void main(String[] args){
Question q = new Question();
Scanner kb = new Scanner(System.in);
String number = "";
do {
System.out.println("Enter a series of numbers or q to quit: ");
number = kb.next();
q.stats.add(q.parseNumber(number));
} while (number.equals("q")==false);
q.printSummary();
}
private void printSummary(){
int oddCount = 0;
int evenCount = 0;
int longestNumber = 0;
for (NumberStats s : stats){
if (longestNumber<s.len){
longestNumber = s.len;
}
if (s.isOdd){
oddCount+=1;
} else {
evenCount+=1;
}
}
System.out.println(String.format("Longest number length was : %i, Odd Numbers: %i, Even Numbers: %i",longestNumber,oddCount,evenCount));
}
private NumberStats parseNumber(String number){
NumberStats stats = new NumberStats();
Integer lastNumber = Integer.parseInt(String.valueOf(number.charAt(number.length()));
stats.isOdd = true;
if (lastNumber%2==0){
stats.isOdd = false;
}
stats.len = number.length();
return stats;
}
}
Your teacher may be a bit more impressed if you created a Sequence class. The class attributes would be the stats (which could be accessed via getter methods). The createSequence method would become the constructor. And you could implement a toString method to return a string representation of the contents.

Recursive methods which exclude each other?

I am trying to write a method that calculates the sum of odd integers between 1 and a given positive integer n, without using anything else than if statements (sheesh!). It worked out just fine until I decided to also create a method that would ask recursively for the number until it was positive and use it to get n.
Now my program outputs the correct results until I enter a negative number. It then asks for a postive one until I enter one and it outputs 0, the value I initialised the variable val with.
I'm not sure where the logic error is. Could you please take a look? I'm sure it's something obvious, but I guess I have just reached the end of my wits today. Thanks!
package oddsum;
import java.util.Scanner;
public class Oddsum {
public static int oddSum(int n){
int val=0;
if(n>1){
if(n%2==0){
val=n+oddSum(n-1);
}else{
val=oddSum(n-1);
}
}
return val;
}
public static int request(int n){
Scanner in= new Scanner(System.in);
System.out.println("Give me a positive integer: ");
n=in.nextInt();
if (n<0){
System.out.println("I said positive! ");
request(n);
}
return n;
}
public static void main(String[] args) {
int val=0;
int n=request(val);
System.out.println(oddSum(n));
}
}
You should remove input parameter from your request() method. Because your negative input is carried out through the recursive call.
public class Oddsum {
public static int oddSum(int n) {
int val = 0;
if (n > 1) {
if (n % 2 == 0) {
val = n + oddSum(n - 1);
} else {
val = oddSum(n - 1);
}
}
return val;
}
public static int request() {
Scanner in = new Scanner(System.in);
System.out.println("Give me a positive integer: ");
int n = in.nextInt();
if (n < 0) {
System.out.println("I said positive! ");
return request();
}
return n;
}
public static void main(String[] args) {
int n = request();
System.out.println(oddSum(n));
}
}
Output;

How to get the user input from one class to another

I have the following code:
public static void main (String args[])
{
Scanner reader = new Scanner(System.in);
System.out.println("Enter a Numerator");
int num =reader.nextInt();
System.out.println("Enter a Denominator");
int den =reader.nextInt();
System.out.println("Enter a Numerator and a Denominator");
Rational r = new Rational(num,den);
System.out.println(r.getRational() + " equals " +r.getDecimal());
}
}
class Rational
{
double getNum()
{
return num;
}
double getDen()
{
return den;
}
//getDecimal
double getDecimal()
{
double r = num/den;
return r;
}
String getRational()
{
return getNum()+"/"+getDen();
}
private int getGCF(int n1, int n2)
{
int rem = 0;
int gcf = 0;
do
{
rem = n1 % n2;
if (rem == 0)
gcf = n2;
else
{
n1 = n2;
n2 = rem;
}
}
while (rem != 0);
return gcf;
}
}
The purpose of the code is let the user enter a numerator and denominator. Then the program will divide and give the answer to the equations. What I need help on, is I keep on getting an Error on the line of code reading : Rational r = new Rational(num,den). I don't know why.
You forgot to set a constructor in your Rational-Class. You try to initiate the Object with:
Rational r = new Rational(num,den);
But only have the standard COnstructor Rational(). To achieve that you can call this Constructor you have to add this construcotr:
private int num =0;
private int den =0;
public Rational(int unum, int uden){
this.num = unum;
this.den = uden;
}
Within your Rational-Class you have to use then this.numand this.dento get the the constructor setted objects.

What's wrong with my recursion code to calculate the digital root in Java? How can I fix it?

This is the first time I have tried recursion, so sorry for the stupidity. I am trying to calculate the digital root of a number by Java. I checked that we could calculate it by dividing by 9, but I still want to use recursion. Could you tell me what's wrong with my recursion code in Java? How can I fix it? Could you provide sample code for me?
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int inputnumber = inputnumber(console);
int sumofdigit = sumofdigit(inputnumber);
int digitalroot = digitalroot(inputnumber);
System.out.println("That number is :" + digitalroot);
}
//input console
public static int inputnumber(Scanner console){
System.out.println("Please input: ");
int num = console.nextInt();
return num;}
public static int digitalroot(int inputnumber ) {
if(inputnumber<10){
return inputnumber;
} else {
return digitalroot(sumofdigit(inputnumber));
}
}
// calculate sum of digits
public static int sumofdigit(int inputnumber){
return sumofdigit(inputnumber/10) + inputnumber%10;
}
Your recursion never ends. Try this with the added if statement:
public static int sumofdigit(int inputnumber) {
if (inputnumber<10)
return inputnumber;
return sumofdigit(inputnumber/10) + inputnumber%10;
}
You have a simlar snippet in digitalroot, but you primarily need it in sumofdigit.
I'd say it is slightly easier to just stop recursion once you hit zero (one less magic number, and it's more often the case that you can stop recursion at zero).
public static int sumofdigit(int inputnumber) {
if (inputnumber == 0)
return 0;
return sumofdigit(inputnumber / 10) + inputnumber % 10;
}
Not that it matters much, but it at least tries to handle summing negative numbers (albeit returning a negated sum).
Your sumofdigit method should return a value to end recursion when your inputnumber is smaller that 10
Your problem is here:
public static int sumofdigit(int inputnumber){
return sumofdigit(inputnumber/10) + inputnumber%10;
}
To fix this you should do:
public static int sumofdigit(int inputnumber) {
if (inputnumber<10)
return inputnumber;
return sumofdigit(inputnumber/10) + inputnumber%10;
}
Here is some explanation on the problem and the solution:
As you might know, any recursion can be turned into a while loop. Your problematic recursion can be turned into
public static int sumofdigit(int inputnumber) {
while(true){
inputNumber = (inputNumber / 10) + (inputnumber%10);
}
return inputNumber;
}
As you can see, this method will never return and will loop undefinitively. A quick fix would be to return when inputnumber<10
public static int sumofdigit(int inputnumber) {
while(inputnumber>=10){
inputNumber = (inputNumber / 10) + (inputnumber%10);
}
return inputNumber;
}
Which turned back into recursion gives:
public static int sumofdigit(int inputnumber) {
if (inputnumber<10)
return inputnumber;
return sumofdigit(inputnumber/10) + inputnumber%10;
}
I wouldn't do this recursively either:
public static int sumofdigit(int x) {
int sumofdigit = 0;
while(x != 0) {
sumofdigit += x % 10;
x /= 10;
}
return sumofdigit;
}
public static int digitalRoot(int x) {
while(x > 9) {
x = sumofdigit(x);
}
return x;
}

Categories