Java
1)Add a Scrollbar to JTextArea for scrolling up or down.
2) For each public method in Rational class, create a corresponding JButton object. When the user clicks on a button, the actionPerformed listener should execute the corresponding Rational method for all the elements in the two arrays and store the results in a new array. You should then display the result array in the JTextArea using the setText method. For example, if the user hits the add button you should loop through all the elements in arrays and execute:
c[i] = a[i].add(b[i]);
3) If the user hits the sort button, uses the JTextArea method append to append the results of sorting.
//please add this to the following code//
test rational.java:
import java.io.*;
import java.util.*;
import java.awt.*;
import java.math.*;
public class TestRational extends Rational
{
public TestRational() {}
Rational r1= new Rational (3,5);
Rational r2= new Rational (4,7);
Rational r3=r1.add(r2);
Rational a[] = new Rational(a[10]);
Rational b[] = new Rational(b[10]);
for(int i=0; i < 11; i++)
{
a[i] = (int)(Math.random() * 8 + 1);
}
for(int j=0; j < 11; j++)
{
b[j] = (int)(Math.random() * 8 + 1);
}
private JTextField field1;
private JTextField field2;
private JTextArea dis;
public TestRational()
{
JButton addition = new JButton(“+”);
JButton subtract = new JButton(“-“);
JButton divide = new JButton(“/”);
JButton multiply = new JButton(“*”);
JButton sortt = new JButton(“Sort”);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
addition.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Rational b1 = new Rational();
b1.add(a);
}
});
subtract.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent f)
{
Rational b2 = new Rational();
b2.subtract(a);
}
});
divide.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent g)
{
Rational b3 = new Rational();
b3.divide(a);
}
});
multiply.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent h)
{
Rational b4 = new Rational();
b4.multiply(a);
}
});
sortt.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent p)
{
Arrays.sort(a);
/*for(int k=0; k<a.length; i++)
field2.setText(“” + a[i] + ” “); */
}
});
buttonPanel.add(addition);
buttonPanel.add(subtract);
buttonPanel.add(divide);
buttonPanel.add(multiply);
buttonPanel.add(sort);
//Jpanel for fraction area
JPanel mainDisplay = new JPanel();
field2 = new JTextField(20);
dis = new JTextArea(10,20);
JScrollPane scroll = new JScrollPane(dis);
mainDisplay.setLayout(new BorderLayout());
mainDisplay.add(dis);
setSize(300,300);
setVisible(true);
}
}
rational class:
public class Rational
{
private int numerator;
private int denom;
public Rational()
{
}
public Rational(int n, int d)
{
numerator = n;
denom = d;
}
public void setNumerator (int n)
{
numerator = n;
}
public int getNumerator()
{
return numerator;
}
public void setDenominator (int d)
{
denom = d;
}
public int getDenominator()
{
return denom;
}
public Rational add(Rational frac)
{
int top, bottom;
top = frac.getNumerator() * denom + frac.getDenominator() * numerator;
bottom = frac.getDenominator() * denom;
Rational sum = new Rational(top, bottom);
return sum;
}
public Rational subtract(Rational frac)
{
int top, bottom;
top = frac.getNumerator() * denom – frac.getDenominator() * numerator;
bottom = frac.getDenominator() * denom;
Rational difference = new Rational(top, bottom);
return difference;
}
public Rational multiply(Rational frac)
{
int up, down;
up = numerator * frac.getNumerator();
down = denom * frac.getDenominator();
Rational product = new Rational(up, down);
return product;
}
public Rational divide(Rational frac)
{
int upper, lower;
upper = frac.getDenominator() * numerator;
lower = frac.getNumerator() * denom;
Rational quotient = new Rational(upper, lower);
return quotient;
}
public String toString()
{
String x=””;
if(numerator == 0)
x = “0”;
else if(denom == 0)
/* —>>>*/System.out.println(“Denominator cannot take a value of 0.”);
else if(denom == 1)
x = “” + numerator;
else if(denom == numerator)
x = “1”;
else
x = numerator + “/” + denom;
return x;
}
}
class Rational
{
private int num,den,firstNum,firstDen;
public Rational()
{
num = firstNum = 0;
den = firstDen = 1;
}
public Rational(int n, int d)
{
num = firstNum = n;
den = firstDen = d;
}
public int getGCF(int n1,int n2)
{
int rem = n1 % n2;
while(rem !=0)
{
n1 = n2;
n2 = rem;
rem = n1 % n2;
}
return n2;
}
private void reduce()
{
int gcf = getGCF(num,den);
num/=gcf;
den/=gcf;
}
public double getDecimal()
{
double decimal = (double) num / den;
return decimal;
}
public String getRational()
{
return num + “/” + den;
}
public String getOriginal()
{
return num + “/” + den;
}
public int getNum()
{
return num;
}
public int getDen()
{
return den;
}
public void multiply(Rational f1,Rational f2)
{
num = firstNum = f1.getNum() * f2.getNum();
den = firstDen = f1.getDen() * f2.getDen();
reduce();
}
public void divide(Rational f1,Rational f2)
{
num = firstNum = f1.getNum() * f2.getDen();
den = firstDen = f1.getDen() * f2.getNum();
reduce();
}
public void add(Rational f1,Rational f2)
{
num = firstNum = f1.getNum() + getGCF(num,den);
den = firstDen = f1.getDen() + getGCF(num,den);
// This is the other problem method.
}
public void subtract(Rational f1,Rational f2)
{
num = firstNum = f1.getNum() – f2.getNum();
den = firstDen = f1.getDen() – f2.getDen();
}
}
Expert Answer
public class Rational extends Number implements Comparable<Rational> {
private long numerator = 0;
private long denominator = 1;
// DEFAULT CONSTRUCTOR – no args passed in
public Rational() {
this(0, 1); // “this” means call a fellow constructor
}
// FULL CONSTRUCTOR – an arg for each class data member
public Rational(long numerator, long denominator) {
long gcd = gcd(numerator, denominator);
this.numerator = ((denominator > 0) ? 1 : -1) * numerator / gcd;
this.denominator = Math.abs(denominator) / gcd;
}
// ACCESSORS
public long getNumerator() {
return numerator;
}
public long getDenominator() {
return denominator;
}
public String toString() {
if(denominator!=1)
return ” ” + numerator + “/” + denominator;
else
return ” ” + numerator;
}
/**
*
* @param secondRational
* @return
*/
public Rational add(Rational secondRational) {
return new Rational(this.numerator * secondRational.denominator + secondRational.numerator * this.denominator, this.denominator * secondRational.denominator);
}
/**
*
* @param secondRational
* @return
*/
public Rational subtract(Rational secondRational) {
return add(new Rational(-secondRational.numerator, secondRational.denominator));
}
/**
*
* @param secondRational
* @return
*/
public Rational multiply(Rational secondRational) {
return new Rational(numerator * secondRational.numerator, denominator * secondRational.denominator);
}
/**
*
* @param secondRational
* @return
*/
public Rational divide(Rational secondRational) {
return new Rational(numerator * secondRational.denominator, secondRational.numerator * denominator);
}
@Override
public int compareTo(Rational f) {
if (((double) numerator / denominator) == ((double) f.numerator / f.denominator)) {
return 0;
} else if (((double) numerator / denominator) > ((double) f.numerator / f.denominator)) {
return 1;
} else {
return -1;
}
}
private static long gcd(long n, long d) {
long n1 = Math.abs(n);
long n2 = Math.abs(d);
int gcd = 1;
for (int k = 1; k <= n1 && k <= n2; k++) {
if (n1 % k == 0 && n2 % k == 0) {
gcd = k;
}
}
return gcd;
}
//@Override
public boolean equals(Object obj) {
if (!(obj instanceof Rational)) {
return false;
}
if (obj == this) {
return true;
}
if (obj == null) {
return false;
}
final Rational other = (Rational) obj;
if (this.numerator != other.numerator) {
return false;
}
if (this.denominator != other.denominator) {
return false;
}
return true;
}
//@Override
public int hashCode() {
int hash = 7;
hash = 53 * hash + (int) (this.numerator ^ (this.numerator >>> 32));
hash = 53 * hash + (int) (this.denominator ^ (this.denominator >>> 32));
return hash;
}
//@Override
public int intValue() {
return (int)(this.numerator/this.denominator);
}
//@Override
public float floatValue() {
return (float) (this.numerator / this.denominator);
}
//@Override
public long longValue() {
return (long) (this.numerator / this.denominator);
}
//@Override
public double doubleValue() {
return (double)this.numerator / this.denominator;
}
}
//TestRational.java
import java.util.Arrays;
public class TestRational extends javax.swing.JFrame {
Rational a[], b[],c[];
/**
* Creates new form TestRational
*/
public TestRational() {
initComponents();
iniatizeArrays();
}
public void iniatizeArrays(){
a = new Rational[10];
b = new Rational[10];
int min=1,max=9;
int range = (max – min) + 1;
for(int i=0;i<10;i++){
while(true){
int numerator =(int)(Math.random() * range) + min;
int denominator =(int)(Math.random() * range) + min;
if (denominator>numerator){
a[i] =new Rational(numerator, denominator);
break;
}
}
}
for(int i=0;i<10;i++){
while(true){
int numerator =(int)(Math.random() * range) + min;
int denominator =(int)(Math.random() * range) + min;
if (denominator>numerator){
b[i] =new Rational(numerator, denominator);
break;
}
}
}
this.jTextArea.setText(“Array A:”+Arrays.toString(a)+”nArray B:”+Arrays.toString(b));
}
@SuppressWarnings(“unchecked”)
//
private void initComponents() {
panel = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea = new javax.swing.JTextArea();
jAddButton = new javax.swing.JButton();
jSubButton = new javax.swing.JButton();
jDivideButton = new javax.swing.JButton();
jMultiplyButton = new javax.swing.JButton();
jSortButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle(“Rational Test”);
panel.setBackground(new java.awt.Color(2, 173, 192));
panel.setName(“Rational Number Operations”); // NOI18N
jTextArea.setColumns(20);
jTextArea.setRows(5);
jScrollPane1.setViewportView(jTextArea);
jAddButton.setText(“Addition”);
jAddButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jAddButtonActionPerformed(evt);
}
});
jSubButton.setText(“Subtraction”);
jSubButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jSubButtonActionPerformed(evt);
}
});
jDivideButton.setText(“Division”);
jDivideButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jDivideButtonActionPerformed(evt);
}
});
jMultiplyButton.setText(“Multiply”);
jMultiplyButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMultiplyButtonActionPerformed(evt);
}
});
jSortButton.setText(“Sort”);
jSortButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jSortButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout panelLayout = new javax.swing.GroupLayout(panel);
panel.setLayout(panelLayout);
panelLayout.setHorizontalGroup(
panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addGroup(panelLayout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(jAddButton, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jSubButton, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jMultiplyButton, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jDivideButton, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 21, Short.MAX_VALUE)))
.addContainerGap())
.addGroup(panelLayout.createSequentialGroup()
.addGap(187, 187, 187)
.addComponent(jSortButton, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
panelLayout.setVerticalGroup(
panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(50, 50, 50)
.addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jAddButton)
.addComponent(jSubButton)
.addComponent(jMultiplyButton)
.addComponent(jDivideButton))
.addGap(57, 57, 57)
.addComponent(jSortButton)
.addContainerGap(145, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}//
private void jAddButtonActionPerformed(java.awt.event.ActionEvent evt) {
c = new Rational[10];
for(int i=0;i<10;i++){
c[i]=a[i].add(b[i]);
}
this.jTextArea.append(“nAddition :”+Arrays.toString(c));
}
private void jSubButtonActionPerformed(java.awt.event.ActionEvent evt) {
c = new Rational[10];
for(int i=0;i<10;i++){
c[i]=a[i].subtract(b[i]);
}
this.jTextArea.append(“nSubtraction :”+Arrays.toString(c));
}
private void jMultiplyButtonActionPerformed(java.awt.event.ActionEvent evt) {
c = new Rational[10];
for(int i=0;i<10;i++){
c[i]=a[i].multiply(b[i]);
}
this.jTextArea.append(“nMultiplication :”+Arrays.toString(c));
}
private void jDivideButtonActionPerformed(java.awt.event.ActionEvent evt) {
c = new Rational[10];
for(int i=0;i<10;i++){
c[i]=a[i].divide(b[i]);
}
this.jTextArea.append(“nDivision :”+Arrays.toString(c));
}
private void jSortButtonActionPerformed(java.awt.event.ActionEvent evt) {
Arrays.sort(c);
this.jTextArea.append(“nSorted result:”+Arrays.toString(c));
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if (“Nimbus”.equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(TestRational.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TestRational.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TestRational.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TestRational.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TestRational().setVisible(true);
}
});
}
// Variables declaration
private javax.swing.JButton jAddButton;
private javax.swing.JButton jDivideButton;
private javax.swing.JButton jMultiplyButton;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JButton jSortButton;
private javax.swing.JButton jSubButton;
private javax.swing.JTextArea jTextArea;
private javax.swing.JPanel panel;
// End of variables declaration
}