Java fraction calculator

二次信任 提交于 2020-01-14 13:34:11

问题


I'm really new to Java programming and I have an assignment due for my AP Computer Programming class, so bear with me. I have to figure out how to multiply two fractions together. I was wondering if there was any way to declare a variable inside a method and use it outside that method (my while loop in the intro method). Thank you, hope that wasn't confusing!

import java.util.Scanner;
import java.util.StringTokenizer;

public class javatest3 {
    static int num1 = 0;
    static int num2 = 0;
    static int denom1 = 0;
    static int denom2 = 0;
    public static void main(String[] args){
    System.out.println("Enter an expression (or \"quit\"): "); //prompts user for input
    intro();

}
public static void intro(){
    Scanner input = new Scanner(System.in); 
    String user= input.nextLine();
    while (!user.equals("quit") & input.hasNextLine()){ //processes code when user input does not equal quit
        StringTokenizer chunks = new StringTokenizer(user, " "); //parses by white space
        String fraction1 = chunks.nextToken(); //first fraction
        String operand = chunks.nextToken(); //operator 
        String fraction2 = chunks.nextToken(); //second fraction
        System.out.println("Fraction 1: " + fraction1); 
        System.out.println("Operation: " + operand); 
        System.out.println("Fraction 2: " + fraction2); 
        System.out.println("Enter an expression (or \"quit\"): "); //prompts user for more input


    while (user.contains("*")){
        parse(fraction1);
        parse(fraction2);
        System.out.println("hi");
        int num = num1 * num2;
        int denom = denom1 * denom2;
        System.out.println(num + "/" + denom);
        user = input.next();

    }

    }
}

public static void parse(String fraction) {
    if (fraction.contains("_")){
        StringTokenizer mixed = new StringTokenizer(fraction, "_");
        int wholeNumber = Integer.parseInt(mixed.nextToken());
        System.out.println(wholeNumber);
        String frac = mixed.nextToken();
        System.out.println(frac);
        StringTokenizer parseFraction = new StringTokenizer(frac, "/"); //parses by forward slash
        int num = Integer.parseInt(parseFraction.nextToken());  
        System.out.println(num);
        int denom = Integer.parseInt(parseFraction.nextToken());
        System.out.println(denom);




    }
    else if (!fraction.contains("_") && fraction.contains("/")){
        StringTokenizer parseFraction = new StringTokenizer(fraction, "/"); //parses by forward slash
        int num = Integer.parseInt(parseFraction.nextToken());  
        System.out.println(num);
        int denom = Integer.parseInt(parseFraction.nextToken());
        System.out.println(denom);



    }else{ 
        StringTokenizer whiteSpace = new StringTokenizer(fraction, " "); 
        int num = Integer.parseInt(whiteSpace.nextToken());  
        System.out.println(num);
}

}}


回答1:


This short answer is "no". Others have already explained why... but here's two possible alternatives. I don't know if you've learned these concepts yet, but the first alternative has to do with passing by reference vs. passing by value, and the second alternative has to do with object-oriented programming.

Alternative #1:

You can declare a variable outside a method, pass it to the method and use it, and then the variable is available outside the method because it was declared outside the method. I think an example will help make this more clear:

void foo () {
    Integer a = 1;
    Integer b = 2;
    bar(a,b);
    System.out.println("a = " + a + ", b = " + b);
}

void bar (Integer a, Integer b) {
    a = 4;
    b = 8;
}

And the result should be a = 4, b = 8. However, it's very important to note that this works because Integer (unlike int) is a class so its objects are passed by reference. If a and b were just ints, then they would be passed by value. That means that bar() would have it's own copy of a and b separate from foo()'s, and modifications to the variables within bar() would not affect foo()'s copies. For example:

void foo () {
    int a = 1;
    int b = 2;
    bar(a,b);
    System.out.println("a = " + a + ", b = " + b);
}

void bar (int a, int b) {
    a = 4;
    b = 8;
}

This would produce the result a = 1, b = 2.

I don't really like this method because it's pretty ugly and easy to make a mistake, but it is possible and will work if done correctly. Plus if you're not doing object-oriented code, your choices may be this or just don't use a function for that part (which is not usually good design). Although this kind of thing is much more common in languages like C and C++. But those languages are more explicit about pass by value or reference, and you have to manipulate pointers manually (whereas Java hides its pointers from the programmer), so it's harder to get confused about when something will be passed by value or reference (though easier to make other kinds of mistakes).

Alternative #2:

This would be my preference, given the choice, but only if you've learned some about object-oriented programming. If you haven't learned that yet, I'd go with another approach (but feel free to read on if you're curious).

I would create a fraction class that has member variables for the numerator and denomonator (and whole number part if you're required to support that - although personally I'd reduce fractions with whole number parts to just numerator and denomonator anyhow, because that's how I do math). Then I'd make a constructor that takes a String parameter, and the body of that constructor would work much like your parse() method. So that would let you do something like this...

String strFractionString = /* initialize the string, e.g., reading from input */
Fraction myFrac = new Fraction(strFractionString); // parses string and assigns num & denom
System.out.println("My Fraction: " + myFrac.numerator + "/" + myFrac.denominator);



回答2:


Nope, the scope of the variable will be limited to the method you created it in. You'll have to declare the variable outside of that method, if you want to use it outside that method.

Here's a helpful resource on variable scope.




回答3:


Assuming that you want the function parse() to return both a numerator and a denominator, there are several ways to accomplish this.

The OO way is to define a class that has two fields, a numerator and a denominator, and have parse() return an instance of this type

class Fraction {
    public int Numerator = 0;
    public int Denominator = 1;
    public Fraction(int numerator, int denominator) {
        Numerator = numerator;
        Denominator = denominator;
    }
    public static Fraction parse(String fractionString) {
        int num, denom;

        // Your parse code (without the int num and int denom declarations) goes here.

        return new Fraction(num, denom);
    }
}

Your calling code would look like this:

    Fraction f1, f2;
    f1= Fraction.parse(fraction1);
    f2= Fraction.parse(fraction2);
    int num = f1.Numerator * f2.Numerator;
    int denom = f1.Denominator * f2.Denominator;



回答4:


Variables declared inside a method are encapsulated as local variables and can't be used outside the method.

If you wanted to use say the String frac do this

public class javatest3 {
    static String frac;

    public static void main(String[] args){

        // now you can use frac here
    }

    public static void parse(String fraction) {
        if (fraction.contains("_")){
            ...
            frac = mixed.nextToken();
        }
    }
}



回答5:


Just declare the variable outside of any methods. Make sure and make the variable static. Then just initialize in the method. That way it can be used in any of the methods inside that class. Here's an example of how you'd do that.

package testPackage;

public class Test {
    public static int waffle = 5;

    public static void main(String[] args) {
        method1();
        method2();
    }

    public static void method1() {
        System.out.println("Heyy Everyone");
        System.out.println("Waffle is " + waffle); // Print waffle before change
        waffle = waffle + 12 - 4; // Change waffle;
        System.out.println("Method 1 set waffle to " + waffle); // Print waffle after change after 
    }                                                           // change in method2

    public static void method2() {
        System.out.println("Waffle is " + waffle); // Print waffle in method2 after method1's change
        waffle = waffle * 3; // Change waffle
        System.out.println("Waffle is now set to " + waffle);// Print waffle/ after change in method2
    }
}



回答6:


Your original code prints and separates the fractions and operands. The assignment we have right now in AP CS requires us to separate the fractions into a numerator, operand, and demoninator. It would look something like this.

StringTokenizer st= new StringTokenizer (input); And then use your find(); method to call each part in




回答7:


Here is my code to multiply the fraction. More simpl, hopefully will answer your question.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;

public class javatest3
{
    static int num1 = 0;
    static int num2 = 0;
    static int denom1 = 0;
    static int denom2 = 0;

    public static void main(String[] args)
    {
        javatest3 javatest3 = new javatest3();
        System.out.println("Enter an expression (or \"quit\"): "); // prompts
                                                                    // user for
                                                                    // input
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String[] array = null;
        try {
            array = in.readLine().trim().split(" ");
            /*
             * I get the array[0] and array[2], it because 2/3 * 3/4
             * 2/3 is array[0], * is array[1] and 3/4 is array[2]
             */
            String[] arrayX = array[0].split("/");
            String[] arrayY = array[2].split("/");
            String result = javatest3.multiplyFaction(
                    Integer.valueOf(arrayX[0]), Integer.valueOf(arrayY[0]),
                    Integer.valueOf(arrayX[1]), Integer.valueOf(arrayY[1]));

            System.out.println("Result: " + result);
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // intro();

    }

    private String multiplyFaction(int x1, int y1, int x2, int y2)
    {
        int mf1 = x1 * y1;
        int mf2 = x2 * y2;

        return String.valueOf(mf1) + "/" + String.valueOf(mf2);
    }

//  public static void intro()
//  {
//      Scanner input = new Scanner(System.in);
//      String user = input.nextLine();
//      while (!user.equals("quit") & input.hasNextLine()) { // processes code
//                                                              // when user
//                                                              // input does
//                                                              // not equal
//                                                              // quit
//          StringTokenizer chunks = new StringTokenizer(user, " "); // parses
//                                                                      // by
//                                                                      // white
//                                                                      // space
//          String fraction1 = chunks.nextToken(); // first fraction
//          String operand = chunks.nextToken(); // operator
//          String fraction2 = chunks.nextToken(); // second fraction
//          System.out.println("Fraction 1: " + fraction1);
//          System.out.println("Operation: " + operand);
//          System.out.println("Fraction 2: " + fraction2);
//          System.out.println("Enter an expression (or \"quit\"): "); // prompts
//                                                                      // user
//                                                                      // for
//                                                                      // more
//                                                                      // input
//
//          while (user.contains("*")) {
//              parse(fraction1);
//              parse(fraction2);
//              System.out.println("hi");
//              int num = num1 * num2;
//              int denom = denom1 * denom2;
//              System.out.println(num + "/" + denom);
//              user = input.next();
//
//          }
//
//      }
//  }

//  public static void parse(String fraction)
//  {
//      if (fraction.contains("_")) {
//          StringTokenizer mixed = new StringTokenizer(fraction, "_");
//          int wholeNumber = Integer.parseInt(mixed.nextToken());
//          System.out.println(wholeNumber);
//          String frac = mixed.nextToken();
//          System.out.println(frac);
//          StringTokenizer parseFraction = new StringTokenizer(frac, "/"); // parses
//                                                                          // by
//                                                                          // forward
//                                                                          // slash
//          int num = Integer.parseInt(parseFraction.nextToken());
//          System.out.println(num);
//          int denom = Integer.parseInt(parseFraction.nextToken());
//          System.out.println(denom);
//
//      }
//      else if (!fraction.contains("_") && fraction.contains("/")) {
//          StringTokenizer parseFraction = new StringTokenizer(fraction, "/"); // parses
//                                                                              // by
//                                                                              // forward
//                                                                              // slash
//          int num = Integer.parseInt(parseFraction.nextToken());
//          System.out.println(num);
//          int denom = Integer.parseInt(parseFraction.nextToken());
//          System.out.println(denom);
//
//      }
//      else {
//          StringTokenizer whiteSpace = new StringTokenizer(fraction, " ");
//          int num = Integer.parseInt(whiteSpace.nextToken());
//          System.out.println(num);
//      }
//  }
}


来源:https://stackoverflow.com/questions/20207131/java-fraction-calculator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!