Rationals cannot be resolved? - java

Running Eclipse, I am working on program to do fraction addition for class, so it will probably look very unprofessional, but here goes. Basically my rational names cannot be resolved, and I'm not certain why. Does it have something to do with the scope? I've commented where the error occurs.
package lab11tests;
import java.util.Scanner;
public class Tests {
private static int num1 = 0;
private static int den1 = 1;
private static int num2 = 0;
private static int den2 = 1;
static Rational r1 = new Rational(num1,den1);
static Rational r2 = new Rational(num2,den2);
static Rational r3 = new Rational();
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Numerator 1: ");
num1=input.nextInt();
System.out.print("Denominator 1: ");
den1=input.nextInt();
System.out.print("Numerator 2: ");
num2 = input.nextInt();
System.out.print("Denominator 2: ");
den2 = input.nextInt();
System.out.println(r1.rational() + " + " + r2.rational() + " equals "+ r3.answer());
}
}
class Rational {
// private int firstNum;
// private int firstDen;
private int num;
private int den;
public Rational(int n, int d){
num = n;
den = d;
}
public Rational(){}
public int getNum(){
return num;
}
public int getDen(){
return den;
}
public void add(){
int commonDen = r1.getDen() * r2.getDen();`enter code here`
this.num=(r1.getNum()*r2.getDen())+(r2.getNum()*r1.getDen()); //Errors are here, all r2 and r1's in the add method "cannot be resolved"
this.den=commonDen;
}
public String rational(){
return num + "/" + den;
}
public String answer(){
return this.num + "/" + this.den;
}
}

The code that is bugging up is inside of class Rational. Attempting to use static variables r1 and r2 will result in an error because there is no r1 and r2 inside of class Rational. Instead, you need to access class Tests to use the static variables.
This is your current code.
int commonDen = r1.getDen() * r2.getDen();
this.num=(r1.getNum()*r2.getDen())+(r2.getNum()*r1.getDen()); //Errors are here, all r2 and r1's in the add method "cannot be resolved"
Instead, your code should look like this.
int commonDen = Tests.r1.getDen() * Tests.r2.getDen();
this.num = (Tests.r1.getNum() * Tests.r2.getDen()) + (Tests.r2.getNum() * Tests.r1.getDen());

Rational is a separate class here the Tests class brackets have been ended before the line of defining Rational class

Related

How to get the user input from one class to another

I have the following code:
public static void main (String args[])
{
Scanner reader = new Scanner(System.in);
System.out.println("Enter a Numerator");
int num =reader.nextInt();
System.out.println("Enter a Denominator");
int den =reader.nextInt();
System.out.println("Enter a Numerator and a Denominator");
Rational r = new Rational(num,den);
System.out.println(r.getRational() + " equals " +r.getDecimal());
}
}
class Rational
{
double getNum()
{
return num;
}
double getDen()
{
return den;
}
//getDecimal
double getDecimal()
{
double r = num/den;
return r;
}
String getRational()
{
return getNum()+"/"+getDen();
}
private int getGCF(int n1, int n2)
{
int rem = 0;
int gcf = 0;
do
{
rem = n1 % n2;
if (rem == 0)
gcf = n2;
else
{
n1 = n2;
n2 = rem;
}
}
while (rem != 0);
return gcf;
}
}
The purpose of the code is let the user enter a numerator and denominator. Then the program will divide and give the answer to the equations. What I need help on, is I keep on getting an Error on the line of code reading : Rational r = new Rational(num,den). I don't know why.
You forgot to set a constructor in your Rational-Class. You try to initiate the Object with:
Rational r = new Rational(num,den);
But only have the standard COnstructor Rational(). To achieve that you can call this Constructor you have to add this construcotr:
private int num =0;
private int den =0;
public Rational(int unum, int uden){
this.num = unum;
this.den = uden;
}
Within your Rational-Class you have to use then this.numand this.dento get the the constructor setted objects.

Why doesn't my array work?

I'm very new to java (only been using it for 2 days now), and am trying to make a class that lets you input three numbers, and then outputs the average of all three. When the code is like this the output always equals 0 and I don't know why? I am able to get it to work if I change add "static" to all the public integers, but why do I have to do that? Is there another way I can do it without making them static?
import java.util.Scanner;
public class lettuce
{
public int num1;
public int num2;
public int num3;
public static void main(String args[])
{
lettuce lettuceObject = new lettuce();
int total = 0;
int average;
int array[] = {lettuceObject.num1,lettuceObject.num2,lettuceObject.num3};
lettuceObject.getNum1();
System.out.println(lettuceObject.num1);
System.out.println(array[0]);
lettuceObject.getNum2();
System.out.println(lettuceObject.num2);
System.out.println(array[1]);
lettuceObject.getNum3();
System.out.println(lettuceObject.num3);
System.out.println(array[2]);
for(int counter = 0; counter < array.length;counter++)
{
total = total + array[counter];
}
average = total/array.length;
System.out.println("The average of the three numbers is: " + average);
}
public int getNum1()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type your first number: ");
return num1 = keyboard.nextInt();
}
public int getNum2()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type your second number: ");
return num2 = keyboard.nextInt();
}
public int getNum3()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type your third number: ");
return num3 = keyboard.nextInt();
}
}
The output is 0 because you have never initialized your num(s), you're assigning to them on get(s) which you never call - and you're trying to set them in get(s) which isn't the customary approach.
public int num1 = 3;
public int num2 = 3;
public int num3 = 3;
And you should get 3. A getter should look like
public int getNum1()
{
return num1;
}
A setter should look like
public void setNum1(int num1) {
this.num1 = num1;
}
And then you would customarily name your class Lettuce and call it from main like
Lettuce lettuce = new Lettuce();
lettuce.setNum1(10);
System.out.println(lettuce.getNum1());
You would customarily also make your fields private and access them through your mutator and accessor methods (getters and setters)
private int num1;
private int num2;
private int num3;
You could choose to create a constructor
public Lettuce(int num1, int num2, int num3) {
this.num1 = num1;
this.num2 = num2;
this.num3 = num3;
}
You could also calculate the average from "lettuce" with something like
public double average() {
return (num1 + num2 + num3) / 3.0;
}
Edit
Please don't edit your question like that. Also, consider the order of your operations. Your get methods are what set the values. So call them before you create your array!
lettuceObject.getNum1();
lettuceObject.getNum2();
lettuceObject.getNum3();
// Each of those values is 0 until you call the previous three lines.
int array[] = {lettuceObject.num1,lettuceObject.num2,lettuceObject.num3};
System.out.println(array[0]);
System.out.println(array[1]);
System.out.println(array[2]);
As you are new I will give you some more tips they making this work.
1: The static modifier specifies that you don't need to instanciate a Class to use that attribute (variable or method ).
For example, if you have a class with one static variable:
public class Clazz {
static int variable=1;
}
You may call it without creating an instance of Clazz. System.out.println(Clazz.variable); would compile with no problems.
Otherwise, a non-staticattribute will need an Instance of Clazz to be accessed:
Clazz instanceOfClazz = new Clazz();
System.out.println(instanceOfClazz.variable);
2: The type intis native. So, when you create your array, you are passing no values, and after reading the output, your array is not updated.
3: a double variable would be more precise to store the result of an average.
4: last but not least, your getNum method could be merged into just 1 method receiving the message as parameter, so you hace a best and clear reuse of the code. That can be staticbecause it doesn't need to interact with any object of the class Lettuce (with receive as parameter all it needs to execute and return the integer sent by the user, you can assing the return outside the method)
Ps.: by notation, the class name should start with capital letter.
Your final class would look better this way:
import java.util.Scanner;
public class Lettuce
{
public int num1;
public int num2;
public int num3;
public static void main(String args[])
{
Lettuce lettuceObject = new Lettuce();
int total = 0;
double average;
lettuceObject.num1 = lettuceObject.getNum("Please type your first number: ");
System.out.println(lettuceObject.num1);
System.out.println(array[0]);
lettuceObject.num2 = lettuceObject.getNum("Please type your second number: ");
System.out.println(lettuceObject.num2);
System.out.println(array[1]);
lettuceObject.num2 = lettuceObject.getNum("Please type your third number: ");
System.out.println(lettuceObject.num3);
System.out.println(array[2]);
int array[] = {lettuceObject.num1,lettuceObject.num2,lettuceObject.num3};
for(int counter = 0; counter < array.length;counter++)
{
total = total + array[counter];
}
average = total/array.length;
System.out.println("The average of the three numbers is: " + average);
}
public int getNum(String message)
{
Scanner keyboard = new Scanner(System.in);
System.out.println(message);
return keyboard.nextInt();
}
}
Hope this helped.

Concerning multiple constructors in Java

I have a question about multiple instances of a constructor in Java.
My assignment is to receive two fractions and then multiply and divide those fractions.
I am unsure as to how to go about having separate values for the instances of the class objects themselves.
Here is the sample code of where I am having the issue:
import java.util.Scanner;
public class TextLab05
{
static int num1, den1; // numerator and denominator of the 1st rational number
static int num2, den2; // numerator and denominator of the 2nd rational number
public static void main (String args[])
{
enterData();
Rational r1 = new Rational(num1,den1);
Rational r2 = new Rational(num2,den2);
}
}
class Rational
{
private int firstNum; // entered numerator
private int firstDen; // entered denominator
private int num; // reduced numerator
private int den; // reduced denominator
public Rational()
{
}
public Rational(int n, int d)
{
n = TextLab05.num1;
d = TextLab05.den1;
//Here specifically is where I am having comprehension issues. How can I include num2 and den2 if I only have int n and int d?
}
}
If this is hard to understand out of context, here is the entire starting code I was given:
import java.util.Scanner;
public class TextLab05
{
static int num1, den1; // numerator and denominator of the 1st rational number
static int num2, den2; // numerator and denominator of the 2nd rational number
public static void main (String args[])
{
enterData();
Rational r1 = new Rational(num1,den1);
Rational r2 = new Rational(num2,den2);
Rational r3 = new Rational();
r3.multiply(r1,r2);
System.out.println("\n\n" + r1.getOriginal() + " * " + r2.getOriginal() + " = " + r3.getRational());
r3.divide(r1,r2);
System.out.println("\n" + r1.getOriginal() + " / " + r2.getOriginal() + " = " + r3.getRational());
// 100 Point Version Only
// r3.add(r1,r2);
// System.out.println("\n" + r1.getOriginal() + " + " + r2.getOriginal() + " = " + r3.getRational());
// r3.subtract(r1,r2);
// System.out.println("\n" + r1.getOriginal() + " - " + r2.getOriginal() + " = " + r3.getRational());
System.out.println();
}
public static void enterData()
{
Scanner input = new Scanner(System.in);
System.out.print("\nEnter the 1st numerator ----> ");
num1 = input.nextInt();
System.out.print("\nEnter the 1st denominator --> ");
den1 = input.nextInt();
System.out.print("\nEnter the 2nd numerator ----> ");
num2 = input.nextInt();
System.out.print("\nEnter the 2nd denominator --> ");
den2 = input.nextInt();
}
}
class Rational
{
private int firstNum; // entered numerator
private int firstDen; // entered denominator
private int num; // reduced numerator
private int den; // reduced denominator
public Rational()
{
}
public Rational(int n, int d)
{
n = TextLab05.num1;
d = TextLab05.den1;
}
private int getGCF(int n1,int n2)
{
int rem = 0;
int gcf = 0;
do
{
rem = n1 % n2;
if (rem == 0)
gcf = n2;
else
{
n1 = n2;
n2 = rem;
}
}
while (rem != 0);
return gcf;
}
public int getNum()
{
return TextLab05.num1;
}
public int getDen()
{
return TextLab05.den1;
}
public double getDecimal()
{
return (double)TextLab05.num1 / TextLab05.den1;
}
public String getRational()
{
String rational = "" + TextLab05.num1 + "/" + TextLab05.den1;
return rational;
}
public String getOriginal()
{
String original = "" + TextLab05.num1 + "/" + TextLab05.den1;
return original;
}
public void reduce()
{
}
public void multiply(Rational r1, Rational r2)
{
}
public void divide(Rational r1, Rational r2)
{
}
public void add(Rational r1, Rational r2)
{
}
public void subtract(Rational r1, Rational r2)
{
}
}
When you call:
Rational r1 = new Rational(num1, den1);
Rational r2 = new Rational(num2, den2);
in the main method of your program you are creating two instances of the Rational class, one named r1 and one named r2. Because you are passing int values to the Rational constructors, the constructor that will be called is the constructor which requires two integer arguments:
public Rational(int n, int d)
{
...
}
The compiler knows this because it matches the name of the Constructor as well as the types of the arguments passed (known as matching the "signature" of the Constructor).
In the code you have provided, the Rational Constructor code doesn't really make sense - this code:
public Rational(int n, int d)
{
n = TextLab05.num1;
d = TextLab05.den1;
}
should probably look something like this:
public Rational(int n, int d)
{
this.firstNum = n;
this.firstDen = d;
}
The values n and d are passed to the constructor, and then in the body of the constructor the instance variables firstNum and firstDen (which are declared in the private part of the Rational class and effectively "belong" to the instance being created) would then be initialised to the values of n and d.
Everywhere within the body of the Rational class you should refer to the member variables firstNum and firstDen, rather than variables that do not "belong" to the class instance.
I assume the Rational class is supposed to represent a rational number. You say:
//Here specifically is where I am having comprehension issues. How can I include num2 and den2 if I only have int n and int d?
You don't need to store two numerators and two denominators in the Rational class. You just need to creat two Rational objects. One to store num1 and den1, the other to store num2 and den2. You are already doing this:
Rational r1 = new Rational(num1,den1);
Rational r2 = new Rational(num2,den2);
It does not make sense to store two numerators and two denominators in Rational. A rational number only has one of each.
In summary: r1 stores num1 and den1, while r2 stores the other two. When you create a new Rational, n and d refer to the numerator and denominator of that particular instance you are creating.
I am not sure if your implementation of Rational is what you intend, but the constructor is not limited to local varables, it can access any static variables from other classes it can access.
public Rational(int n, int d)
{
n = TextLab05.num1;
d = TextLab05.den1;
}
n and d are local variables, num1 and den1 are static variables in class TextLab05.
So you are assigning the local variables with the static values from the other class.
The code doesn't make sense, as you don't do anything with the values after assigning them to local variables that are disposed when the method ends.
The most important thing to do is understand the concept. You are going to store a rational number in your Rational class. When you do this:
Rational r1 = new Rational(num1,den1);
You are making a single instance of a Rational and naming it r1. r1 should now contain a numerator and a denominator (in this case num1 and den1).
Let's say you want to make the number one half, or 1/2. You could do this:
Rational oneHalf = new Rational(1,2);
Realize that new Rational(1,2) is calling the constructor of your Rational class. In your constructor you need to assign num and den to the passed values (in this case 1 and 2). So you would need something like this:
this.num = num1;
this.den = den1;
So if you want to have the ability to multiply one Rational with another Rational you would need a method or function to do that. In your Rational class, create a method called multiply(Rational anotherRational).
That function would do something like this:
this.num = this.num * anotherRational.num;
this.den = this.den * anotherRational.den;
I gave away half the answer, I'll let you do the rest. Don't just copy what you find here, think about what you're doing.

Java fraction calculator

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

constructor Rational in class Rational cannot be applied to the given types?

So the gist of this program is to create a Rational class so that when you run it, a GUI input will come up and ask for a numerator and a denominator. It will then return the reduced fraction. But I keep getting this error message and I don't know why. Here's the program so far:
import javax.swing.JOptionPane;
public class lab8
{
public static void main (String args[])
{
String strNbr1 = JOptionPane.showInputDialog("Enter Numerator ");
String strNbr2 = JOptionPane.showInputDialog("Enter Denominator ");
int num = Integer.parseInt(strNbr1);
int den = Integer.parseInt(strNbr2);
Rational r = new Rational(num,den);
JOptionPane.showMessageDialog(null,r.getNum()+"/"+r.getDen()+" equals "+r.getDecimal());
System.exit(0);
}
}
class Rational
{
private int num;
private int den;
public Rational()
{
num = 0;
den = 1;
}
public double getNum()
{
return num;
}
public int getDen()
{
return den;
}
}
You are trying to call a constructor that doesn't exist.
Your class constructor asks for nothing:
public Rational()
while it should ask for 2 ints:
public Rational(int num, int den){
this.num = num;
this.den = den;
}
so you can pass both num and den to it as you are trying to do in
Rational r = new Rational(num,den);

Categories