Issue with Scope and Access - java

Using Java and trying to solve the following problem, my code keeps giving this error:
"TesterClass.java:41: error: incompatible types: int cannot be converted to String
return numerator;"
The code is supposed to print out 0 and and a 1.
I have changed about everything around, I know it is a scope and access issue, just not sure where it is.
public class TesterClass
{
public static void main(String[] args)
{
Fraction f1 = new Fraction();
Fraction f2 = new Fraction(1,2);
System.out.println(f1);
System.out.println(f2.numerator / f2.denominator); //class Scope
}
}
/** Class Fraction */
class Fraction
{
// instance variables
private int numerator;
private int denominator;
// constructor: set instance variables to default values
public Fraction()
{
int d = 1;
numerator = d;
denominator = d;
}
// constructor
public Fraction(int initNumerator, int initDenominator)
{
numerator = initNumerator;
denominator = initDenominator;
}
public String toString()
{
if (denominator == 1)
return numerator;
return numerator + "/" + denominator;
}
public int getNum()
{
return numerator;
}
public int getDen()
{
return denominator;
}
}
Should print out
1
0

return numerator; in itself cannot work because the method is supposed to return a String but numeratoris of type int.
If you want to keep the distiction using if (denominator == 1) you need to manually convert numerator to a String.
You could for example do that using
return String.valueOf(numerator)
(thanks #Antonio)

public class TesterClass
{
public static void main(String[] args)
{
Fraction f1 = new Fraction();
Fraction f2 = new Fraction(1,2);
System.out.println(f1.getNum());
System.out.println(f1);
System.out.println(f2);
}
}
/** Class Fraction */
class Fraction
{
// instance variables
private int numerator;
private int denominator;
// constructor: set instance variables to default values
public Fraction()
{
int d = 1;
int n = 1;
numerator = n;
denominator = d;
}
// constructor: set instance variables to init parameters
public Fraction(int initNumerator, int initDenominator)
{
numerator = initNumerator;
denominator = initDenominator;
}
public String toString()
{
if (denominator == 1)
return String.valueOf(numerator);
return String.valueOf(numerator) + "/" + String.valueOf(denominator);
}
public int getNum()
{
return numerator;
}
public int getDen()
{
return denominator;
}
}

You also trying access private fields numerator and denominator from TesterClass class.
To solve your error you may do:
public String toString() {
if (denominator == 1)
return numerator+"";
return numerator + "/" + denominator;
}

Related

How to aggregate methods from another class?

I have a class Fraction with the arithmetic operations for fractions. Here is an abstract of my class Fraction. (I've included only method of addition.)
package com.company;
import java.util.Scanner;
public class Fraction {
private int num; // numerator
private int denom; // denominator
public Fraction() {
super();
}
public Fraction(int num, int denom) {
super();
this.num = num;
this.denom = denom;
if (denom == 0) {
this.denom = 1;
}
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public int getDenom() {
return denom;
}
public void setDenom(int denom) {
if (denom > 0) {
this.denom = denom;
}
}
public void inputFraction() {
Scanner innum = new Scanner(System.in);
System.out.println("Input numerator: ");
num = innum.nextInt();
Scanner indenom = new Scanner(System.in);
System.out.println("Input denominator: ");
denom = indenom.nextInt();
}
public String toString() {
return num + "/" + denom;
}
// addition
public Fraction add(Fraction f2) {
int num2 = f2.getNum();
int denom2 = f2.getDenom();
int num3 = (num * denom2) + (num2 * denom);
int denom3 = denom * denom2;
Fraction f3 = new Fraction(num3, denom3);
f3.simplifyFraction();
return f3;
}
}
Now my second task is to make a class Calculator, which aggregates two instances of class Fraction as its attributes and create a complete set of arithmetic operations using instances of the class Fraction as operands. So, if I am correct, I basically have to use those methods from the class Fraction in my Calculator. I've attempted to do that but I do not get any output when I call for method add (from class Calculator) in main().
Here is an abstract of my Calculator class. (I've included only method of addition to give the general idea.)
package com.company;
public class Calculator {
private Fraction f1 = new Fraction();
private Fraction f2 = new Fraction();
private Fraction f;
public Calculator() {
super();
}
public Calculator(Fraction f) {
this.f = f;
}
public void input() {
f1.inputFraction();
f2.inputFraction();
}
public void view() {
f1.toString();
System.out.println("Fraction = " + f1.toString());
f2.toString();
System.out.println("Fraction = " + f2.toString());
}
public Calculator add() {
Calculator f = new Calculator(f1.add(f2));
return f;
}
}
And part of my main():
Calculator m = new Calculator();
m.input();
m.view();
System.out.println("Sum = " + m.add());
I'm assuming there are multiple places where I have gone wrong, so I'd be grateful for some advice.
Your add method is the problem here. It is returning a Calculator object and println calls that object's toString method so the toString method for Calculator is being called. The add method should not return a new Calculator but instead a new Fraction that represents your result. Then the code will print the toString method in your Fraction class which is what you want to display.
public class Calculator {
.
.
.
public Fraction add() {
return f1.add(f2);
}
}

The Constructor Rational(String) is not found

I am having an error on line 5 in my main function... The line reads:
System.out.println( "The fractional number is " + myRational.Rational(s) );
The error that occuring is telling me
The method Rational(String) is undefined for the type Assignment13.Rational.
Any help or suggestions would be greatly appreciated.
import java.math.BigInteger;
import java.util.Scanner;
public class Assignment13 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a decimal number: ");
String s = input.next();
Rational myRational = new Rational();
System.out.println( "The fractional number is " + myRational.Rational(s) );
}
public class Rational extends Number implements Comparable<Rational> {
// Data fields for numerator and denominator
private BigInteger numerator = BigInteger.ZERO;
private BigInteger denominator = BigInteger.ONE;
/** Construct a rational with default properties */
public Rational() {
this(BigInteger.ZERO,BigInteger.ONE);
}
/** Construct a rational with specified numerator and denominator */
public Rational(BigInteger numerator, BigInteger denominator) {
BigInteger gcd = gcd(numerator, denominator);
this.numerator= (denominator.compareTo(BigInteger.ZERO) > 0 ? BigInteger.ONE :
new BigInteger("-1")).multiply(numerator.divide(gcd));
this.denominator = denominator.divide(gcd);
}
public Rational(String decimal) {
int index = (decimal.contains(".")) ? decimal.indexOf('.') : decimal.indexOf('/');
BigInteger d;
BigInteger n;
// if string is in decimal form
if (decimal.contains(".")) {
int power = decimal.substring(index + 1, decimal.length()).length();
d = new BigInteger ("Math.pow(10,power)");
n = new BigInteger(new StringBuilder(decimal).deleteCharAt(index).toString());
} else {
// if string contains '/'
n = new BigInteger(decimal.substring(0, index));
d = new BigInteger(decimal.substring (index + 1, decimal.length()));
}
BigInteger gcd = gcd(n, d);
this.numerator = ((d.compareTo(BigInteger.ZERO) > 0) ? BigInteger.ONE : new BigInteger("-1")).multiply(n).divide(gcd);
this.denominator = d.abs().divide(gcd);
}
/** Find GCD of two numbers */
private BigInteger gcd(BigInteger n, BigInteger d) {
BigInteger n1 = n.abs();
BigInteger n2 = d.abs();
BigInteger gcd = BigInteger.valueOf(1);
for (BigInteger k = BigInteger.valueOf(1); k.compareTo(n1) <= 0 && k.compareTo(n2) <= 0; k.add(BigInteger.ONE)) {
if (n1.mod(k) == BigInteger.ZERO && n2.mod(k) == BigInteger.ZERO)
gcd = k;
}
return gcd;
}
/** Return numerator */
public BigInteger getNumerator() {
return numerator;
}
/** Return denominator */
public BigInteger getDenominator() {
return denominator;
}
/** Add a rational number to this rational */
public Rational add(Rational secondRational) {
BigInteger n = numerator.multiply(secondRational.getDenominator()).add(denominator.multiply(secondRational.getNumerator()));
BigInteger d = denominator.multiply(secondRational.getDenominator());
return new Rational(n, d);
}
/** Subtract a rational number from this rational */
public Rational subtract(Rational secondRational) {
BigInteger n = numerator.multiply(secondRational.getDenominator()).subtract(denominator.multiply(secondRational.getNumerator()));
BigInteger d = denominator.multiply(secondRational.getDenominator());
return new Rational(n, d);
}
/** Multiply a rational number by this rational */
public Rational multiply(Rational secondRational) {
BigInteger n = numerator.multiply(secondRational.getNumerator());
BigInteger d = denominator.multiply(secondRational.getDenominator());
return new Rational(n, d);
}
/** Divide a rational number by this rational */
public Rational divide(Rational secondRational) {
BigInteger n = numerator.multiply(secondRational.getDenominator());
BigInteger d = denominator.multiply(secondRational.numerator);
return new Rational(n, d);
}
#Override
public String toString() {
if (denominator.compareTo(BigInteger.ONE) == 0)
return numerator + "";
else
return numerator + "/" + denominator;
}
#Override // Override the equals method in the Object class
public boolean equals(Object other) {
if (((this.subtract((Rational)(other))).getNumerator()).compareTo(BigInteger.ZERO) == 0)
return true;
else
return false;
}
#Override // Implement the abstract intValue method in Number
public int intValue() {
return (int)doubleValue();
}
#Override // Implement the abstract floatValue method in Number
public float floatValue() {
return (float)doubleValue();
}
public BigInteger bigIntegerValue() {
return numerator.multiply(new BigInteger("1").divide(denominator));
}
#Override // Implement the doubleValue method in Number
public double doubleValue() {
return numerator.divide(denominator).doubleValue();
}
#Override // Implement the abstract longValue method in Number
public long longValue() {
return (long)doubleValue();
}
#Override // Implement the compareTo method in Comparable
public int compareTo(Rational o) {
if (this.subtract(o).getNumerator().compareTo(BigInteger.ZERO) > 0)
return 1;
else if (this.subtract(o).getNumerator().compareTo(BigInteger.ZERO) < 0)
return -1;
else
return 0;
}
}
}
You pass the String s to a constructor of class Assignment13.Rational and call it from an instance myRational which is work. There is no reason to create a new object nor use another one for the same thing.
myRational is already Rational since the variable declaration. If you want to print a newly created object from the String s, do:
System.out.println("The fractional number is " + new Assignment13().new Rational(s));
Or better make the class static and then is accessible with:
new Rational(s)) at the same class
new Assignment13.Rational(s) from all the classes since they are public.
In both cases, you can omit the line:
Rational myRational = new Rational(); // TODO: remove
I suggest you override the method Object::toString which is while printing out to the console by default.

having an issue converting fractions to double

For some reason I've been unable to print a fraction as a double. I can't get past it. It gives formatting errors every time. The parts giving me issues are commented. Class and driver code are below. and help is appreciated.
Class code
public class Fraction1
{
private int numerator;
private int denominator;
public void Fraction1(int n, int d)
{
this.numerator = n;
this.denominator = d;
}
public void print()
{
System.out.println(numerator + "/" + denominator);
}
public Fraction1 add(Fraction1 other)
{
int n = this.numerator * other.denominator +
this.denominator * other.numerator;
int d = this.denominator * other.denominator;
return this;
}
//public void printAsDouble()
//{
// this.printAsDouble();
// System.out.println((double)(numerator)/(double) (denominator));
//}
}
Driver code
import java.util.*;
public class FractionDriver1
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
Fraction c, d, x;
x = new Fraction();
System.out.println("Enter numerator; then denominator.");
c = new Fraction(input.nextInt(), input.nextInt());
c.print();
System.out.println();
System.out.println("Enter numerator; then denominator.");
d = new Fraction(input.nextInt(), input.nextInt());
d.print();
System.out.println("Sum:");
x.add(c).add(d);
x.print();
//x.printAsDouble();
}
}
Should be:
(double)((numerator)/(denominator))
public class Fraction1
{
private int numerator;
private int denominator;
//no return type in constructor
public Fraction1(int n, int d)
{
this.numerator = n;
this.denominator = d;
}
public void print()
{
System.out.println(numerator + "/" + denominator);
}
public Fraction1 add(Fraction1 other)
{
//Does nothing. What does saving the values in n and d give you.
//Nothing. Hence your objects numerator and denominator
//remains 0 and hence 0/0 gives your error
int n = this.numerator * other.denominator +
this.denominator * other.numerator;
int d = this.denominator * other.denominator;
return this;
}
//public void printAsDouble()
//{
// this.printAsDouble();
// System.out.println((double)(numerator)/(double) (denominator));
//}
}
x.add(c).add(d);
So x is an empty object i.e numerator and denominator = 0.
I use the add function, but it does not modify my x object and it remains the same. In the end, i call print and it should always print 0/0.
As per the error you are getting, check your command line arguments, they must be wrong.

Java NullpointerException in the main class

The problem:
After creating an array of FractionClass objects I try to give each Fraction a numerator and denominator ,by reading in a txtfile that looks like this:
11 12
7 24
2 3
5 6
7 9
...
The first number being the numerator and the second one being the denominator, to do this I use the Scanner class.
Under the readFractions-methode i placed comments where the NULLpointerexception is located.
The mainfile:
package labo2oef5;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Labo2Oef5 {
private static Breuk [] fractionArray;
private static int amountOfLines;
public static void main(String[] args) throws FileNotFoundException {
lengteBestand(); // stel amountOfLines al in
readFractions();
System.out.println(fractionArray[4].getNumerator()+" / "+ fractionArray[4].getDenominator());`
}
public static void readFractions() throws FileNotFoundException{
Scanner lezer = new Scanner(new File("breuken01.txt"));
fractionArray = new Breuk[amountOfLines];
for(int i=0; i<amountOfLines;i++){
double numerator = (double) lezer.nextInt();
double denominator = (double) lezer.nextInt();
fractionArray[i].setNumerator(numerator); // HERE IT GOES WRONG, THE NULLPOINTEREXCEPTION IS HERE
fractionArray[i].setDenominator(denominator);// THIS LINE SUFFERS AS WELL FROM THE NULLPOINTEREXCEPTION
lezer.nextLine();
}
}
public static int lengteBestand() throws FileNotFoundException{
Scanner lezer = new Scanner(new File("breuken01.txt"));
amountOfLines=0;
while(lezer.hasNextLine()){
amountOfLines++;
lezer.nextLine();
}
return amountOfLines;
}
}
The Breuk(is dutch for Fraction) class:
package labo2oef5;
public class Breuk {
private double numerator, denominator;
public Breuk() {
numerator = 0;
denominator = 1;
}
public Breuk(double numerator, double denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
#Override
public String toString() {
String breuk = numerator + "/" + denominator;
if (numerator == 0) {
breuk = "0";
}
return breuk;
}
private static double grootsteGemeneDeler(double a, double b) {
if (a < 0 || b < 0) {
return grootsteGemeneDeler(Math.abs(a), Math.abs(b));
}
if (b == 0) {
return a;
}
if (a < b) {
return grootsteGemeneDeler(b, a);
}
if (a % b != 0) {
return grootsteGemeneDeler(b, a % b);
} else {
return b;
}
}
public String normaliseer() {
double numerator2 = numerator / (grootsteGemeneDeler(numerator, denominator));
double denominator2 = denominator / (grootsteGemeneDeler(numerator, denominator));
return numerator2 + "/" + denominator2;
}
public double decimaleVorm() {
double decim = (double) numerator / denominator;
System.out.println(decim);
return decim;
}
public boolean isGroterDan(Breuk br) {
if (this.decimaleVorm() > br.decimaleVorm()) {
return true;
} else {
return false;
}
}
public void vermeerderBreuk(Breuk br) {
this.numerator = this.numerator * br.denominator + this.denominator * br.numerator;
this.denominator = this.denominator * br.denominator;
}
public void produkt(Breuk br, Breuk breu) {
numerator = br.numerator * breu.numerator;
denominator = br.denominator * breu.denominator;
}
public void setNumerator(double numerator) {
this.numerator = numerator;
}
public void setDenominator(double denominator) {
this.denominator = denominator;
}
public double getNumerator() {
return numerator;
}
public double getDenominator(){
return denominator;
}
}
Both answers are the right answer ,I just had to add this code underneath their answer as well:
if (lezer.hasNextLine()) {
lezer.nextLine();
}
fractionArray[i] is null, so it throws NullPointerException.
I think that you should do it like that:
fractionArray[i] = new Breuk();
fractionArray[i].setNumerator(numerator);
fractionArray[i].setDenominator(denominator);
Try this:
public static void readFractions() throws FileNotFoundException{
Scanner lezer = new Scanner(new File("breuken01.txt"));
fractionArray = new Breuk[amountOfLines];
for(int i=0; i<amountOfLines;i++){
double numerator = (double) lezer.nextInt();
double denominator = (double) lezer.nextInt();
fractionArray[i] = new Breuk(numerator, denominator);
// Creating an array of references leaves them all null until you point them to something non-null by calling new
lezer.nextLine();
}
}

Why am I getting the wrong boolean returned when all other instances are correct?

Here's my Rational class:
package lab18f;
import static java.lang.System.*;
class Rational implements Comparable<Rational>
{
//add two instance variables
private int num, den;
//write two constructors
public Rational ()
{
num = 1;
den = 1;
}
public Rational (int numer, int deno)
{
num = numer;
den = deno;
}
//write a setRational method
public void setRational(int numer, int deno)
{
num = numer;
den = deno;
}
//write a set method for numerator and denominator
public void setNumerator(int numer)
{
num = numer;
}
public void setDenominator(int deno)
{
den = deno;
}
public void add(Rational other)
{
//num1/den1 + num2/den2
//new numerator = (num1 * den2 + num2 * den1)
//new denominator = (den1 * den2)
int newNumer = (this.getNumer()*other.getDeno() + other.getNumer()*this.getDeno());
int newDeno = this.getDeno()*other.getDeno();
this.setRational(newNumer, newDeno);
reduce();
}
private void reduce()
{
int gcd = 0;
int numer = num;
int deno = den;
if(numer > deno)
gcd = gcd(numer,deno);
else if(numer < deno)
gcd = gcd(deno, numer);
else
gcd = numer;
this.setRational(num/gcd, den/gcd);
}
private int gcd(int numOne, int numTwo)
{
int one = numOne;
int two = numTwo;
int gcd = two;
if(two==0)
return one;
return gcd(two, one%two);
}
public Object clone ()
{
return new Rational(num, den);
}
//ACCESSORS
//write get methods for numerator and denominator
public int getNumer()
{
return num;
}
public int getDeno()
{
return den;
}
public boolean equals( Object obj)
{
Rational lhs = (Rational)obj;
if((getNumer()/getNumer()== lhs.getNumer()/lhs.getNumer()) && getDeno()/getNumer() == lhs.getDeno()/lhs.getNumer())
return true;
return false;
}
public int compareTo(Rational other)
{
return -1;
}
//write toString() method
public String toString()
{
return "" + getNumer() + "/" + getDeno();
}
}
and the runner class for the Rational class:
import static java.lang.System.*;
public class Lab18f
{
public static void main( String args[] )
{
Rational test = new Rational();
out.println("test = " + test);
Rational newOne = new Rational(3,4);
out.println("newOne = "+newOne);
out.println("test.equals(newOne) = "+test.equals(newOne));
newOne = (Rational)test.clone();
out.println("\n\nnewOne after test.clone() = "+newOne);
out.println("test.equals(newOne) = "+test.equals(newOne));
Rational rOne = new Rational(1,2);
Rational rTwo = new Rational(2,3);
out.println("1/2.equals(2/3) = "+rOne.equals(rTwo));
test.setRational(4,6);
out.println("2/3.equals(4/6) = "+rTwo.equals(test));
out.println("\n\nrOne = "+rOne);
out.println("rTwo = "+rTwo);
out.println("rOne.compareTo(rTwo) = "+rOne.compareTo(rTwo));
out.println("rTwo.compareTo(rOne) = "+rTwo.compareTo(rOne));
rOne.add(rTwo);
out.println("\n\nrOne.add(rTwo) = "+ rOne);
rOne.setRational(1,2);
rTwo.setRational(1,3);
rOne.add(rTwo);
out.println("\n\n1/2.add(1/3) = "+ rOne);
rOne.setRational(4,10);
rTwo.setRational(3,5);
rOne.add(rTwo);
out.println("\n\n4/10.add(3/5) = "+ rOne);
rOne.setRational(2,10);
rTwo.setRational(3,6);
rOne.add(rTwo);
out.println("\n\n2/10.add(3/6) = "+ rOne);
//1/4 + 2/8 = 1/2
rOne.setRational(1,4);
rTwo.setRational(2,8);
out.println("\n\n1/4.equals(2/8) = "+rOne.equals(rTwo));
rOne.add(rTwo);
out.println("\n\n1/4.add(2/8) = "+ rOne);
//1/6 + 2/8 = 5/12
rOne.setRational(1,6);
rTwo.setRational(2,8);
out.println("\n\n1/6.equals(2/8) = "+rOne.equals(rTwo));
rOne.add(rTwo);
out.println("\n\n1/6.add(2/8) = "+ rOne);
}
}
my issue at hand is that when I run the runner class (which obviously runs the Rational class) I have a statement like this in my output:
test = 1/1
newOne = 3/4
test.equals(newOne) = true
which clearly the fraction 1/1 does not equal 3/4
Your equals method doesn't appear to be doing what it's supposed to be doing. For one, you are doing integer division, and you are dividing the numerator by itself. Try multiplying the numerator of one and the denominator of the other and comparing it to the product of the numerator of the other and the denominator of the first one. The fractions are equal if those two products are equal.
public boolean equals(Object obj)
{
Rational lhs = (Rational) obj;
return ((getNumer() * lhs.getDeno()) == (getDeno() * lhs.getNumer()));
}

Categories

Resources