I am trying to run a class that performs calculations from data obtained from a random variable generator class. What I want is that 3 random variables be generated at any given time, then all calculation in that class be performed without another set of random variables be generated. Once all calculations have been performed then a new set of random variables can be generated. The Computation class is as shown below :
public class Computation {
public int meltTemp;
//public void mTemp;
public int mouldTemp;
public int setTemp;
public int Q;
public int volume;
public double Cp;
public int actualMouldTemp;
public double dT;
public int AMT ;//= Math.abs(dT);
public double mTemp;
public Hashtable catalogue1;
protected void setup() {
//create Hashtable
catalogue1 = new Hashtable();
}
public double getAnswer() {
int rand1[] = new int[3];
int input [] = new int [2];
ControlGUI par = new ControlGUI ();
//input = ControlGUI.getArray();
//catalogue am = new catalogue();
RandomVariableGenerator var = new RandomVariableGenerator();
rand1 = RandomVariableGenerator.getRand();
//int rand[] = Arrays.copyOf(rand1, rand1.length);
meltTemp = 245;
System.out.println("Melt Temp is : "+ meltTemp);
actualMouldTemp = (int) ((0 - 51.4)+(0.302 * meltTemp) +(1.64 * rand1[0])+(0.201 * rand1[1]));
System.out.println("The actual mould temperature is :" +actualMouldTemp + " Degrees celcius" );
return actualMouldTemp;
}
public int getDiff(){
Computation amg = new Computation();
double result[] = new double [4]; {
setTemp = 55;
dT = (actualMouldTemp - setTemp);
AMT = (int) Math.abs(dT);
System.out.println("The temperature difference is : "+ AMT);
return AMT;
}
}
The next method to try and use the generated variables is getHeatingTime1() which needs rand1[2] for the tank volume:
public double getHeatingTime1(){
Computation jose = new Computation();
int [] Results = new int [4];
Results [0] = AMT;
//Results [] = Computation.class;
Q = 3; //heating in kW
Cp = 4.2; //Specific heat capacity of water
volume = 6;
//AMT =
System.out.println("AMT IS "+ Results [0]);
long HT1 = (long) ((volume*Cp*Results [0])/Q);
return HT1;
}
public double getHeatingTime2(){
int Results [] = new int [4] ;
Computation cr7 = new Computation();
//double dT = cr7.getDiff();
Q = 9; //heating in kW
Cp = 4.2; //Specific heat capacity of water
volume = 6;
//AMT = 7;
System.out.println("AMT IS "+ Results [1]);
long HT2 = (long) ((volume*Cp*Results [1])/Q);
return HT2;
}
public double getHeatingTime3(){
int Results [] = new int [4];
//double AMT = getDiff();
Computation jt = new Computation();
//double dT = jt.getDiff();
// AMT = 7;
Q = 18; //heating in kW
Cp = 4.2; //Specific heat capacity of water
volume = 6;
System.out.println("AMT IS "+ Results [1]);
long HT3 = (long) ((volume*Cp*Results [1])/Q);
return HT3;
}
public double getCoolingTime(){
// double CT = 0;
Computation nvh = new Computation();
int rand1[] = new int[3];
int rand[] = Arrays.copyOf(rand1, rand1.length);
//RandomVariableGenerator var = new RandomVariableGenerator();
//rand1 = Computation;
mouldTemp = 55;
System.out.println("Rand 0 is "+ rand1[0]);
System.out.println("Rand 1 is "+ rand1[1]);
System.out.println("Rand 2 is "+ rand1[2]);
double CT = ((0.5/rand[2])*((mouldTemp - rand1[0])/(rand1[1] - mouldTemp)));
double CTA = Math.abs(CT);
return CTA;
}
}
The Random variable generator class is as shown below:
public class RandomVariableGenerator {
public static int[] getRand (){
int rand[] = new int [3];
Random r = new Random ();
int myRandomNumber = 0;
//for (int i=0; i < 1 ; i++)
myRandomNumber = r.nextInt(15) + 5;
System.out.println("Chilled water temperature:" + myRandomNumber);
rand[0] = myRandomNumber;
Random rn = new Random ();
int myNumber = 0;
// (for int i=0; i < 1; i++)
myNumber = rn.nextInt(25) + 50;
System.out.println("Heated water temperature:" + myNumber);
rand[1]= myNumber;
Random rm = new Random ();
int myRandNumber = 0;
// (for int i=0; i < 1; i++)
myRandNumber = rm.nextInt(2) + 6;
System.out.println("Tank Volume:" + myRandNumber);
rand[2]= myRandNumber;
return rand;
}
}
Declare an instance int vector to hold the three values at object (instance) level (rndVars[3])
public class Computation {
public int meltTemp;
//public void mTemp;
public int mouldTemp;
public int setTemp;
public int Q;
public int volume;
public double Cp;
public int actualMouldTemp;
public double dT;
public int AMT ;//= Math.abs(dT);
public double mTemp;
private int [] rndVars = new int[3];
...
Have a public method setRandomVars() you can call whenever you need the 3 values to be reset.
public void setRandomVars(){
rndVars[0] = RandomVariableGenerator.getRand();
rndVars[1] = RandomVariableGenerator.getRand();
rndVars[2] = RandomVariableGenerator.getRand();
}
You could make all of the 3 random variables private and to the class, not the function. Then, when you need a new set call a function that resets them.
For example:
public class MyClass{
//replace these with the actual types/variables you need
int var1;
double var2;
double var3;
/**
*Call this function when you need a new set of variables
**/
public void resetVariables(){
//Change this to the random class you would prefer to use
Random random = new Random(System.currentTimeMillis());
var1 = random.nextInt();
var2 = random.nextDouble();
var3 = random.nextDouble();
}
//put your other functions here except remove the declarations for var1, var2, and var3
/*
ex.
public int myFunction(){
Random random = new Random(System.currentTimeMillis());
int var1 = random.nextInt();
return var1 * 2;
}
becomes
public int myFunction(){
// use the global variable instead of the function's variable
return var1 * 2;
}
*/
}
Related
I have tested the random number generator and it works fine outside of the app. It's a fairly standard piece of code. I created getters and setters, and NetBeans does not complain about anything being passed to the application, but what should be a random number is a "0". I would like to understand more about getters and setters and classes. I may have designated something incorrectly.
//This is the class code
public class RandomGen {
int minSeed = 100;
int maxSeed = 999;
int num;
public static void RandomNum(int minSeed, int maxSeed) {
Random rand = new Random();
int num = rand.nextInt(maxSeed - minSeed) + 1;
}
public void setMin(int minSeed) {
this.minSeed = minSeed;
}
public void setMax(int maxSeed) {
this.maxSeed = maxSeed;
}
public int getNum() {
return num;
}
}
This is the code within main in my application
RandomGen rnumber = new RandomGen();
int rnum = rnumber.getNum();
int bigSeed = rnumber.maxSeed;
int smallSeed = rnumber.minSeed;
System.out.println("Random Number = " + rnum);
System.out.println("MaxSeed = " + bigSeed);
System.out.println("MinSeed = " + smallSeed);
This is the printed return
Random Number = 0
MaxSeed = 999
MinSeed = 100
You have created a local variable so use the global as
num = rand.nextInt(maxSeed - minSeed) + 1;
As per your code , you need to call that static method to initialize num as well so
RandomGen rnumber = new RandomGen();
RandomGen.RandomNum(rnumber.minSeed, rnumber.maxSeed);
//^^^^^^^^^^^^^^^^^^^^^
int rnum = rnumber.getNum();
int bigSeed = rnumber.maxSeed;
int smallSeed = rnumber.minSeed;
Note: constructors cannot be static, can't have any return type
static int num; // global to class, different from the `num` inside RandomNum
public static void RandomNum(int minSeed, int maxSeed)
{
Random rand = new Random();
// local variable
// changes here, can only be seen inside RandomNum method
//int num = rand.nextInt(maxSeed - minSeed) + 1;
num = rand.nextInt(maxSeed - minSeed) + 1;
}
first
static int num; // must also be static
second
public static void RandomNum(int minSeed, int maxSeed)
{
Random rand = new Random();
num = rand.nextInt(maxSeed - minSeed) + 1; // remove the declaration you try to make it local variable
}
This is incorrect.
Try this:
import java.util.Random;
public class RandomGen {
private Random random;
private int minRange;
private int maxRange;
public static void main(String[] args) {
int minRange = (args.length > 0) ? Integer.parseInt(args[0]) : 100;
int maxRange = (args.length > 1) ? Integer.parseInt(args[1]) : 200;
int numValues = (args.length > 2) ? Integer.parseInt(args[2]) : 10;
RandomGen randomGen = new RandomGen(minRange, maxRange);
for (int i = 0; i < numValues; ++i) {
System.out.println(randomGen.getNextIntInRange());
}
}
public RandomGen(int minRange, int maxRange) {
this(minRange, maxRange, null);
}
public RandomGen(int minRange, int maxRange, Long seed) {
this.minRange = minRange;
this.maxRange = maxRange;
this.random = (seed == null) ? new Random() : new Random(seed);
}
public int getNextIntInRange() {
return this.minRange + this.random.nextInt(this.maxRange-this.minRange)+1;
}
}
I have trouble with this equation: E * cotangent((q * E)/(k * t)) = nkT/q.
I'm looking for the values of E for the equality can be achieved
knowing that: q and k are constants, t and n are variables.
For that I tried this code but apparently is failed:
public class Equation {
public static double q = 1.6E-19;
public static double k = 1.38E-23;
//double y = E * 1/Math.tan(E*q/k*t);
//DecimalFormat df = new DecimalFormat("#.#####");
public static double[] nktq = new double[]{0.02857,0.02674,0.03118,0.02829,0.02976,0.02898,0.03001,0.02953,0.032};
public static double[] t = new double[]{80,100,150,200,250,280,300,320,350};
public static double[] n = new double[]{4.14,3.1,2.41,1.64,1.38,1.20,1.16,1.07,1.06};
private static DecimalFormat df2 = new DecimalFormat(".##");
public static double genE(){
double start = 0;
double end = 30;
double random = new Random().nextDouble();
// DecimalFormat df = new DecimalFormat("#.##");
// df.setRoundingMode(RoundingMode.FLOOR);
double E = start + (random * (end - start));
//double E = new Double(df.format(result));
System.out.println(df2.format(E));
return E;
}
public static void main(String[] args) {
//double y = E * 1/Math.tan(E*q/k*t);
//DecimalFormat df = new DecimalFormat("#.#####")
double E = 0;
while ( Math.round(E * 1/Math.tan((q * E)/(k * t[0]))*100000)!= nktq[0]){
genE();
}
}
}
Any help is appreciated!
You create a new Random instance for each value. That's wrong.
Here's what I'd recommend you try:
public class Equation {
private Random random;
public Equation() { this(null); }
public Equation(Long seed) {
this.random = (seed == null) ? new Random() : new Random(seed.longValue());
}
public double nextConst() { return this.random.nextDouble(); }
public double nextConst(double start, double end) {
return start + (end-start)*this.random.nextDouble();
}
// Add the rest of your stuff here.
}
import java.util.Collections;
import java.util.Vector;
public class Metaheuristic {
private static int[] DATA;
private static int NUM_CHROMOSOMES ;
private static int MAX_POWER;
private static int MAX_NUMBER;
private static int FITNESS_THRESHOLD;
private static float MUTATE = (float) .05;
private Vector population;
private boolean done = true;
int numRuns = 0;
public void GeneticAlgorithm (int[] data, int target, int n){
NUM_CHROMOSOMES = n;
MAX_POWER = data.length;
MAX_NUMBER = (int) Math.pow(2, MAX_POWER) - 1;
FITNESS_THRESHOLD = target;
DATA = new int[data.length];
DATA = data;
Metaheuristic s = new Metaheuristic();
s.start();
//System.out.println("s");
}
public Metaheuristic(){
generateRandomPopulation();
}
private void generateRandomPopulation(){
System.out.println("***Randomly Generating population with: " + NUM_CHROMOSOMES + " Chromosome(s)***");
population = new Vector();
for(int i = 0; i < NUM_CHROMOSOMES; ++i){
int randomValue = (int) (Math.random()*MAX_NUMBER);
population.add(new Chromosome(randomValue, MAX_POWER));
}
System.out.println("First Population: " + population +"\n");
}
public void start(){
Collections.sort(population);
Chromosome fitess = (Chromosome) population.lastElement();
done = fitess.fitness(DATA, FITNESS_THRESHOLD) >= MAX_POWER? true:false;
if(done){
System.out.println("DONE, solution found: " + fitess);
}
else{
numRuns++;
System.out.println("FITESS: " + fitess + " fitness: " + fitess.fitness(DATA, FITNESS_THRESHOLD ));
generateNewPopulation();
start();
}
}
private void generateNewPopulation(){
System.out.println("***Generating New Population");
Vector temp = new Vector();
for(int i = 0; i < population.size()/2; ++i){
Chromosome p1 = selectParent();
Chromosome p2 = selectParent();
temp.add(cross1(p1, p2));
temp.add(cross2(p1, p2));
}
population.clear();
population.addAll(temp);
System.out.println("New Population: " + population + "\n");
}
private Chromosome selectParent(){
int delta = population.size();
delta = NUM_CHROMOSOMES - NUM_CHROMOSOMES/2;
int num = (int) (Math.random()*10 + 1);
int index;
if(num >= 4){
index = (int) (Math.random()*delta + NUM_CHROMOSOMES/2);
}
else{
index = (int) (Math.random()*delta);
}
return (Chromosome) population.get(index);
}
private Chromosome cross1(Chromosome parent1, Chromosome parent2){
String bitS1 = parent1.getBitString();
String bitS2 = parent2.getBitString();
int length = bitS1.length();
String newBitString = bitS1.substring(0, length/2) + bitS2.substring(length/2, length);
Chromosome offspring = new Chromosome();
offspring.setBitString(newBitString);
if(shouldMutate()){
mutate(offspring);
}
return offspring;
}
private Chromosome cross2(Chromosome parent1, Chromosome parent2){
String bitS1 = parent1.getBitString();
String bitS2 = parent2.getBitString();
int length = bitS1.length();
String newBitString = bitS2.substring(0, length/2) + bitS1.substring(length/2, length);
Chromosome offspring = new Chromosome();
offspring.setBitString(newBitString);
if(shouldMutate()){
mutate(offspring);
}
return offspring;
}
private boolean shouldMutate(){
double num = Math.random();
int number = (int) (num*100);
num = (double) number/100;
return (num <= MUTATE);
}
private void mutate(Chromosome offspring){
String s = offspring.getBitString();
int num = s.length();
int index = (int) (Math.random()*num);
String newBit = flip(s.substring(index, index+1));
String newBitString = s.substring(0, index) + newBit + s.substring(index+1, s.length());
offspring.setBitString(newBitString);
}
private String flip(String s){
return s.equals("0")? "1":"0";
}
public static void main(String[] args) {
double average = 0;
int sum = 0;
for(int i = 0; i < 10; ++i){
Metaheuristic s = new Metaheuristic();
s.start();
sum = sum + s.numRuns;
average = (double) sum / (double)(i+1);
System.out.println("Number of runs: " + s.numRuns);
}
System.out.println("average runs: " + average);
}
}
import java.lang.Comparable;
public class Chromosome implements Comparable{
protected String bitString;
public static int[] DATA;
public int TARGET;
public Chromosome(){
}
public Chromosome(int value, int length){
bitString = convertIntToBitString(value, length);
}
public void setBitString(String s){
bitString = s;
}
public String getBitString(){
return bitString;
}
public int compareTo(Object o) {
Chromosome c = (Chromosome) o;
int num = countOnes(this.bitString) - countOnes(c.getBitString());
return num;
}
public int fitness(int[] data, int target){
DATA = new int[data.length];
System.arraycopy(data, 0, DATA, 0, data.length);
TARGET = target;
return countOnes(bitString);
}
public boolean equals(Object o){
if(o instanceof Chromosome){
Chromosome c = (Chromosome) o;
return c.getBitString().equals(bitString);
}
return false;
}
public int hashCode(){
return bitString.hashCode();
}
public String toString(){
return "Chromosome: " + bitString;
}
public static int countOnes(String bits){
int sum = 0;
for(int i = 0; i < bits.length(); ++ i){
String test = bits.substring(i, i+1);
sum = sum + (DATA[i]*Integer.parseInt(test));
}
return sum;
}
public static String convertIntToBitString(int val, int length){
int reval = val;
StringBuffer bitString = new StringBuffer(length);
for(int i = length-1; i >=0; --i ){
if( reval - (Math.pow(2, i)) >= 0 ){
bitString.append("1");
reval = (int) (reval - Math.pow(2, i));
}
else{
bitString.append("0");
}
}
return bitString.toString();
}
/* public static void main(String[] args){
//System.out.println(convertIntToBitString(2046, 10));
Chromosome c = new Chromosome(1234, 10);
System.out.println(c.fitness());
}*/
}
My fitness function is f(x ) = s · (C − P(x )) + (1 − s) · P(x ) in which C is my target value to reach and P(*x ) = (Sigma) wixi, where wi is the element's set and xi is 0 or 1 (the element is chosen or not). also s is 0 or 1, depends on p(x) value. please help me to write this fitness.
I have just tried it but the program run with errors.
You have several problems in your code, and obviously you didn't debug it. Here are some tips though.
First NUM_CHROMOSOMES is 0, because it's an uninitialized field (of the GeneticAlgorithm which you don't use).
Since NUM_CHROMOSOMES is 0, this for loop is useless:
for (int i = 0; i < NUM_CHROMOSOMES; ++i) {
Then, this line:
int randomValue = (int) (Math.random() * MAX_NUMBER);
Since MAX_NUMBER is never manually initialized (same as NUM_CHROMOSOMES, its value is 0, and so is randomValue.
Anyway, population is empty and since you don't test for emptyness, this line:
Chromosome fitess = (Chromosome) population.lastElement();
... throws an exception, because there is no such thing as a last element in your empty population Vector.
As a side note, StringBuffer, Vector are obsolete classes, and you never need to import Comparable, since it belongs to the java.lang package.
The following code performs 'hierarchical' sorting of a two-dimensional matrix. Firstly, it sorts elements based on the values of ranks. Secondly, it takes this sorted matrix, searches elements that have the same values of ranks, and sorts them based on dist. In descending order.
Question 1: Is it possible to achieve the same result in the easier way? I tried to create a Comparator, but it provided incorrect result for this particular case.
Question 2: How to get indexes of unsorted elements after sorting?
import java.util.ArrayList;
public class Test {
public static void main(String args[]) {
ArrayList<ArrayList<Double>> values = new ArrayList<ArrayList<Double>>();
ArrayList<Double> ranks = new ArrayList<Double>();
ArrayList<Double> dist = new ArrayList<Double>();
ranks.add(8.0);
ranks.add(3.0);
ranks.add(8.0);
ranks.add(1.0);
dist.add(1.8);
dist.add(2.8);
dist.add(1.9);
dist.add(2.1);
values.add(0,ranks);
values.add(1,dist);
int len = ranks.size();
ArrayList<ArrayList<Double>> sortedranks = new ArrayList<ArrayList<Double>>();
sortedranks = order(values,0,ranks.size());
boolean swapped = true;
int j = 0;
double tmp1, tmp2;
while (swapped) {
swapped = false;
j++;
for (int i = 0; i < len - j; i++) {
double val1 = sortedranks.get(0).get(i);
double val2 = sortedranks.get(0).get(i+1);
if (val1==val2) {
if (sortedranks.get(1).get(i) < sortedranks.get(1).get(i+1)) {
tmp1 = sortedranks.get(1).get(i);
tmp2 = sortedranks.get(1).get(i+1);
sortedranks.get(1).remove(i);
sortedranks.get(1).remove(i);
sortedranks.get(1).add(i,tmp2);
sortedranks.get(1).add(i+1,tmp1);
swapped = true;
}
}
}
}
for (int i = 0; i < len; i++) {
System.out.println("Ranks " + i + " : " + sortedranks.get(0).get(i)
+ ", Distances : " + sortedranks.get(1).get(i));
}
}
public static ArrayList<ArrayList<Double>> order(ArrayList<ArrayList<Double>> values, int i_start, int i_fin) {
boolean swapped = true;
int j = 0;
int i_rank = 0;
int i_dist = 1;
double tmp1_rank, tmp2_rank, tmp1_dist, tmp2_dist;
while (swapped) {
swapped = false;
j++;
for (int i = i_start; i < i_fin - j; i++) {
if (values.get(i_rank).get(i) < values.get(i_rank).get(i+1)) {
tmp1_rank = values.get(i_rank).get(i);
tmp2_rank = values.get(i_rank).get(i+1);
tmp1_dist = values.get(i_dist).get(i);
tmp2_dist = values.get(i_dist).get(i+1);
values.get(i_rank).remove(i);
values.get(i_rank).remove(i);
values.get(i_dist).remove(i);
values.get(i_dist).remove(i);
values.get(i_rank).add(i,tmp2_rank);
values.get(i_rank).add(i+1,tmp1_rank);
values.get(i_dist).add(i,tmp2_dist);
values.get(i_dist).add(i+1,tmp1_dist);
swapped = true;
}
}
}
return values;
}
}
The code that uses Comparator (does not work for my case):
public class MyEntry implements Comparable<MyEntry> {
private Double rank;
private Double dist;
public MyEntry(double rank, double dist) {
this.rank = rank;
this.dist = dist;
}
public static Comparator<MyEntry> ValueComparator = new Comparator<MyEntry>() {
public int compare(MyEntry value1, MyEntry value2) {
Double rfirst = value1.rank;
Double rsecond = value2.rank;
Double dfirst = value1.dist;
Double dsecond = value2.dist;
if (rsecond != rfirst) {
return (int) (rsecond - rfirst);
}
else {
return (int) (dsecond - dfirst);
}
}
};
}
Your Comperator approach would work, but is has a few bugs.
First of all I would replace the Doubles in MyEntry by double.
Comparing Double is not the same as comparing double
For example:
Double a = 1.0;
Double b = 1.0;
System.out.println(a == b);
System.out.println(a.equals(b));
System.out.println(a.doubleValue()== b.doubleValue());
Will return
false
true
true
Then in the comparison you cast to int, but this implies flooring that data.
(int) (2 - 1.9) will give 0
Better is to compare using < and return -1 or 1.
public static Comparator<MyEntry> ValueComparator = new Comparator<MyEntry>() {
public int compare(MyEntry value1, MyEntry value2) {
double rfirst = value1.rank;
double rsecond = value2.rank;
double dfirst = value1.dist;
double dsecond = value2.dist;
if (rsecond != rfirst) {
return rsecond < rfirst?-1:1;
}
else if(dsecond!=dfirst){
return dsecond < dfirst ?-1:1;
}
return 0;
}
}
For your second question you require an index. This could be done in two ways. First option is to include the index in MyEntry like this:
public class MyEntry implements Comparable<MyEntry> {
private double rank;
private double dist;
private int index;
private static int nextIndex = 0;
public MyEntry(double rank, double dist) {
this.rank = rank;
this.dist = dist;
this.index = nextIndex++;
}
This way you will be able to retain the index but it is not so flexible.
A more flexible approach could be to have the index in a separate array, and sort that.
class IndexedArrayComparator implements Comparator<Integer>{
MyEntry[] array;
public IndexedArrayComparator(MyEntry[] entries){
this.array=entries;
}
public Integer[] createIndexes(){
Integer[] index = new Integer[array.length];
for(int i =0;i<index.length;i++){
index[i]=i;
}
return index;
}
public int compare(Integer i0, Integer i1) {
double rfirst = array[i0].rank;
double rsecond = array[i1].rank;
double dfirst = array[i0].dist;
double dsecond = array[i1].dist;
if (rsecond != rfirst) {
return rsecond > rfirst?-1:1;
}
else if(dsecond!=dfirst){
return dsecond > dfirst ?-1:1;
}
return 0;
}
}
You can then use it like this:
MyEntry[] entries = new MyEntry[5];
entries[0]= new MyEntry(1.1,5);
entries[1]= new MyEntry(1.1,4);
entries[2]= new MyEntry(2.1,5);
entries[3]= new MyEntry(0.1,3);
entries[4]= new MyEntry(3.1,1);
IndexedArrayComparator comp = new IndexedArrayComparator(entries);
Integer[] index = comp.createIndexes();
Arrays.sort(index,comp);
for(int i =0;i<index.length;i++){
MyEntry e = entries[index[i]];
System.out.println(String.format("%2d:r= %3.1f, d= %3.1f" ,index[i],e.rank,e.dist));
}
Which will give:
3:r= 0.1, d= 3.0
1:r= 1.1, d= 4.0
0:r= 1.1, d= 5.0
2:r= 2.1, d= 5.0
4:r= 3.1, d= 1.0
The second way of sorting while maintaining the index is also described here. Credits to Jon Skeet
I'm trying to convert my single dimensional array into a multidimensional array [5][7]. I know I have to convert my methods sortBySimpleInterest and displayInterest to accept a single multidimensional array instead of multiple single dimensional arrays. With making those two methods into a multidimensional array will I have to change the calculation to accept multidimensional arrays as well? I am also confused on how I should set up the SortbySimpleInterest method using the selection sort. Thanks for the help, I'm new to java
import java.util.Scanner;
public class InterestCalculatorBatchMDA {
public static void main(String[] args )
{
int cnt = 0;
double[][] arrPrincipalAmt = new double[5][7];
double[][] arrInterestRate = new double[5][7];
double[][] arrTerm = new double[5][7];
double[][] arrSimple = new double[5][7];
double[][] arrCompoundMonthly = new double[5][7];
double[][] arrCompoundDaily = new double[5][7];
double[][] arrCompoundWeekly = new double[5][7];
do{
arrPrincipalAmt[cnt] = getPrincipalAmount(1);
arrInterestRate[cnt] = getInterestRate(1);
arrTerm[cnt] = getTerm(1);
arrSimple[cnt] = round(calculateSimpleInterest(arrPrincipalAmt[cnt], arrInterestRate[cnt], arrTerm[cnt]),5);
arrCompoundMonthly[cnt] = round(calculateCompoundInterest(arrPrincipalAmt[cnt], arrInterestRate[cnt],arrTerm[cnt] ,12.0 ),5);
arrCompoundWeekly[cnt] = round(calculateCompoundInterest(arrPrincipalAmt[cnt], arrInterestRate[cnt], arrTerm[cnt], 52.0 ),5);
arrCompoundDaily[cnt] = round(calculateCompoundInterest(arrPrincipalAmt[cnt], arrInterestRate[cnt], arrTerm[cnt], 365.0 ),5);
cnt++;
}while (cnt < 5 && askYesNo("Enter another set of data (Yes/No):"));
displayInterest(arrPrincipalAmt,arrInterestRate,arrTerm,arrSimple,arrCompoundMonthly,arrCompoundWeekly,arrCompoundDaily,cnt);
sortBySimple(arrPrincipalAmt,arrInterestRate,arrTerm,arrSimple,arrCompoundMonthly,arrCompoundWeekly,arrCompoundDaily,cnt);
displayInterest(arrPrincipalAmt,arrInterestRate,arrTerm,arrSimple,arrCompoundMonthly,arrCompoundWeekly,arrCompoundDaily,cnt);
}
/** Round **/
public static double round(double numb1, double numb2) {
double round = ((double) Math.round(numb1*(Math.pow(10, numb2)))/(Math.pow(10, numb2)));;
return round;
}
/** Calculate Simple **/
public static double calculateSimpleInterest(double numb1, double numb2, double numb3) {
double calculateSimpleInterest = ((numb1)*(numb2/100.0)*(numb3/12.0));
return calculateSimpleInterest;
}
/** Calculate Compounded Daily **/
public static double calculateCompoundInterest(double numb1, double numb2, double numb3, double numb4 ) {
double calculateCompoundInterest = (numb1*Math.pow((1.0+((numb2/100.0)/numb4)),(numb4*(numb3/12.0))))-numb1;
return calculateCompoundInterest;
}
/** Get principal amount **/
public static double getPrincipalAmount(double numb1) {
Scanner input = new Scanner(System.in);
double numb2 = 1;
do{System.out.print("Enter Loan Amount: ");
numb2 = input.nextDouble();
if(numb2 > 0);
else{
System.out.println("Data Error: Loan amount must be greater than zero. You entered " +numb2);
}
}while (numb2 < 0);
return numb2;
}
/** Get interest rate **/
public static double getInterestRate(double numb1) {
Scanner input = new Scanner(System.in);
double numb2=1;
do{System.out.print("Enter Yearly Interest Rate (1 to 100 percent): ");
numb2 = input.nextDouble();
double getInterestRate = 0;
if (numb2 >= 0 && numb2 <= 100)
getInterestRate = numb2;
else{
System.out.println("Data Error: Interest rate must be greater than or equal to zero and less than or equal to 100. You entered " +numb2);
}
}while (numb2 <= 0 || numb2 >= 100);
return numb2;
}
/** Get term **/
public static double getTerm(double numb1) {
Scanner input = new Scanner(System.in);
double numb2=1;
do{System.out.print("Enter the Term (in months): ");
numb2 = input.nextInt();
double getTerm = 0;
if (numb2 > 0)
getTerm = numb2;
else{
System.out.println("Data Error: Loan amount must be greater than zero. You entered " +numb2);
}
}while (numb2 <= 0);
return numb2;
}
/** Sort by simple interest **/
public static void sortBySimple(double[][] arrPrincipalAmt ,double[][] arrInterestRate, double[][] arrTerm, double[][] arrSimple, double[][] arrCompoundMonthly, double[][] arrCompoundWeekly, double[][] arrCompoundDaily, double count){
for(int i = 0;i<count;i++)
{
for(int j=i+1; j<count;j++)
{
if(arrSimple[j]<arrSimple[i])
{
double temp = arrSimple[i];
arrSimple[i] = arrSimple[j];
arrSimple[j] = temp;
double temp1 = arrPrincipalAmt[i];
arrPrincipalAmt[i] = arrPrincipalAmt[j];
arrPrincipalAmt[j] = temp1;
double temp2 = arrInterestRate[i];
arrInterestRate[i] = arrInterestRate[j];
arrInterestRate[j] = temp2;
double temp3 = arrTerm[i];
arrTerm[i] = arrTerm[j];
arrTerm[j] = temp3;
double temp4 = arrSimple[i];
arrSimple[i] = arrSimple[j];
arrSimple[j] = temp4;
double temp5 = arrCompoundMonthly[i];
arrCompoundMonthly[i] = arrCompoundMonthly[j];
arrCompoundMonthly[j] = temp5;
double temp6 = arrCompoundDaily[i];
arrCompoundDaily[i] = arrCompoundDaily[j];
arrCompoundDaily[j] = temp6;
double temp7 = arrCompoundDaily[i];
arrCompoundDaily[i] = arrCompoundDaily[j];
arrCompoundDaily[j] = temp7;
}
}
}
}
/** Display Interest **/
public static void displayInterest(double[][] amt ,double[][] interest, double[][] term, double[][] simple, double[][] monthly, double[][] weekly, double[][] arrCompoundDaily, int count){
int i=0;
System.out.println("[Line #] [Principal Amount] [Interest Rate] [Term] [Simple Interest] [Compound Monthly] [Compound Weekly] [Compound Daily]");
do{
System.out.print((i+1)+" ");
System.out.print(amt[i]+" ");
System.out.print(+interest[i]+" ");
System.out.print(+ term[i]+" ");
System.out.print(+simple[i]+" ");
System.out.print(+monthly[i]+" ");
System.out.print(+weekly[i]+" ");
System.out.println(+arrCompoundDaily[i]);
i++;
}while(i < count);
}
/**ask yes or no **/
public static boolean askYesNo(String question) {
Scanner input = new Scanner(System.in);
String enteredText;
boolean isAnswerValid;
do{
isAnswerValid = false;
System.out.println(question);
enteredText = input.nextLine();
if (enteredText.length() > 0)
{
enteredText = enteredText.toUpperCase();
if(enteredText.equals("YES") || enteredText.equals("Y") || enteredText.equals("NO") || enteredText.equals("N"))
{
isAnswerValid = true;
}
}
if(isAnswerValid == false)
{
System.out.println("Please enter 'Yes' or 'No'?");
}
} while(isAnswerValid == false);
if(enteredText.equals("YES") || enteredText.equals("Y"))
{
return true;
}
return false;
}
}
If you can map a certain calculation scenario to a single structure, then the simple solution would be to use a class.
class InterestRateSource {
private Double firstFactor;
private Double secondFactor;
//etc
public InterestRateSource(Double firstFactor, Double secondFactor) {
this.firstFactor = firstFactor;
this.secondFactor = secondFactor;
};
public Double getFirstFactor() {
return this.firstFactor;
};
public Double getSecondFactor() {
return this.secondFactor;
};
};
// expand the above to account for all the variables of a single test case.
// Then simply use a List or whatever suitable collection.
List<InterestRateSource> myList = new ArrayList<InterestRateSource>();
myList.add(new InterestRateSource(5, 7));
myList.add(new InterestRateSource(3,4));
for (InterestRateSource currentRate: myList) {
// now you are iterating through the list. Do whatever calculations you need to do.
};