(Solved Homework): Make a class Rational to provide at least following methods and constructors: Plz Write it in Java. Rational r1= new Rational (3,5);

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

 package Rational;

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:

iWriteHomework
Order NOW for a 10% Discount
Pages (550 words)
Approximate price: -

Why Us?

Top Quality and Well-Researched Papers

All ourbpapers are written from scratch. In fact, Clients who ask for paraphrasing services are highly discouraged. We have writers ready to craft any paper from scratch and deliver quality ahead of time.

Professional and Experienced Academic Writers

Our writers keeps you posted on your papers progress - providing you with paper outline/draft. You are also at liberty to communicate directly with your writer.

Free Unlimited Revisions

If you think we missed something, send your order for a free revision. You have 10 days to submit the order for review after you have received the final document. You can do this yourself after logging into your personal account or by contacting our support.

Prompt Delivery and 100% Money-Back-Guarantee

All papers are always delivered on time, in many cases quite ahead of time. In case we need more time to master your paper, we may contact you regarding the deadline extension. In case you cannot provide us with more time, a 100% refund is guaranteed.

Original & Confidential

We use several writing tools checks to ensure that all documents you receive are free from plagiarism. Our editors carefully review all quotations in the text. We also promise maximum confidentiality in all of our services.

24/7 Customer Support

Our support agents are available 24 hours a day 7 days a week and committed to providing you with the best customer experience. Get in touch whenever you need any assistance.

Try it now!

Calculate the price of your order

Total price:
$0.00

How it works?

Follow these simple steps to get your paper done

Place your order

Fill in the order form and provide all details of your assignment.

Proceed with the payment

Choose the payment system that suits you most.

Receive the final file

Once your paper is ready, we will email it to you.

Our Services

No need to work on your paper at night. Sleep tight, we will cover your back. We offer all kinds of writing services.

Essays

Essay Writing Service

No matter what kind of academic paper you need and how urgent you need it, you are welcome to choose your academic level and the type of your paper at an affordable price. We take care of all your paper needs and give a 24/7 customer care support system.

Admissions

Admission Essays & Business Writing Help

An admission essay is an essay or other written statement by a candidate, often a potential student enrolling in a college, university, or graduate school. You can be rest assurred that through our service we will write the best admission essay for you.

Reviews

Editing Support

Our academic writers and editors make the necessary changes to your paper so that it is polished. We also format your document by correctly quoting the sources and creating reference lists in the formats APA, Harvard, MLA, Chicago / Turabian.

Reviews

Revision Support

If you think your paper could be improved, you can request a review. In this case, your paper will be checked by the writer or assigned to an editor. You can use this option as many times as you see fit. This is free because we want you to be completely satisfied with the service offered.

× Contact Live Agents