Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

loops - Java: Using Scanner to receive data and compare each of them

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!

question from:https://stackoverflow.com/questions/66068252/java-using-scanner-to-receive-data-and-compare-each-of-them

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...