So, the issue is that my program goes fine through the process of collecting the two integers to go into the rational class, but then upon getting to the menu, it just exits after taking the choice. I've no idea why and no one is around to help.
EDIT: After significant fiddling, I've managed to at least get the system to give me some output: that is, that regardless of the number that I put in it is giving me the invalid output. I'm thinking maybe I should go back to the switch/case?
Here's the code:
import java.util.Scanner;
public class RationalDriver
{
private static Scanner in = new Scanner(System.in);
private static char choice;
private static String input;
public static void main(String[] args)
{
printHeading();
Rational first = new Rational();
numberOne(first);
Rational second = new Rational();
numberTwo(second);
menu(first, second);
}
public static void menu(Rational first, Rational second)
{
try{
displayMenu();
getValue(choice);
if(choice == '1')
{
System.out.println("\n" + first + " + " + second + " equals ");
first.add(second);
System.out.println(first);
}
else if(choice == '2')
{
System.out.println("\n" + first + " - " + second + " equals ");
first.subtract(second);
System.out.println(first);
}
else if(choice == '3')
{
System.out.println("\n" + first + " * " + second + " equals ");
first.multiply(second);
System.out.println(first);
}
else if(choice == '4')
{
System.out.println("\n" + first + " / " + second + " equals ");
first.divide(second);
System.out.println(first);
}
else if(choice == '5')
{
System.out.println("\nAre " + first + " and " + second + " equal?");
if(first.equals(second))
{
System.out.println("\nYes!");
}
}
else if(choice == '6')
{
System.out.println("Please enter a new rational number: ");
numberOne(first);
}
else if(choice == '7')
{
System.out.println("Please enter a new rational number: ");
numberTwo(second);
}
else if(choice == '8')
{
System.out.println("You chose to exit.");
System.exit(0);
}
else
{
System.out.println("You did not choose a valid entry.");
}
}
catch (Exception e) { e.printStackTrace(); }
}
private static void printHeading() // printHeading method
{
System.out.println("Oliver, James");
System.out.println("CSC201-02PR");
System.out.println("Dr. Java");
System.out.println("Project 7");
System.out.println("Rational Number");
System.out.println();
}
private static void displayMenu()
{
System.out.println("Enter the corresponding number for the desired action:");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.println("5. Test for Equality");
System.out.println("6. Change 1st Rational Number");
System.out.println("7. Change 2nd Rational Number");
System.out.println("8. Exit");
}
public static char getValue(char choice)
{
System.out.println("\nPlease enter your menu option (1 - 8):");
choice = in.next().charAt(0);
return choice;
}
public static void numberOne(Rational first)
{
int numer = 0;
int denom = 1;
boolean breaker = false;
while(!breaker)
{
System.out.println("Please enter your first numerator:");
input = in.next();
numer = Integer.parseInt(input);
System.out.println("Please enter your first denominator:");
input = in.next();
denom = Integer.parseInt(input);
if(denom == 0)
{
System.out.println("Denominator cannot be undefined.");
denom = in.nextInt();
}
else
breaker = true;
}
first.setNumer(numer);
first.setDenom(denom);
first.normalize();
System.out.println("Your rational number is: " + first + "\n");
}
public static void numberTwo(Rational second)
{
int numer = 0;
int denom = 1;
boolean breaker = false;
while(!breaker)
{
System.out.println("Please enter your second numerator:");
input = in.next();
numer = Integer.parseInt(input);
System.out.println("Please enter your second denominator:");
input = in.next();
denom = Integer.parseInt(input);
if(denom == 0)
{
System.out.println("Denominator cannot be undefined.");
denom = in.nextInt();
}
else
breaker = true;
}
second.setNumer(numer);
second.setDenom(denom);
second.normalize();
System.out.println("\nYour rational number is: " + second + "\n");
}
}
Here's the Rational class that I've made:
public class Rational
{
private int numerator; // instance variable for the numerator
private int denominator; // instance variable for the denominator
public Rational() // Constructor
{
numerator = 0;
denominator = 1;
}
public Rational(int numer, int denom) // Overloaded Constructor
{
numerator = numer;
denominator = denom;
normalize();
}
public void setNumer(int numer) // Setter for the Numerator value
{
numerator = numer;
}
public void setDenom(int denom) // Setter for the Denominator value
{
denominator = denom;
}
public void normalize()
{
if(denominator < 0)
{
denominator = -denominator;
numerator = -numerator;
}
}
public int getNumer() // Numerator Getter
{
return numerator;
}
public int getDenom() // Denominator Getter
{
return denominator;
}
public void add(Rational second) // Addition method
{
int a = this.getNumer();
int b = this.getDenom();
int c = second.getNumer();
int d = second.getDenom();
numerator = ((a * d) + (b * c));
denominator = (b * d);
this.normalize();
}
public void subtract(Rational second) // Subtraction Method
{
int a = this.getNumer();
int b = this.getDenom();
int c = second.getNumer();
int d = second.getDenom();
numerator = ((a * d) - (b * c));
denominator = (b * d);
this.normalize();
}
public void multiply(Rational second) // Multiplication Method
{
int a = this.getNumer();
int b = this.getDenom();
int c = second.getNumer();
int d = second.getDenom();
numerator = (a * c);
denominator = (b * d);
this.normalize();
}
public void divide(Rational second) // Division Method
{
int a = this.getNumer();
int b = this.getDenom();
int c = second.getNumer();
int d = second.getDenom();
numerator = (a * d);
denominator = (b * c);
this.normalize();
}
public boolean equals(Object second) // Equals method
{
if(second == null)
{
return false;
}
if(!(second instanceof Rational))
{
return false;
}
Rational other = (Rational)second;
return this.getNumer() * other.getDenom() == other.getNumer() * this.getDenom();
}
public String toString() // toString method
{
if(numerator == 0)
{
return "Result = 0";
}
if(denominator == 1)
{
return Integer.toString(numerator);
}
return Integer.toString(numerator) + "/" + Integer.toString(denominator);
}
}
Related
I'm writing a Java program to allow the user to input a numerator and a denominator and display them as a fraction e.g. 4/5. This should be in a continuous loop until the user enters a numerator that is 0. The program is to compare each fraction and determine whether they are the same and report the result e.g. 4/5 and 4/5 are equal, 4/5 and 6/9 are not equal.
I can't get the program to run properly and I don't know the reason. The program runs, but the result is wrong i.e. when the fractions are equal, the program prints otherwise. I've tried using an object array but it doesn't work either.
Below are my codes
Fraction class
import java.util.Scanner;
public class Fraction {
private int n, d;
private String sN, sD, sF;
public void readInput(){
Scanner kb = new Scanner(System.in);
System.out.println("Enter the numerator: ");
n = kb.nextInt();
System.out.println("Enter the denominator: ");
d = kb.nextInt();
while (d == 0){
System.out.println("Error. Denominator should not" +
" be 0. Please enter again: ");
d = kb.nextInt();
}
sN = String.valueOf(n);
sD = String.valueOf(d);
sF = (sN + "/" + sD);
}
public void writeOutput(){
if (d < 0){ // Check if d is negative
d = -(d);
n = -(n);
System.out.println("The fraction that you have entered is: " +
n + "/" + d);
System.out.println("");
}
else{
System.out.println("The fraction that you have entered is: " +
n + "/" + d);
System.out.println("");
}
}
public int getN(){
return n;
}
public int getD(){
return d;
}
public boolean isZero(Fraction x){
return n == 0;
}
public boolean isEqual(Fraction x, Fraction y){
return x.sF.equals(y.sF);
}
}
public class main
public class TestFraction{
public static void main(String[] args){
Fraction frac = new Fraction();
Fraction frac2 = new Fraction();
System.out.println("The program is looped around getting the" +
" numerator and denominator of a fraction" +
" and displaying them as a fraction.");
System.out.println("Enter a zero fraction (i.e. numerator = 0)"
+ " to end the program.");
System.out.println("");
frac.readInput(); // User enter 1st fraction
if (!frac.isZero(frac)){ // Check if 1st numerator is zero
frac.writeOutput(); // Print 1st fraction
while (!frac.isZero(frac)){
frac2.readInput(); // User enter 2nd fraction
if (!frac2.isZero(frac2)){ // Check for subsequent numerator
frac2.writeOutput(); // Print 2nd fraction
if (frac2.isEqual(frac, frac2))
System.out.println("These 2 fractions are equal.");
else
System.out.println("These 2 fractions are not equal.");
}
else{
System.out.println("You have eneded the program with a" +
" zero fraction.");
System.exit(0);
}
}
}
else{
System.out.println("You have eneded the program with a" +
" zero fraction.");
System.exit(0);
}
}
}
I've decided to convert the fractions into Strings so as to compare them, I couldn't think of any other ways of comparing. If there is a better way, please share. Would really appreciate the knowledge.
Thanks in advance!
You can override toString() for printing the fraction. Also, override equals() for equality testing (which requires we override hashCode(), too).
public static class Fraction {
protected int n, d;
public void readInput(Scanner kb) {
System.out.println("Enter the numerator: ");
n = kb.nextInt();
System.out.println("Enter the denominator: ");
d = kb.nextInt();
while (d == 0){
System.out.println("Error. Denominator should not" +
" be 0. Please enter again: ");
d = kb.nextInt();
}
}
#Override
public String toString() {
return n + "/" + d;
}
public int getN() {
return n;
}
public int getD() {
return d;
}
public boolean isZero(Fraction x) {
return n == 0;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj.getClass() != this.getClass()) {
return false;
}
final Fraction other = (Fraction)obj;
return other.d == d && other.n == n;
}
#Override
public int hashCode() {
// Very simple hash
return toString().hashCode();
}
}
And in main:
Fraction frac1 = new Fraction();
Fraction frac2 = new Fraction();
// Only create 1 scanner
Scanner kb = new Scanner(System.in);
frac1.readInput(kb);
System.out.println(frac1);
frac2.readInput(kb);
System.out.println(frac2);
// No need for the checks for 0 in the denom since
// Fraction.readInput() guarantees it will not be 0
if (frac1.equals(frac2)) {
System.out.println("The 2 are equal.");
}
else {
System.out.println("The 2 are not equal.");
}
I am trying to compare two different strings, one character at a time. I need to return the correct number of digits until they do not equal each other anymore. However, I can't include the character of '.' in the return statement. How would I go about doing this?
import java.util.Scanner;
import java.math.BigDecimal;
public class PiEstimate {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String a;
String b;
char y;
char c;
char d;
String userInput;
do {
System.out.print("Enter a number of randomly generated points:");
userInput = in.nextLine();
if (!isValid(userInput)) {
System.out.print("\n" + "You entered an invalid integer. Please enter a valid integer greater than 0: ");
userInput = in.nextLine();
BigDecimal estimate = new BigDecimal((Math.PI / 4) * 4);
estimate.toString();
System.out.println("\n" + "Your estimate is: " + calculation(userInput));
System.out.println("\n" + "Accuracy of digits is :" + comparison(estimate.toString(),userInput));
} else {
BigDecimal estimate = new BigDecimal((Math.PI / 4) * 4);
estimate.toString();
System.out.println("\n" + "Your estimate is: " + calculation(userInput));
System.out.println("\n" + "Accuracy of digits is :" + comparison(estimate.toString(),userInput));
}
System.out.println("\n" + "Would you like to play again? Enter 'Y' for yes or 'N' for no: ");
String optionToPlay = in.nextLine();
c = optionToPlay.charAt(0);
d = Character.toUpperCase(c);
if (d == 'n' || d == 'N') {
BigDecimal estimate2= new BigDecimal( (Math.PI / 4) * 4);
System.out.println("\n" + "The best estimate is: " + estimate2);
}
} while (d == 'Y');
} // end psvm
public static boolean isValid(String a) {
boolean isFlag = true;
char holder;
for (int i = 0; i < a.length(); i++) {
holder = a.charAt(i);
if (!Character.isDigit(a.charAt(i))) {
return false;
} if (i == 0 && holder == '-') {
return false;
}
} // end for
return isFlag;
} // end isValid
public static double calculation(String a) { // String a means 'looking for a string
double calc = Double.parseDouble(a);
int i;
double x;
double y;
double c = 0;
double runningCounter = 0;
double totalCounter;
for (i = 0; i < calc; i++) {
x = Math.random();
y = Math.random();
c = Math.sqrt((x * x) + (y * y));
if (c <= 1) {
runningCounter++;
}
} // end for
totalCounter = ((runningCounter / calc) * 4);
calc = totalCounter;
return calc;
}
public static int comparison (String bear, String userInput) {
int i = 0;
String s = calculation(userInput) + "";
int b;
int counter2 = 0;
for (i=0; i < s.length(); i++) {
if (s.charAt(i) != bear.charAt(i)) {
return i;
}
}
return i;
} // end comparison
} // end class
Code from IDE
I would like to run a program that can determine the validation and type of credit card number based of number entered. Compiler shows notification that there is an error in my coding but I cannot detect where is it. The program is also cannot be run. Below is the coding,
import java.util.*;
public class CreditCard {
public static void main(String args[]) {
String CType;(String number) {
if (number.startsWith("4"))
return "Visa";
else if (number.startsWith("5"))
return "MasterCard";
else if (number.startsWith("6"))
return "Discover";
else if (number.startsWith("37"))
return "American Express";
else
return "Unknown type";
};
Scanner input = new Scanner(System.in);
System.out.println("Enter a credit card number: ");
long number = input.nextLong();
long total = sumOfEvenPlaces(number) + (sumOfOddPlaces(number)*2);
if (isValid(total)) {
System.out.println("The "+CType+" card number is valid");
} else {
System.out.println("The "+CType+" card number is invalid.");
}
}
public static boolean isValid(long total) {
if (total % 10 != 0) {
} else {
return true;
}
return false;
}
public static int sumOfEvenPlaces(long number) {
int sum = 0;
int remainder;
while (number % 10 != 0 || number / 10 != 0) {
remainder = (int) (number % 10);
sum = sum + getDigit(remainder * 2);
number /= 100;
}
return sum;
}
public static int getDigit(int number) {
if (number > 9) {
return (number % 10 + number / 10);
}
return number;
}
public static int sumOfOddPlaces(long number) {
int sum = 0;
int remainder;
number /= 10;
while (number % 10 != 0 || number / 10 != 0) {
remainder = (int) (number % 10);
sum = sum + getDigit(remainder * 2);
number /= 100;
}
return sum;
}
}
I do card type detection with an enum:
package com.gabrielbauman.gist;
import java.util.regex.Pattern;
public enum CardType {
UNKNOWN,
VISA("^4[0-9]{12}(?:[0-9]{3}){0,2}$"),
MASTERCARD("^(?:5[1-5]|2(?!2([01]|20)|7(2[1-9]|3))[2-7])\\d{14}$"),
AMERICAN_EXPRESS("^3[47][0-9]{13}$"),
DINERS_CLUB("^3(?:0[0-5]\\d|095|6\\d{0,2}|[89]\\d{2})\\d{12,15}$"),
DISCOVER("^6(?:011|[45][0-9]{2})[0-9]{12}$"),
JCB("^(?:2131|1800|35\\d{3})\\d{11}$"),
CHINA_UNION_PAY("^62[0-9]{14,17}$");
private Pattern pattern;
CardType() {
this.pattern = null;
}
CardType(String pattern) {
this.pattern = Pattern.compile(pattern);
}
public static CardType detect(String cardNumber) {
for (CardType cardType : CardType.values()) {
if (null == cardType.pattern) continue;
if (cardType.pattern.matcher(cardNumber).matches()) return cardType;
}
return UNKNOWN;
}
}
You can then do CardType.detect("cardnumbergoeshere") and you'll get back CardType.VISA, etc.
There's a unit test over at the gist.
For validation, I have:
public boolean isValid(String cardNumber) {
int sum = 0;
boolean alternate = false;
for (int i = cardNumber.length() - 1; i >= 0; i--) {
int n = Integer.parseInt(cardNumber.substring(i, i + 1));
if (alternate) {
n *= 2;
if (n > 9) {
n = (n % 10) + 1;
}
}
sum += n;
alternate = !alternate;
}
return (sum % 10 == 0);
}
That should do it.
Edit: fixed escape characters in DINERS_CLUB
This may be more along the lines of what you're trying to do:
public static void main(final String args[])
{
String cType = null;
System.out.println("Enter a credit card number: ");
final Scanner input = new Scanner(System.in);
final String cardNumber = input.next();
if (cardNumber.startsWith("4"))
{
cType = "Visa";
}
else if (cardNumber.startsWith("5"))
{
cType = "MasterCard";
}
else if (cardNumber.startsWith("6"))
{
cType = "Discover";
}
else if (cardNumber.startsWith("37"))
{
cType = "American Express";
}
else
{
cType = "Unknown type";
}
final long total = sumOfEvenPlaces(Long.valueOf(cardNumber)) + (sumOfOddPlaces(Long.valueOf(cardNumber)) * 2);
if (isValid(total))
{
System.out.println("The " + cType + " card number is valid");
}
else
{
System.out.println("The " + cType + " card number is invalid.");
}
}
On a stylistic note, CType should start with a lower case letter (e.g. cType). You'll have to experiment with the use of Scanner as well as I'm not sure my implementation will do what you're looking for.
This question already has answers here:
How to evaluate a math expression given in string form?
(26 answers)
Closed 9 years ago.
I'm doing a program that presents the student with a math quiz. I am having trouble figuring out how to take the input problem type and turning that string into the arithmetic operator. Here is the method for that part of the code. Please and thanks!
public static String getUserChoice(String choice) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter the symbol that corresponds to one of the following problems\n"
+ "Addition (+)\n Subtraction (-)\n or Multiplication (*): ");
choice = in.next();
if ("+".equals(choice)){
return +;
}
}
return choice;
Update
Here's the entire code if it helps see what I am doing.
public static void main(String[] args) {
int digit = 0;
int random = 0;
String result1 = getUserChoice("");
digit = getNumberofDigit1(digit);
int number1 = getRandomNumber1(digit);
int number2 = getRandomNumber2(digit);
System.out.println(number1 + result1 + number2);
getCorrectAnswer(number1, result1, number2);
}
public static String getUserChoice(String choice) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter the symbol that corresponds to one of the following problems\n"
+ "Addition (+)\n Subtraction (-)\n or Multiplication (*): ");
choice = in.next();
return choice;
}
public static int getNumberofDigit1(int digit) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a 1 for problems with one digit, or a 2 for two-digit problems: ");
digit = in.nextInt();
return digit;
}
public static int getRandomNumber1(int numbers) {
int random = 0;
if (numbers == 1) {
random = (int) (1 + Math.random() * 9);
} else if (numbers == 2) {
random = (int) (10 + Math.random() * 90);
}
return random;
}
public static int getRandomNumber2(int numbers) {
int random2 = 0;
if (numbers == 1) {
random2 = (int) (1 + Math.random() * 9);
} else if (numbers == 2) {
random2 = (int) (10 + Math.random() * 90);
}
return random2;
}
public static void getCorrectAnswer(int number1, String result1, int number2) {
}
public static void getUserAnswer() {
Scanner in = new Scanner(System.in);
}
public static void CheckandDisplayResult() {
}
here is the one approach to your problem:
private static Scanner input;
public static void main(String[] args) {
input = new Scanner(System.in);
final String result1 = getUserChoice();
final int digit = getNumberofDigit1();
final int number1 = getRandomNumber(digit);
final int number2 = getRandomNumber(digit);
System.out.println(number1 + result1 + number2);
final int userAnswer = input.nextInt();
final int correctAnswer = getCorrectAnswer(number1, result1, number2);
System.out.println( (userAnswer == correctAnswer) ? "Ok" : ("Wrong, right is: " + correctAnswer));
input.close();
}
public static String getUserChoice() {
System.out.println("Please enter the symbol that corresponds to one of the following problems\n" + "Addition (+)\n Subtraction (-)\n or Multiplication (*): ");
return input.next();
}
public static int getNumberofDigit1() {
System.out.println("Enter a 1 for problems with one digit, or a 2 for two-digit problems: ");
return input.nextInt();
}
public static int getRandomNumber(final int numbers) {
return (int) ( (numbers == 1) ? (1 + Math.random() * 9) : (10 + Math.random() * 90) );
}
public static int getCorrectAnswer(final int number1, final String result1, final int number2) {
if ("+".equals(result1))
return number1+number2;
else if ("-".equals(result1))
return number1-number2;
else if ("*".equals(result1))
return number1*number2;
return -1;
}
and here is a little bit another getCorrectAnswer part:
public interface IMyOperator {
public int operation(final int a, final int b);
};
static class classSum implements IMyOperator {
public int operation(final int a, final int b) {
return a+b;
}
}
static class classSub implements IMyOperator {
public int operation(final int a, final int b) {
return a-b;
}
}
static class classMul implements IMyOperator {
public int operation(final int a, final int b) {
return a*b;
}
}
final static HashMap<String, IMyOperator> operators = new HashMap<String, IMyOperator>(3) {{
put("+", new classSum());
put("-", new classSub());
put("*", new classMul());
}};
public static int getCorrectAnswer(final int number1, final String result1, final int number2) {
return operators.get(result1).operation(number1, number2);
}
First, I want to show you how to test to see if it is what you want.
You can always check to make sure it is a string, or int, or w/e by doing the following.
Scanner scan = new Scanner(System.in);
while(scan.hasNext()) {
if(scan.hasNextInt()) {
int response = scan.nextInt();
}
}
Here is code for what you want to do.
import java.util.Random;
import java.util.Scanner;
public class Main {
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
// Math Quiz v1.0 //
String printme = "Please choose the quiz type:\n\n"
+ "(1) Addition\n"
+ "(2) Subtraction\n"
+ "(3) Multiplication\n"
+ "(4) Division\n"
+ "(5) Modulus\n\n\n";
System.out.println(printme);
int reponse = in.nextInt();
// Setup //
int a = new Random().nextInt(100);
int b = new Random().nextInt(100);
int answer = -1;
switch(reponse) {
case 1:
System.out.println("What is " + a + " + " + b + "?");
answer = in.nextInt();
if(answer == a + b) {
System.out.println("Your right!");
} else {
System.out.println("You fail!");
}
break;
case 2:
System.out.println("What is " + a + " - " + b + "?");
answer = in.nextInt();
if(answer == a - b) {
System.out.println("Your right!");
} else {
System.out.println("You fail!");
}
break;
case 3:
System.out.println("What is " + a + " * " + b + "?");
answer = in.nextInt();
if(answer == a * b) {
System.out.println("Your right!");
} else {
System.out.println("You fail!");
}
break;
case 4:
System.out.println("What is " + a + " / " + b + "?");
answer = in.nextInt();
if(answer == a / b) {
System.out.println("Your right!");
} else {
System.out.println("You fail!");
}
break;
case 5:
System.out.println("What is " + a + " % " + b + "?");
answer = in.nextInt();
if(answer == a % b) {
System.out.println("Your right!");
} else {
System.out.println("You fail!");
}
break;
default:
System.out.println("Error, enter an integer between 1 & 5.");
break;
}
}
}
So here is my Fraction class. The math works but I want to fraction to be reduced. Note: This is in Eclipse SDK Juno.
public class Fraction {
private int n, d;
public Fraction(int num, int denum){
n = num;
d = denum;
}
public int getNumerator(){
return n;
}
public void setNumerator(int num){
n = num;
}
public int getDenumerator(){
return d;
}
public void setDenumerator(int denum){
d = denum;
}
**public void reduce(){
int gcf = 1, smaller;
if (n < d){
smaller = n;
}
else{
smaller = d;
}
for (int i = 1;i <= smaller; i++){
if(n % i == 0 && d % i ==0){
gcf = i;
}
}
n = n/gcf;
d = d/gcf;
System.out.print(n + "/" + d);
}**
}
In bold is what I what to output in my FractionMath shown below. I don't know how to apply the reduce method in this class. I tried method.Fraction() but that gave me an error...help?
import java.util.*;
public class FractionMath {
public static void main(String[] args){
Fraction f1, f2;
Fraction ans = new Fraction(0,0);
Scanner sc = new Scanner(System.in);
System.out.print("Enter the numerator; then denumerator:\n");
f1 = new Fraction(sc.nextInt(), sc.nextInt());
System.out.print("Enter another numerator; and denumerator:\n");
f2 = new Fraction(sc.nextInt(), sc.nextInt());
System.out.print("Add (1)\nSubtract (2)\nMultiply (3)\nDivide (4)\n");
int choice = sc.nextInt();
if (choice == 1){
if (f1.getDenumerator() == f2.getDenumerator()){
ans.setNumerator(f1.getNumerator() + f2.getNumerator());
ans.setDenumerator(f1.getDenumerator());
}
else{
ans.setNumerator(f1.getNumerator() * f2.getDenumerator() + f2.getNumerator() * f1.getDenumerator());
ans.setDenumerator(f1.getDenumerator() * f2.getDenumerator());
}
}
else if (choice == 2){
if (f1.getDenumerator() == f2.getDenumerator()){
ans.setNumerator(f1.getNumerator() - f2.getNumerator());
ans.setDenumerator(f1.getDenumerator());
}
else{
ans.setNumerator(f1.getNumerator() * f2.getDenumerator() - f2.getNumerator() * f1.getDenumerator());
ans.setDenumerator(f1.getDenumerator() * f2.getDenumerator());
}
}
else if (choice == 3){
ans.setNumerator(f1.getNumerator() * f2.getNumerator());
ans.setDenumerator(f1.getDenumerator() * f2.getDenumerator());
}
else if (choice == 4){
ans.setNumerator(f1.getNumerator() * f2.getDenumerator());
ans.setDenumerator(f1.getDenumerator() * f2.getNumerator());
}
}
}
There are a lot of solutions on the web for this. Maybe try this one