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 making a fraction calculator in JAVA that keeps inputting a fraction and then an operator and then the next fraction and so on. I've successfully made this thing work for matrices and integers but can't make a function to input fraction so that I can call that function from the loop every time a new fraction has to be inputted.
This is how its working for now but I want the inputting fraction part to be another function so that the function could be used for various occasions .
System.out.println("Enter Numerator 1");
num1=Integer.parseInt(sc.readLine());
System.out.println("Enter Denominator 1");
den1=Integer.parseInt(sc.readLine());
System.out.println("Enter Numerator 2");
num2=Integer.parseInt(sc.readLine());
System.out.println("Enter Denominator 2");
den2=Integer.parseInt(sc.readLine());
Here is an example of a Fraction class that can prompt user for a new fraction.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Fraction {
private final int nom;
private final int den;
public Fraction(int nom, int den) {
if (den <= 0)
throw new IllegalArgumentException("Invalid denominator: " + den);
this.nom = nom;
this.den = den;
}
public int getNom() {
return this.nom;
}
public int getDen() {
return this.den;
}
#Override
public String toString() {
return (this.den == 1 ? String.valueOf(this.nom) : this.nom + "/" + this.den);
}
public static Fraction prompt(Scanner sc, String message) {
Pattern p = Pattern.compile("\\s*(?:(?:(\\d+)\\s+)?(\\d+)/)?(\\d+)\\s*");
for (;;) {
System.out.print(message + ": ");
String line = sc.nextLine();
Matcher m = p.matcher(line);
if (m.matches()) {
if (m.start(2) == -1)
return new Fraction(Integer.parseInt(m.group(3)), 1); // whole number
int nom = Integer.parseInt(m.group(2));
int den = Integer.parseInt(m.group(3));
if (m.start(1) != -1)
nom += Integer.parseInt(m.group(1)) * den;
return new Fraction(nom, den);
}
System.out.println("** Not a valid fraction. Please enter values like 2/3 or 4 3/7 or 13");
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
for (;;) {
Fraction fraction = Fraction.prompt(sc, "Enter value");
if (fraction.getNom() == 0)
break;
System.out.println("You entered: " + fraction);
}
}
}
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);
}
}
I am currently having an issue with obtaining a value in the superclass from the subclass. In the superclass, if choice == 5, it calls the power method in the subclass. The problem is that it prints out 0.0 when it calls getCurrentValue() from the power method in the subclass even when the field currentValue has a value other than 0. I'm wondering if I messed something up when I extended the superclass. When I'm calling getCurrentValue() from the power method in the subclass, could I be calling a different currentValue field, perhaps one that's value hasn't changed?
Here is the code for my superclass:
import java.util.Scanner;
public class TrippelTylerMemoryCalculator {
//Fields
private double currentValue;
//Methods
public static int displayMenu(){
Scanner input = new Scanner(System.in);
int choice;
System.out.print("\nMenu \n" +
"1. Add \n" +
"2. Subtract \n" +
"3. Multiply \n" +
"4. Divide \n" +
"5. Power \n" +
"6. Logarithm \n" +
"7. Clear \n" +
"8. Quit \n\n" +
"What would you like to do? \n");
choice = input.nextInt();
if(choice<1 || choice>6){
while(choice<1 || choice>6){
System.out.println("You have entered an invalid menu option. \n" +
"What would you like to do? \n");
choice = input.nextInt();
}
return choice;
}
else{
return choice;
}
}
public static double getOperand(String prompt){
Scanner input = new Scanner(System.in);
double operand;
System.out.println(prompt);
operand = input.nextDouble();
return operand;
}
public double getCurrentValue(){
return currentValue;
}
public void add(double operand2){
double operand = operand2;
double answer;
answer = currentValue + operand;
currentValue = answer;
}
public void subtract(double operand2){
double operand = operand2;
double answer;
answer = currentValue - operand;
currentValue = answer;
}
public void multiply(double operand2){
double operand = operand2;
double answer;
answer = currentValue * operand;
currentValue = answer;
}
public void divide(double operand2){
double operand = operand2;
double answer;
if(operand == 0){
currentValue = Double.NaN;
}
else{
answer = currentValue / operand;
currentValue = answer;
}
}
public void clear(){
currentValue = 0;
}
//Main Method
public static void main(String[] args) {
TrippelTylerMemoryCalculator instance = new TrippelTylerMemoryCalculator();
TrippelTylerScientificMemoryCalculator instance2 = new TrippelTylerScientificMemoryCalculator();
//Fields for main method
double operand;
boolean repeat = true;
//Program starts here
while(repeat){
System.out.print("The current value is: " + instance.getCurrentValue() + "\n");
int choice;
choice = displayMenu();
if(choice == 1){
operand = getOperand("What is the second value?");
instance.add(operand);
}
else if(choice == 2){
operand = getOperand("What is the second value?");
instance.subtract(operand);
}
else if(choice == 3){
operand = getOperand("What is the second value?");
instance.multiply(operand);
}
else if(choice == 4){
operand = getOperand("What is the second value?");
instance.divide(operand);
}
else if(choice == 5){
operand = getOperand("What is the second value?");
instance2.power(operand);
}
else if(choice == 6){
}
else if(choice == 7){
instance.clear();
}
else if(choice == 8){
System.out.println("Goodbye!");
System.exit(0);
}
}
}
}
And here is the code for my subclass:
public class TrippelTylerScientificMemoryCalculator extends TrippelTylerMemoryCalculator{
public void power(double operand2){
double operand = operand2;
double answer;
//answer = Math.pow(temp, operand);
System.out.println(getCurrentValue());
}
}
Any input would be greatly appreciated! Thanks everyone!
You've got two instances, referred to by variables instance and instance2. These are the only lines of your code which use instance2:
TrippelTylerScientificMemoryCalculator instance2 = new
TrippelTylerScientificMemoryCalculator();
...
instance2.power(operand);
Where do you expect the value to come from? I suspect you only want one instance, and make that an instance of the subclass. Then all your operations will act on the same object. So just change the instance variable declaration to:
TrippelTylerScientificMemoryCalculator instance = new
TrippelTylerScientificMemoryCalculator();
... remove the instance2 declaration entirely, and use instance when you want to call the power method.
(I'd also strongly advise shorter type names, but that's a different matter.)
Additionally, note that unlike all the rest of your operations, your power method doesn't alter the current value (or do anything useful, in fact), but does take responsibility for printing it. That seems odd to me. You should try to be consistent in what your methods do.
I need to create a program in Java that determines if a number is prime.
The user should enter any number, and the program will determine if it's prime or not, and display "not prime" or "prime." My code now compiles and runs but it always says a number isn't prime even if it is.
import java.util.Scanner;
public class PrimeNumber
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int constant = 0;
int variable = 0;
System.out.println("Enter a Number to test if Prime or Not");
constant = input.nextInt();
variable = constant;
double answer = 0.0;
answer = testPrime(constant, variable);
System.out.println(+answer);
if (answer == 1)
{
System.out.println(+constant + " is a prime number.");
}
else
{
System.out.println(+constant + " is NOT a prime number.");
}
}
public static double testPrime(int number, int divide)
{
double prime = 0.0;
prime = number%divide;
if (prime > 0 && divide != number)
{
return testPrime(number, divide - 1);
}
else
{
return prime;
}
}
}
if (prime > 0 && divide != number)
This will never be true. Because your divide and number are always equal.
See that you have assigned variable=constant and that's what you pass to the method
constant = input.nextInt();
variable = constant;
answer = testPrime(constant, variable);
That said, you need go so complex to find out if a number is prime or not. Check the web for simple algorithms. See http://www.mkyong.com/java/how-to-determine-a-prime-number-in-java/ for example.
Not the answer as the OP wants recursion (homework I guess).
You need to only go till the square root of n to see if it has a divisor (divisor besides self will be < sqrt(n))
boolean isPrime(int n) {
if(n % 2 == 0)return false;
int till = (int)java.lang.Math.pow(n, 0.5); //(int)n / 2;
for(int i= 3;i<till;i+=2) {
if(n % i == 0)
return false;
}
return true;
}
I see you want recursion for this, so I converted tgkprog's answer to a recursive method (although his is definitely more efficient). Additionally, I think you may want to return a prime factor if the input isn't prime? I'm just speculating this judging from the OP's return value of a double instead of a boolean. Mine will return an int though, because returning a double is silly.
int isPrime(int n){ //starter function
if(n<=1) return n; //sanity check for weird inputs
if(n % 2 == 0) return 2; //2 is a prime factor
int start = (int)java.lang.Math.pow(n, 0.5);
return isPrime(n,start-(start%2)); //makes start odd if it wasn't already
}
int isPrime(int n, int testval){ //recursive function
if(testval<=1) return 1; //n is prime, return n since it has no prime factors
if(n % i == 0)
return i; //found a prime factor!
return isPrime(n,i-2);
}
with recursion
import java.util.Scanner;
public class PrimeRecursion
{
static int dbg;
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter non 0 if you want debug :");
dbg = input.nextInt();
long constant = 3;
long variable = 0;
while(true){
System.out.println("Enter a Number to test if Prime or Not (1 to exit)");
constant = input.nextLong();
if(constant < 3){
if(constant == 2){
System.out.println("2 is a special prime");
}
return;
}
if(constant % 2 == 0){
System.out.println(constant + " is NOT a prime number, even number.");
}else{
variable = (long)Math.pow(constant, 0.5);
variable = (variable % 2 == 1) ? variable : variable + 1;//odd number
double answer = 0.0;
answer = testPrime(constant, variable);
System.out.println("End answer : " + answer);
if (answer == 1){
System.out.println(+constant + " is a prime number. answer : " + answer);
}
else{
System.out.println(constant + " is NOT a prime number.answer : " + answer);
}
}
System.out.println();
}
}
static double testPrime(long number, long divide)
{
double prime = 0.0;
prime = (double)number / divide;
if(dbg > 0){
System.out.println("Debug number " + number + " | divide " + divide + " |prime : " + prime + " | Math.abs(prime) " + Math.abs(prime));
}
if (prime == ((long)prime))//whats the best way to do this?
{
//divided evenly
return divide;
}
else{
return testPrime(number, divide - 2);
}
}
}
the recursive function for me goes like-Correct me if i am wrong.Thank you.calling statement >Boolean b=isPrime(number,number-1);
recursive function-
void isPrime(int p,int d);
{
int prime=p%d;
if((p==0&&d>1)||p%2==0)
return true;//that the number is not prime
if(d==1)
return false;
else
return isPrime(p,d-2);//calls the function again
}
Well I am directly giving you all the code instead of writing snippet. Hope you all may like this one as I have tried my best to make it as simple as possible.
The code is :>
import java.util.*;
class Prime_Number
{
static int c=0;
public static void main(String args[])
{
int n,i,sq=0;
Scanner in=new Scanner(System.in);
Prime_Number ob=new Prime_Number();
System.out.print("Enter a no.:>");
n=in.nextInt();
i=n;
sq=(int)(Math.sqrt(n));//square root is been taken since a no. cannot have factors greater than its square root
int k=ob.prime_Chk(n,i,sq);
if(k==1)
{
System.out.println("Prime");
}
else
{
System.out.println("Non-Prime");
}
}
public int prime_Chk(int g,int i,int sq)
{
if(i==sq)
{
return c;
}
else
{
if(g%i==0)
{
c++;
}
i--;
return(prime_Chk(g,i,sq));
}
}
}
Well in the prime() I have taken int i , int sq and int g as arguments.Instead of those if you wish then you can take other variables also.
import java.util.Scanner;
public class HW8R_T03 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.print("Enter number: ");
int n = sc.nextInt();
int simple = prime(n,n-1);
System.out.println(simple==1 ? "prime" : "not prime");
}
static int prime(int x, int y){
int div = 1;
if (y==0 || y==1){
return div;
}
if (x%y==0){
div = y;
} else {
div = prime (x, --y);
}
return div;
}
}