How can I rewrite this code to use object oriented programming? - java

public class stackOverflow
{
public static void main (String args[])
{
int maxNumbers = 100;
int numbers[] = new int[maxNumbers];
for (int k = 0; k < numbers.length; k++)
numbers[k] = getRandom(10,99);
for (int k = 0; k < numbers.length; k++)
System.out.print(numbers[k] + " ");
System.out.println();
}
public static int getRandom(int min, int max)
{
int range = max - min + 1;
double rndDouble = Math.random() * range;
int rndInt = (int) rndDouble + min;
return rndInt;
}
}
The provided program works correctly, but I didn't write it very neatly/professionally. Can anyone give me some guidance on how I could rewrite this to implement Object Oriented Programming under a List class?

This can be an alternative...
class Numbers {
int maxNumbers;
int numbers[];
public Numbers(int maxNumbers) {
// TODO Auto-generated constructor stub
this.maxNumbers = maxNumbers;
this.numbers = new int[maxNumbers];
}
public int getRandom(int min, int max) {
int range = max - min + 1;
double rndDouble = Math.random() * range;
int rndInt = (int) rndDouble + min;
return rndInt;
}
}
public class StackOverflow {
public static void main(String [] args) {
Numbers numbers = new Numbers(100);
for (int k = 0; k < numbers.numbers.length; k++)
numbers.numbers[k] = numbers.getRandom(10,99);
for (int k = 0; k < numbers.numbers.length; k++)
System.out.print(numbers.numbers[k] + " ");
}
}
Or something like this...
public class StackOverflow {
static int maxNumbers = 100;
static int numbers[] = new int[maxNumbers];
public static void main (String args[]) {
StackOverflow stackOverflow = new StackOverflow();
for (int k = 0; k < numbers.length; k++)
numbers[k] = stackOverflow.getRandom(10,99);
for (int k = 0; k < numbers.length; k++)
System.out.print(numbers[k] + " ");
System.out.println();
}
public int getRandom(int min, int max) {
int range = max - min + 1;
double rndDouble = Math.random() * range;
int rndInt = (int) rndDouble + min;
return rndInt;
}
}
Friend, There are a numbers of alternatives.

import java.util.ArrayList;
import java.util.List;
int maxNumbers = 100;
List<Integer> numbers = new ArrayList<Integer>();
for (int k = 0; k < maxNumbers; k++)
numbers.add( getRandom(10,99) );
System.out.println(numbers.toString());
is this kind of what you wanted?

A Number of ways to write this structured linear program in oops. Here is my version..
public class stackOverflow
{
int numbers[];
public stackOverflow(){ //assuming default constructor will provide a 100 length array
int maxNumbers = 100;
this.numbers[] = new int[maxNumbers];
}
public stackOverflow(int length){ //Provide a length according to your need.
this.numbers[] = new int[length];
}
private void fillNumberArrayWithRandomNumber(){
for (int k = 0; k < this.numbers.length; k++)
numbers[k] = this.getRandom(10,99);
}
private void printAllNumbersInArray(){
for (int k = 0; k < this.numbers.length; k++)
System.out.print(numbers[k] + " ");
System.out.println();
}
public static void main (String args[])
{
stackOverflow obj1 = new stackOverflow(); //default Constructor will call with array lenth 100
obj1.fillNumberArrayWithRandomNumber();
obj1.printAllNumbersInArray();
stackOverflow obj2 = new stackOverflow(50); //overloaded Constructor will Call with array length 50
obj2.fillNumberArrayWithRandomNumber();
obj2.printAllNumbersInArray();
}
public int getRandom(int min, int max)
{
int range = max - min + 1;
double rndDouble = Math.random() * range;
int rndInt = (int) rndDouble + min;
return rndInt;
}
}
Another Way to separate the business logic to the other class. and calling it From Others.
public class GenerateRandomNumbers
{
int numbers[];
public GenerateRandomNumbers(){ //assuming default constructor will provide a 100 length array
int maxNumbers = 100;
this.numbers[] = new int[maxNumbers];
}
public GenerateRandomNumbers(int length){ //Provide a length according to your need.
this.numbers[] = new int[length];
}
public void fillNumberArrayWithRandomNumber(){
for (int k = 0; k < this.numbers.length; k++)
numbers[k] = this.getRandom(10,99);
}
public void printAllNumbersInArray(){
for (int k = 0; k < this.numbers.length; k++)
System.out.print(numbers[k] + " ");
System.out.println();
}
private int getRandom(int min, int max)
{
int range = max - min + 1;
double rndDouble = Math.random() * range;
int rndInt = (int) rndDouble + min;
return rndInt;
}
}
class stackOverflow {
public static void main (String args[])
{
GenerateRandomNumbers obj1 = new GenerateRandomNumbers(); //default Constructor will call with array lenth 100
obj1.fillNumberArrayWithRandomNumber();
obj1.printAllNumbersInArray();
GenerateRandomNumbers obj2 = new GenerateRandomNumbers(50); //overloaded Constructor will Call with array length 50
obj2.fillNumberArrayWithRandomNumber();
obj2.printAllNumbersInArray();
}
}

You could do it with Random (and nextInt(int)), and in Java 8+ a lambda expression. That might look something like
int maxNumbers = 100;
int min = 10;
int max = 99;
Random rand = new Random();
List<Integer> al = new ArrayList<>();
IntStream.range(0, maxNumbers).forEach(x -> {
al.add(rand.nextInt(max - min) + min);
});
al.stream().forEach(x -> {
System.out.printf("%d%n", x);
});

Using a list:
The following is an example class that utilizes an object list to hold each number. You can either declare a max size with the parameterized constructor or you could use the default constructor which sets it to 100.
The setNumbers method will never execute more than once (by checking the size to the max size) so that the list never gets larger than the max size. Also, you could add parameters to the setNumbers method so that you could choose the range that each random number would be between rather than just 10-99. The getNumbers method will return the list object which contains all of the numbers.
import java.util.ArrayList;
import java.util.List;
public class Example {
int maxNumbers;
List<Object> list = new ArrayList<Object>();
public Example(){
this.maxNumbers = 100;
}
public Example( int max){
this.maxNumbers = max;
}
private int getRandom(int min, int max)
{
int range = max - min + 1;
double rndDouble = Math.random() * range;
int rndInt = (int) rndDouble + min;
return rndInt;
}
public List<Object> getNumbers(){
return this.list;
}
public void setNumbers(){
if (list.size() >= maxNumbers){
return;
}
for (int k = 0; k < this.maxNumbers; k++)
this.list.add(getRandom(10,99));
}
}
Here is an example for a driver class.
public class ExampleDriver
{
public static void main (String args[])
{
//Instantiates the object using the default constructor.
Example test = new Example();
//Generates the numbers within the list.
test.setNumbers();
//Stores the returned list from getNumbers() to exampleList
List<Object> exampleList = test.getNumbers();
}
}

You can create your own RandomList which extends ArrayList<Integer>:
public class RandomList extends ArrayList<Integer> {
private int size;
private int min;
private int max;
public RandomList(int size, int min, int max) {
super(size);
this.size = size;
this.min = min;
this.max = max;
}
/**
* Populate list with entries between min and max
*/
public void populate() {
Random rand = new Random();
for (int t = 0; t < size; t++) {
this.add(rand.nextInt(max - min) + min);
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (Integer i:this) {
sb.append(i).append(" ");
}
return sb.toString();
}
public static void main (String [] args) {
RandomList randomList = new RandomList(100, 10, 99);
randomList.populate();
System.out.println(randomList);
}
}

You could implement your own List class. For that you should define a Node, a List class (which will contain nodes) and a Service that will be responsible to create the random numbers.
This service will be represented in a singleton (a class that cannot be instantiated by any other class).
public class MyRandom {
private static MyRandom rdn = new MyRandom();
private MyRandom() {}
public static MyRandom getInstance() {
return rdn;
}
public int getRandom(int min, int max) {
int range = max - min + 1;
double rndDouble = Math.random() * range;
int rndInt = (int) rndDouble + min;
return rndInt;
}
}
The Node will only contain a value (the random number) and a reference to the next node. This is the Node class
public class MyNode {
private final int value;
private MyNode next;
public MyNode(int value) {
this.value = value;
next = null;
}
public void setNext(MyNode next) {
this.next = next;
}
public int getValue() {
return value;
}
public MyNode getNext() {
return next;
}
}
The List class will contain a reference to the root node, which will also be responsible to add new nodes to the list.
Keep in mind that you could use Generics as well.
public final class MyList {
private MyNode root;
public MyList(int maxNumber) {
for (int i = 0; i < maxNumber; i++) {
addNode(MyRandom.getInstance().getRandom(0, 99));
}
}
public boolean isEmpty() {
return root == null;
}
public void addNode(int value) {
if (isEmpty()) {
root = new MyNode(value);
} else {
MyNode aux = root;
while (aux.getNext() != null)
aux = aux.getNext();
aux.setNext(new MyNode(value));
}
}
public void printList() {
if (!isEmpty()) {
MyNode aux = root;
while (aux.getNext() != null) {
System.out.println(aux.getValue());
aux = aux.getNext();
}
System.out.println(aux.getValue());
}
}
}
And the Main must only instantiate the MyList class and call the printList to show the list.
public class Main {
public static void main(String[] args) {
MyList lista = new MyList(10);
lista.printList();
}
}
Hope this helps you.

Related

Using Depth-First Search in JAVA program instead of Breadth-First Search

I have a JAVA program where I am creating graphs and I have a Breadth-First Search but I would like to change it to Depth First Search. What changes should I make in a code? Thanks for help in advance.
public class ConnectedComponents
{
static final int MAXV = 100;
static boolean processed[] = new boolean[MAXV];
static boolean discovered[] = new boolean[MAXV];
static int parent[] = new int[MAXV];
static void bfs(CCGraph g, int start)
{
Queue<Integer> q = new LinkedList<Integer>();
int i, v;
q.offer(start);
discovered[start] = true;
while (!q.isEmpty())
{
v = q.remove();
process_vertex(v);
processed[v] = true;
for (i = g.degree[v] - 1; i >= 0; i--)
{
if (!discovered[g.edges[v][i]])
{
q.offer(g.edges[v][i]);
discovered[g.edges[v][i]] = true;
parent[g.edges[v][i]] = v;
}
}
}
}
I think you should understand the difference between depth first search and breadth first search. The code for depth first search goes as follows:
public class ConnectedComponents
{
static final int MAXV = 100;
static boolean processed[] = new boolean[MAXV];
static boolean discovered[] = new boolean[MAXV];
static int parent[] = new int[MAXV];
static void dfs(CCGraph g, int vertex)
{
discovered[vertex] = true;
for (i = g.degree[vertex] - 1; i >= 0; i--)
{
if (!discovered[g.edges[vertex][i]])
{
parent[g.edges[v][i]]=vertex;
dfs(g.edges[v][i]]);
}
}
}
}
The basic difference is the order by which vertexes are tested. While BFS uses queue (FIFO: First In First Out), DFS use stack (LIFO: Last In First Out).
You could implement stack using LinkedList:
LinkedList<Integer> stack = new LinkedList<Integer>();
stack.pop(); //returns the top of the stack
For more information please post mcve including test data.
Full code of the program. The goal is to change bfs to dfs.
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class CCGraph
{
static final int MAXV = 100;
static final int MAXDEGREE = 50;
public int edges[][] = new int[MAXV + 1][MAXDEGREE];
public int degree[] = new int[MAXV + 1];
public int nvertices;
public int nedges;
CCGraph()
{
nvertices = nedges = 0;
for (int i = 1; i <= MAXV; i++)
degree[i] = 0;
}
void read_CCGraph(boolean directed)
{
int x, y;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of vertices: ");
nvertices = sc.nextInt();
System.out.println("Enter the number of edges: ");
int m = sc.nextInt();
System.out.println("Enter the edges: <from> <to>");
for (int i = 1; i <= m; i++)
{
x = sc.nextInt();
y = sc.nextInt();
insert_edge(x, y, directed);
}
sc.close();
}
void insert_edge(int x, int y, boolean directed)
{
if (degree[x] > MAXDEGREE)
System.out.printf(
"Warning: insertion (%d, %d) exceeds max degree\n", x, y);
edges[x][degree[x]] = y;
degree[x]++;
if (!directed)
insert_edge(y, x, true);
else
nedges++;
}
void print_CCGraph()
{
for (int i = 1; i <= nvertices; i++)
{
System.out.printf("%d: ", i);
for (int j = degree[i] - 1; j >= 0; j--)
System.out.printf(" %d", edges[i][j]);
System.out.printf("\n");
}
}
}
public class ConnectedComponents
{
static final int MAXV = 100;
static boolean processed[] = new boolean[MAXV];
static boolean discovered[] = new boolean[MAXV];
static int parent[] = new int[MAXV];
static void bfs(CCGraph g, int start)
{
LinkedList<Integer> q = new LinkedList<Integer>();
int i, v;
q.offer(start);
discovered[start] = true;
while (!q.isEmpty())
{
v = q.remove();
process_vertex(v);
processed[v] = true;
for (i = g.degree[v] - 1; i >= 0; i--)
{
if (!discovered[g.edges[v][i]])
{
q.offer(g.edges[v][i]);
discovered[g.edges[v][i]] = true;
parent[g.edges[v][i]] = v;
}
}
}
}
static void initialize_search(CCGraph g)
{
for (int i = 1; i <= g.nvertices; i++)
{
processed[i] = discovered[i] = false;
parent[i] = -1;
}
}
static void process_vertex(int v)
{
System.out.printf(" %d", v);
}
static void connected_components(CCGraph g)
{
int c;
initialize_search(g);
c = 0;
for (int i = 1; i <= g.nvertices; i++)
{
if (!discovered[i])
{
c++;
System.out.printf("Component %d:", c);
bfs(g, i);
System.out.printf("\n");
}
}
}
static public void main(String[] args)
{
CCGraph g = new CCGraph();
g.read_CCGraph(false);
g.print_CCGraph();
connected_components(g);
}
}

Printing the summary of a series of questions using non-void method

Hy. I wrote this piece of code
import java.util.Scanner;
public class SportsEvents {
public static void main(String[] args) {
String[] contestants = getcontestants();
int[] score=getscores();
System.out.println("The maximum score is: "+getMaxValue(score));
System.out.println("The minimum score is: "+getMinValue(score));
System.out.println("The average is: "+getAverage(score));
}
public static String[] getcontestants()
{
int numcontestants=1;
String name[] = new String[numcontestants];
for(int j=0;j<numcontestants;j++){
Scanner ip=new Scanner(System.in);
System.out.println("Enter contestant's name");
name[j]=ip.nextLine();
}
return name;
}
public static int[] getscores()
{
int numscores=8;
int score[] = new int[numscores];
for (int a=0;a<numscores;a++){
Scanner ip=new Scanner(System.in);
System.out.println("Enter the scores");
score[a]=ip.nextInt();
}
return score;
}
public static int getMaxValue(int[] array) {
int maxValue = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > maxValue) {
maxValue = array[i];
}
}
return maxValue;
}
public static int getMinValue(int[] array) {
int minValue = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < minValue) {
minValue = array[i];
}
}
return minValue;
}
public static int getAverage(int[] people) {
int sum = 0;
for (int i=0; i < people.length; i++) {
sum = sum + people[i];
}
int result = sum / people.length;
return result;
}
}
As you can see, the user enters a name and 8 scores and the computers find the biggest score, the lowest score, and the average. I want a non-void method that will give a summary of everything but I don't know how to do it.
Ex: If I entered James as a name and the numbers 1-8, I want it to print: The contestant is James, his highest score was 8. His lowest score was 1. His average is 49.
Thank you and tell me if it's confusing!!
What you want is to store your immediate result into a single object contains min, max, avg.
In java 8 there's already a method out of the box for you:
int[] score=getscores();
IntSummaryStatistics stats = Arrays.stream(score).summaryStatistics();
IntSummaryStatistics contains
private long count;
private long sum;
private int min;
private int max;
You can also manually get that result:
First define a class will hold your data:
public class SportsEvents {
public static class IntArrayStatistic {
private int min = Integer.MAX_VALUE;
private int max = Integer.MIN_VALUE;
private int sum = 0;
private int avg;
private int count;
// Getter - Setter
public static IntArrayStatistic of(int[] input) {
if (input == null) {
throw new IllegalArgumentException("Null array");
}
IntArrayStatistic result = new IntArrayStatistic();
result.count = input.length;
for (int i : input) {
if (i < result.min) {
result.min = i;
}
if (i > result.max) {
result.max = i;
}
result.sum += i;
}
result.avg = result.sum / result.count;
return result;
}
}
}
And to use this:
int[] score=getscores();
IntArrayStatistic stats = IntArrayStatistic.of(score);

how to delete all the same occurences from an array

So far I have tried to create the method below, but when I run it, the new array leaves zeros for the empty spaces. If a find all method is created to work with this how can it be implemented with a binary search instead of a linear search
package bp;
import java.util.Arrays;
public class SortedList implements IUnsortedList {
/**
* The max size of the List.
*/
public static final int MAX_SIZE = 10000;
/**
* The max value of each occurence.
*/
public static final int MAX_VALUE = 10;
/**
* Flag for the amount of items on the list.
*/
private int sizeOfList = 0;
/**
* Variable to define true or false for duplicates.
*/
private boolean duplicatesAllowed = true;
/**
* Array saves the occurences in the list.
*/
private final int[] listItems = new int[MAX_SIZE];
/**
* Variable for the value to find or delete.
*/
private int searchKey;
/**
* Variable for counter in a loop.
*/
private int f;
#Override
public int getSizeOfList() {
return sizeOfList;
}
#Override
public boolean areDuplicatesAllowed() {
return duplicatesAllowed;
}
#Override
public void setDupliatesAllowed(boolean pDuplicatesAllowed) {
duplicatesAllowed = pDuplicatesAllowed;
}
#Override
public void clear() {
sizeOfList = 0;
}
#Override
public void insert(int pValueToInsert) {
//Loop finds the position of the Item
for (f = 0; f < sizeOfList; f++)
if (listItems[f] > pValueToInsert)
break;
//Loop moves the items after the position up
for (int n = sizeOfList; n > f; n-- )
listItems[n] = listItems[n - 1];
//Insert the Value in the right position
listItems[f] = pValueToInsert;
//Increment List size
sizeOfList++;
}
#Override
public void delete(int pValueToDelete) {
int destroyHAHAHA = find(pValueToDelete);
//If it doesnt find it the item
if (destroyHAHAHA==sizeOfList)
System.out.println("I let you down boss, Can't find "
+ pValueToDelete);
//If it does, kill it with fire
else {
for (int n = destroyHAHAHA; n <sizeOfList; n++)
listItems[n] = listItems[n + 1];
sizeOfList--;
}
}
#Override
public void deleteAll(int pValueToDelete) {
int j = 0;
for(int i = 0; i < listItems.length; i++ )
{
if (listItems[i] != pValueToDelete)
listItems[j++] = listItems[i];
}
int [] newArray = new int[j];
System.arraycopy(listItems, 0, newArray, 0, j );
}
#Override
public void initializeWithRandomData(int pSizeOfList) {
// Loop creates an array with certain number of elements
if (duplicatesAllowed) {
for (int n = 0; n < pSizeOfList; ++n) {
insert(listItems[n] = (int) (Math.random() * MAX_VALUE + 1));
}
} else {
int newvalue=0;
for (int n = 0; n < pSizeOfList; ++n) {
listItems[n] = newvalue++;
++sizeOfList;
}
}
}
#Override
public int find(int pValueToFind) {
searchKey = pValueToFind;
int lowNumber = 0;
int highNumber = sizeOfList - 1;
int result;
while (true) {
result = (lowNumber + highNumber) / 2;
if (listItems[result] == searchKey)
return result;
else if (lowNumber > highNumber)
return sizeOfList;
else {
if (listItems[result] < searchKey)
lowNumber = result + 1;
else
highNumber = result - 1;
}
}
}
#Override
public int[] findAll(int pValueToFind) {
//Array with the location of item
int[] answerArray = new int[sizeOfList];
int searchIndex;
int answerIndex = 0;
for (searchIndex = 0; searchIndex < sizeOfList; searchIndex++) {
if (listItems[searchIndex] == pValueToFind) {
answerArray[answerIndex++] = searchIndex;
}
}
if (answerIndex > 0) {
return Arrays.copyOfRange(answerArray, 0, answerIndex);
} else {
return new int[0];
}
}
#Override
public String toString() {
return Arrays.toString(Arrays.copyOfRange(listItems, 0, sizeOfList));
}
public void bubbleshort(){
int out;
int in;
int middle;
for (out = 0; out < sizeOfList - 1; out++) {
middle = out;
for(in = out +1; in < sizeOfList; in++)
if(listItems[in] < listItems[middle])
middle = in;
selectionSort(out, middle);
}
}
public void selectionSort(int one, int two) {
int temporal = listItems[one];
listItems[one] = listItems[two];
listItems[two] = temporal;
}
}
You can use Common langs ArrayUtils.removeElement() or ArrayUtils.removeAll() method to remove all the elements from the array.
Set contains no duplicates. You can use a Set.
Set<T> mySet = new HashSet<T>(Arrays.asList(someArray));
or
Set<T> mySet = new HashSet<T>();
Collections.addAll(mySet, myArray);

Program won't quit after 10 integers or 0 have been entered

Can someone help explain to me why my program won't terminate after either "0" or 10 integers have been entered? It's supposed to after, but it won't and keeps going even after either condition to quit have been met. It compiles correctly and doesn't give me any errors, so I think it has to do with my loops but I don't know what's wrong...
import java.util.Scanner;
public class Lab11
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int intArray[] = new int[10];
int size = 0;
int userInt;
do
{
do
{
System.out.print("Enter an integer in the array, or enter '0' to quit:" + " ");
userInt = scan.nextInt();
if (userInt != 0)
{
intArray[size] = userInt;
size++;
}
}
while (size <= intArray.length);
System.out.println(sum(intArray, size));
System.out.println(max(intArray, size));
System.out.println(min(intArray, size));
System.out.println(average(intArray, size));
System.out.println(stringToArray(intArray, size));
}
while (userInt !=0);
}
public static int sum(int intArray[], int size)
{
int sum = 0;
for (int a = 0; a <= size; a++)
{
sum = sum + intArray[size];
}
return sum;
}
public static int max(int intArray[], int size)
{
int max = intArray[0];
for (int b = 1; b <= size; b++)
{
if (intArray[size] > max)
{
max = intArray[size];
}
}
return max;
}
public static int min(int intArray[], int size)
{
int min = intArray[0];
for (int c = 1; c <= size; c++)
{
if (intArray[size] < min)
{
min = intArray[size];
}
}
return min;
}
public static double average(int intArray[], int size)
{
double total = 0;
double average = 0;
for (double element : intArray)
{
total = total + element;
}
if (intArray.length > 0)
{
average = total / intArray.length;
}
return average;
}
public static String stringToArray(int intArray[], int size)
{
String stringArray = "";
for (int d = 1; d <= size; d++)
{
stringArray = intArray.toString();
}
return stringArray;
}
}
The first if statement that tests for 0 is sandwiched in a do/while, and the do/while will loop your checker until your if statement is true. Place it outside your loop.
Edit: Heh the main method bit was for C, not java :)

Inheritance problems in Java

I have some problems with getting inheritance to work. In the parent class, the array Coefficients is private. I have some access methods but I still can't get it to work.
import java.util.ArrayList;
public class Poly {
private float[] coefficients;
public static void main (String[] args){
float[] fa = {3, 2, 4};
Poly test = new Poly(fa);
}
public Poly() {
coefficients = new float[1];
coefficients[0] = 0;
}
public Poly(int degree) {
coefficients = new float[degree+1];
for (int i = 0; i <= degree; i++)
coefficients[i] = 0;
}
public Poly(float[] a) {
coefficients = new float[a.length];
for (int i = 0; i < a.length; i++)
coefficients[i] = a[i];
}
public int getDegree() {
return coefficients.length-1;
}
public float getCoefficient(int i) {
return coefficients[i];
}
public void setCoefficient(int i, float value) {
coefficients[i] = value;
}
public Poly add(Poly p) {
int n = getDegree();
int m = p.getDegree();
Poly result = new Poly(Poly.max(n, m));
int i;
for (i = 0; i <= Poly.min(n, m); i++)
result.setCoefficient(i, coefficients[i] + p.getCoefficient(i));
if (i <= n) {
//we have to copy the remaining coefficients from this object
for ( ; i <= n; i++)
result.setCoefficient(i, coefficients[i]);
} else {
// we have to copy the remaining coefficients from p
for ( ; i <= m; i++)
result.setCoefficient(i, p.getCoefficient(i));
}
return result;
}
public void displayPoly () {
for (int i=0; i < coefficients.length; i++)
System.out.print(" "+coefficients[i]);
System.out.println();
}
private static int max (int n, int m) {
if (n > m)
return n;
return m;
}
private static int min (int n, int m) {
if (n > m)
return m;
return n;
}
public Poly multiplyCon (double c){
int n = getDegree();
Poly results = new Poly(n);
for (int i =0; i <= n; i++){ // can work when multiplying only 1 coefficient
results.setCoefficient(i, (float)(coefficients[i] * c)); // errors ArrayIndexOutOfBounds for setCoefficient
}
return results;
}
public Poly multiplyPoly (Poly p){
int n = getDegree();
int m = p.getDegree();
Poly result = null;
for (int i = 0; i <= n; i++){
Poly tmpResult = p.multiByConstantWithDegree(coefficients[i], i); //Calls new method
if (result == null){
result = tmpResult;
} else {
result = result.add(tmpResult);
}
}
return result;
}
public void leadingZero() {
int degree = getDegree();
if ( degree == 0 ) return;
if ( coefficients[degree] != 0 ) return;
// find the last highest degree with non-zero cofficient
int highestDegree = degree;
for ( int i = degree; i <= 0; i--) {
if ( coefficients[i] == 0 ) {
highestDegree = i -1;
} else {
// if the value is non-zero
break;
}
}
float[] newCoefficients = new float[highestDegree + 1];
for ( int i=0; i<= highestDegree; i++ ) {
newCoefficients[i] = coefficients[i];
}
coefficients = newCoefficients;
}
public Poly differentiate(){
int n = getDegree();
Poly newResult = new Poly(n);
if (n>0){ //checking if it has a degree
for (int i = 1; i<= n; i++){
newResult.coefficients[i-1]= coefficients[i] * (i); // shift degree by 1 and multiplies
}
return newResult;
} else {
return new Poly(); //empty
}
}
public Poly multiByConstantWithDegree(double c, int degree){ //used specifically for multiply poly
int oldPolyDegree = this.getDegree();
int newPolyDegree = oldPolyDegree + degree;
Poly newResult = new Poly(newPolyDegree);
//set all coeff to zero
for (int i = 0; i<= newPolyDegree; i++){
newResult.coefficients[i] = 0;
}
//shift by n degree
for (int j = 0; j <= oldPolyDegree; j++){
newResult.coefficients[j+degree] = coefficients[j] * (float)c;
}
return newResult;
}
}
Can anyone help me fix my Second class that inherits from the one above? I cant seem to get my multiply and add methods for the second class to work properly.
public class QuadPoly extends Poly
{
private float [] quadcoefficients;
public QuadPoly() {
super(2);
}
public QuadPoly(int degree) {
super(2);
}
public QuadPoly(float [] f) {
super(f);
if (getDegree() > 2){
throw new IllegalArgumentException ("Must be Quadratic");
}
}
public QuadPoly(Poly p){
super(p.coefficients);
for (int i = 0; i < coefficients.length; i++){
if (coefficients[i] < 0){
throw new Exception("Expecting positive coefficients!");
}
}
}
// public QuadPoly(Poly p){
// super(p.coefficients);
//}
public QuadPoly addQuad (QuadPoly p){
return new QuadPoly(super.add(p));
}
public QuadPoly multiplyQuadPoly (QuadPoly f){
if (quadcoefficients.length > 2){
throw new IllegalArgumentException ("Must be Quadratic");
}
return new QuadPoly(super.multiplyPoly(f));
}
I would make the coefficients protected or use an accessor method.
I wouldn't throw a plain checked Exception. An IllegalArgumentException would be a better choice.
What is quadcoefficients? They don't appear to be set anywhere.
You put coefficients private. I wouldn't change this but I would add a getter method into Poly class:
public class Poly {
//somecode here
public float[] getCoefficients(){
return this.coefficients;
}
}
Then I would use it by the getter method in other code;
public QuadPoly(Poly p){
super(p.getCoefficients);
//some more code here
}
Even if you make coefficient protected, you are trying to reach coefficients field of another Object, which is a parameter. So it is not related to inheritance and the problem.

Categories