Make a class Rational to provide at least following methods and constructors: Plz Write it in Java.
Rational r1= new Rational (3,5);
Rational r2= new Rational (4,7);
Rational r3=r1.add(r2);
// also sub,mult,divide methods
Other that four operations you should provide methods that you think is useful for user of your class.
2. Write a JFrame or JApplet (file name: TestRational.java) that performs the following tasks:
a) Define two arrays of size 10. Each element in the array references to a Rational object that you wrote in Problem 1 above.
Rational a[], b[];
a = new Rational[10];
b = new Rational[10];
Rational |
b) Initialize the arrays in Question a) by creating random Rational numbers. Do this by generating two random numbers between 1 and 9 for each Rational and using the numbers as the numerator and denominator. Denominator should be greater than Numerator. You should generate random numbers with Math.random.
c) Display the contents of both arrays on the screen using JTextArea.
d) Add a Scrollbar to JTextArea for scrolling up or down.
e) 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]);
f) If the user hits the sort button, uses the JTextArea method append to append the results of sorting.
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;
}
}
/**
* @fileName TestRational.java
* @author ravi
* @since 31/1/17
*/
package Rational;
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”)
// <editor-fold defaultstate=”collapsed” desc=”Generated Code”>
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();
}// </editor-fold>
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);
}
//</editor-fold>
/* 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
}
output: