mercredi 1 novembre 2017

Java - beginner code, adding fractions

I have a school project due next week and I'm trying to crack the way to solve this question. The problem was to develop a program that adds the fractions the user inputs until he types -1.

  • the input will always be in pair and positive numbers.
  • Must only use: int, for,while, if, scanner (so no break or arrays)

the program must also solve the previous question which I already solved:

import java.util.Scanner;

public class 2Fractions{
    public static void main(String[] args) {

        Scanner myScanner=new Scanner(System.in);
        int a = myScanner.nextInt();
        int b = myScanner.nextInt();
        int c = myScanner.nextInt();
        int d = myScanner.nextInt();

        int m = a*d + b*c;
        int n = b*d;

        int r = m%n;
         while (r != 0) {
            m=n;
            n=r; 
            r = m%n;
         }
        m = (a*d + b*c)/n;
        n = (b*d)/n;

        System.out.println(m);
        System.out.println(n);
    }
}

So my questions are this:

  • can I use a while loop until user types -1 using the scanner?
  • Is it alright to use the 'while' to let a user type 'infinite' (I am aware that there is no such this in java) number of number until termination?
  • in the code of the previous question I wrote the common factor for the equation, how do I write a common factor for an unknown number of variables

Aucun commentaire:

Enregistrer un commentaire