Hi I'm new to java and am working on a Fraction calculator and I am unable to figure out how to get the calculator to reduce simple fractions and add mixed fractions.
Example:
Reduction: 1/2 + -5/6 = -1/3
Mixed Fractions: 4_15/16 + -3_11/16 = 1_1/4
Edit: For mixed fractions, I tried to subtract the numerator from the denominator for num>den to get the whole and the remainder and return it and print but it's not printing out anything.
import java.util.Scanner;
public class Fraction {
public static void main(String[] args) {
System.out.println("Enter an Expression or quit:");
Scanner input = new Scanner(System.in);
String text = input.nextLine();
while (!text.equals("quit")){
String frac1 = text.substring(0,text.indexOf(" "));
String oper = text.substring((text.indexOf(" "))+1,(text.indexOf(" "))+2);
String frac2 = text.substring((text.indexOf(" "))+3);
int fn1 = num(frac1); //frac1 numerator
int fd1 = den(frac1); //frac1 denominator
int fn2 = num(frac2); //frac2 numerator
int fd2 = den(frac2); //frac2 denominator
if (oper.equals("+")){
int sumfinalnum = add(fn1, fd1, fn2, fd2);
if (fd1 == 1 && fd2 == 1){
System.out.println(sumfinalnum);
}
else if ((fn1 + fn2)==0){
System.out.println("0");
}
else if (fd1 == fd2){
if (sumfinalnum>fd1){
System.out.println(extractWholePart(sumfinalnum,fd1)+"_"+extractNumPart(sumfinalnum,fd1)+"/"+fd1);
}
else{
System.out.println(sumfinalnum+"/"+fd1);
}
}
else if (!(fd1 == fd2)){
System.out.println(sumfinalnum+"/"+(fd1*fd2));
}
System.out.println("Enter an Expression or quit:");
text = input.nextLine();
}
}
}
public static int num(String input){
if (input.contains("_")){ //mixed to improper
String a = input.substring(0,input.indexOf("_"));
String b = input.substring((input.indexOf("_"))+1,input.indexOf("/"));
String c = input.substring((input.indexOf("/"))+1);
int a1 = Integer.parseInt(a);
int b1 = Integer.parseInt(b);
int c1 = Integer.parseInt(c);
int d = a1*c1;
int e = d+b1;
return e;
}
else if (!input.contains("/")){
int input1 = Integer.parseInt(input);
return input1;
}
else {
String strnum1 = input.substring(0,input.indexOf("/"));
int num1 = Integer.parseInt(strnum1);
return num1;
}
}
public static int den(String input){
if(!input.contains("/")) { //whole
return 1;
}
String strnum2 = input.substring((input.indexOf("/"))+1);
int num2 = Integer.parseInt(strnum2);
return num2;
}
public static int add(int fn1,int fd1,int fn2,int fd2){
if (fd1 == fd2){ //matching denominator
int numadd = fn1 + fn2;
return numadd;
}
else if (fd1 == 1 && fd2 == 1){ //whole numbers no denom
int sum = fn1 + fn2;
return sum;
}
else if (!(fd1 == fd2)){ //different denominator***
int dencomadd = fd1*fd2;
int gcd1 = dencomadd/fd1;
int gcd2 = dencomadd/fd2;
int comf1num = fn1*gcd1;
int comf2num = fn2*gcd2;
int total = comf1num+comf2num;
return total;
}
else{
return 0;
}
}
public static int extractWholePart(int finalnum, int finalden){
int whole = 0;
while (finalnum > finalden){
whole++;
}
return whole;
}
public static int extractNumPart(int finalnum, int finalden){
while (finalnum > finalden){
finalnum -= finalden;
}
return finalnum;
}
}
Let's start with - It's java, don't be afraid to use bigger variable names. fn1 could very well be called fraction1Numerator.
Next, have a single method to do what it's designed to do. Having an add method that needs four else-ifs in main is not a really good idea.
Creating an object Fraction that would have member variables numerator and denominator would allow your add function to return the entire answer. After all you have the code to add mixed fractions that looks good.
class Fraction{
public int whole;
public int numerator;
public int denominator;
}
I also added "whole" to indicate whole part after simplification. add function would than have signature
public static Fraction add(Fraction fraction1, Fraction fraction2) ...
Extracting whole numbers is simple - subtract denominator from numerator until you can't do that anymore.
public void extractWholePart(Fraction fraction){
int whole = 0;
while (fraction.numerator > fraction.denominator){
whole++;
fraction.numerator -= fraction.denominator;
}
fraction.whole = whole;
}
simplification on the other hand is just dividing both nominator and denominator by the greatest common divisor - algorythm for calculating that is easily findable on the internet.
Try something like this
float mixedToDecimal(String data)
// data would be like this "1 5/8";
String[] parts = data.split(" ");
if(!(parts.lenght > 0)) // this mean that if data is NOT mixedfraction then just return -1
return -1;
float value = Integer.parseInt(parts[0]);
if (parts.length > 1) {
// has fractional part
parts = parts[1].split("/");
float numerator = Integer.parseInt(parts[0]);
float denominator = Integer.parseInt(parts[1]);
value += numerator / denominator;
}
// value contains 1.625
return value;
Related
Problem Statement: Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
My Solution:
class Solution7{
public int reverse(int x) {
if(x>Integer.MAX_VALUE || x<Integer.MIN_VALUE) {
return 0;
}
StringBuilder S_rev = new StringBuilder();
String S_r_v=S_rev.append(Math.abs(x)).reverse().toString();//.toString() String builder to String
double reverse_no=Double.parseDouble(S_r_v);
if (x < 0) {
return -(int)reverse_no;
}
return (int)reverse_no;
}
}
My Solution is ok for most of the test case. But it cannot pass one test case and I got a error
Error: Line 10: java.lang.NumberFormatException: For input string: "8463847412-"
If someone know what type of error it is please discuss.
Thank you in advance.
It seems like you are trying to pass in Integer.MIN_VALUE
When you pass in the minimum integer value, Math.abs seems to return a negative number as stated here
https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#abs-int-
Note that if the argument is equal to the value of Integer.MIN_VALUE, the most negative representable int value, the result is that same value, which is negative.
You can either check for x<=Integer.MIN_VALUE and return 0 if x is Integer.MIN_VALUE or handle the special case for Integer.MIN_VALUE
if(x== Integer.MIN_VALUE)
return -8463847412;
By converting number to String and reversing the sign symbol ended up on the end of the value. This makes the number invalid.
You don't have to convert to String or double. You can use module operator % to extract digits:
public int reverse(int x) {
long result = 0;
while (x != 0) {
result *= 10;
result += x % 10;
x /= 10;
}
if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
throw new IllegalArgumentException(); // overflow
}
return result;
}
If you necessarily want to implement it using StringBuilder, here it is:
public static void main(String[] args) {
ReverseNum reverseNum = new ReverseNum();
System.out.println(reverseNum.reverse(-123));
System.out.println(reverseNum.reverse(123));
System.out.println(reverseNum.reverse(0));
}
public int reverse(int x) {
int res = 1;
String xStr = String.valueOf(x);
StringBuilder builder = null;
if (xStr.startsWith("-")) {
builder = new StringBuilder(xStr.substring(1));
res = -1;
} else {
builder = new StringBuilder(xStr);
}
return res * Integer.valueOf(builder.reverse().toString());
}
Output:
-321
321
0
P.S. If you want to avoid integer overflow, then you can simply use long instead of int, like this:
public long reverse(int x) {
long res = 1;
String xStr = String.valueOf(x);
StringBuilder builder = null;
if (xStr.startsWith("-")) {
builder = new StringBuilder(xStr.substring(1));
res = -1;
} else {
builder = new StringBuilder(xStr);
}
return res * Long.valueOf(builder.reverse().toString());
}
public class ReverseString {
public static void main(String args[]) {
ReverseString rs = new ReverseString();
System.out.println(rs.reverse(-84638));
System.out.println(rs.reverse(5464867));
}
public long reverse(int number) {
boolean isNegative = number < 0;
StringBuilder reverseBuilder = new StringBuilder();
String reversedString = reverseBuilder.append(Math.abs(number)).reverse().toString();
long reversedStringValue = Long.parseLong(reversedString);
if(isNegative) {
return reversedStringValue * -1;
} else {
return reversedStringValue;
}
}
}
This code provides the output you have mentioned in the requirement. And It also supports for integer overflow. Your requirement is to convert int values. It is okay to get the converted value in the higher format since converted value may not be in the range of int. I have changed the reverse method return type to long.
I have identified a few issues in your code.
public int reverse(int x) {
if(x>Integer.MAX_VALUE || x<Integer.MIN_VALUE) {
return 0;
}
Above code segment, not point of checking whether the value is inside the int range because it is already received in the param as a string. It should throw an error before executing your code lines since it is not able to fit the larger value to int variable.
Finally, the int number you have used is not in the int range. (-8463847412)
What about this?
public class ReverseNumber {
public static void main(String[] args) {
System.out.println(reverse(123456));
System.out.println(reverse(0));
System.out.println(reverse(-987654));
}
private static int reverse(int i) {
final int signum;
if(i < 0) {
signum = -1;
} else {
signum = +1;
}
int reversedNumber = 0;
int current = Math.abs(i);
while(0 < current) {
final int cipher = current % 10;
reversedNumber = Math.addExact(Math.multiplyExact(reversedNumber, 10), cipher);
current = current / 10;
}
return signum * reversedNumber;
}
}
Output:
654321
0
-456789
This solution avoids strings and can handle negative numbers.
It throws an Arithmetic exception if an integer overflow happens.
Actually my aim is to find the super no for eg i will be given 2 values n,k where n=148 and k =3 so i have to form p = 148148148 then add digits of p until i get a single no (ans = 3) this is what i have tried.......
import java.util.*;
public class RecurrsiveDigitSum {
public int check(int n) {
int s = 0;
int d;
while(n>0) {
d = n%10;
s = s+d;
n = n/10;
System.out.println(s);
}
if(s/10 !=0){
check(s);
}
return s;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int k = scan.nextInt();
int sum;
RecurrsiveDigitSum obj = new RecurrsiveDigitSum();
sum = obj.check(n);
System.out.println(sum);
sum = sum * k;
System.out.println(sum);
int s1 = obj.check(sum);
System.out.println(s1);
}
}
but the problem here is that even if my s = 4 finally its just returning the first value of s that has been found so pls help me friends
you must put return before recursive calling.
if(s/10 !=0){
return check(s);
}
If you don't put it, the result of calling function will be loss and the result of s will be returned instead of check(s).
I've improved your solution little bit.
public int check(int n) {
int s = 0;
while(n>0) {
s += n%10;
n /= 10;
}
if(s/10 != 0){
return check(s);
}
return s;
}
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 7 years ago.
I'm learner of Java.
I'm trying to convert decimal to fraction using BigInteger in Rational class.
If I print the numerator and denominator, right output comes out.
However, when I add, subtract, multiply, and divide, some strange output come out.
For example when I inputs
3.25 -3
The output is
13 4
-3 1
RationalTest#14ae5a5
RationalTest#7f31245a
RationalTest#6d6f6e28
RationalTest#135fbaa4
What is wrong with my code? What is that hashcode?
I couldn't find out in the internet, so I need your help:<
import java.util.Scanner;
import java.math.*;
public class TestTest
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
RationalTest r1 = RationalTest.getFraction(sc.next());
RationalTest r2 = RationalTest.getFraction(sc.next());
//Test if the right numerator and denominator comes out
System.out.println(r1.getNumerator()+" "+r1.getDenominator());
System.out.println(r2.getNumerator()+" "+r2.getDenominator());
System.out.println(r1.add(r2));
System.out.println(r1.subtract(r2));
System.out.println(r1.multiply(r2));
System.out.println(r1.divide(r2));
}
}
class RationalTest extends Number implements Comparable<RationalTest>
{
private static final long serialVersionUID = 1L;
private BigInteger numerator = BigInteger.ZERO;
private BigInteger denominator = BigInteger.ONE;
public RationalTest()
{
this(BigInteger.ZERO, BigInteger.ONE);
}
//Find GCD of numerator and denominator
public RationalTest(BigInteger numerator, BigInteger denominator)
{
BigInteger gcd = gcd(numerator, denominator);
this.numerator = ((denominator.compareTo(BigInteger.ZERO)>0) ? new BigInteger("1"):new BigInteger("-1")).multiply(numerator.divide(gcd));
this.denominator = denominator.abs().divide(gcd);
}
//Converting decimal to fraction
public static RationalTest getFraction(String s)
{
int result=-1;
for(int i=0; i<s.length(); i++)
{
if(s.charAt(i)=='.')
{
result=1;
break;
}
else
result=0;
}
//If result=1, String s is a decimal
if(result==1)
{
double d = Double.parseDouble(s);
long num = (long) Math.floor(d); // Only the int part
double denom = d-num; // Only the decimal part
int digitDec = s.length()-1-s.indexOf('.');
long up = (int) (denom*Math.pow(10, digitDec)); // numerator of denom
long down = (int) Math.pow(10, digitDec); // denominator of denim
return new RationalTest(BigInteger.valueOf(down*num+up), BigInteger.valueOf(down));
}
//If result=0, String s is not a decimal
else
{
return new RationalTest(BigInteger.valueOf(Long.parseLong(s)), BigInteger.ONE);
}
}
private static BigInteger gcd(BigInteger n, BigInteger d)
{
BigInteger n1 = n.abs();
BigInteger n2 = d.abs();
BigInteger gcd = BigInteger.ONE;
for(BigInteger k=BigInteger.ONE; k.compareTo(n1)<=0 && k.compareTo(n2)<=0; k=k.add(BigInteger.ONE))
{
if(n1.mod(k).equals(BigInteger.ZERO) && n2.mod(k).equals(BigInteger.ZERO))
gcd = k;
}
return gcd;
}
public BigInteger getNumerator()
{
return numerator;
}
public BigInteger getDenominator()
{
return denominator;
}
public RationalTest add(RationalTest secondRationalTest)
{
BigInteger n = (numerator.multiply(secondRationalTest.getDenominator())).add(denominator.multiply(secondRationalTest.getNumerator()));
BigInteger d = denominator.multiply(secondRationalTest.getDenominator());
return new RationalTest(n, d);
}
public RationalTest subtract(RationalTest secondRationalTest)
{
BigInteger n = (numerator.multiply(secondRationalTest.getDenominator())).subtract(denominator.multiply(secondRationalTest.getNumerator()));
BigInteger d = denominator.multiply(secondRationalTest.getDenominator());
return new RationalTest(n, d);
}
public RationalTest multiply(RationalTest secondRationalTest)
{
BigInteger n = numerator.multiply(secondRationalTest.getNumerator());
BigInteger d = denominator.multiply(secondRationalTest.getDenominator());
return new RationalTest(n, d);
}
public RationalTest divide(RationalTest secondRationalTest)
{
BigInteger n = numerator.multiply(secondRationalTest.getDenominator());
BigInteger d = denominator.multiply(secondRationalTest.getNumerator());
return new RationalTest(n, d);
}
#Override
public boolean equals(Object other)
{
if((this.subtract((RationalTest)(other))).getNumerator().equals(BigInteger.ZERO))
return true;
else
return false;
}
#Override
public int intValue()
{
return (int)doubleValue();
}
#Override
public float floatValue()
{
return (float)doubleValue();
}
#Override
public double doubleValue()
{
double x = this.getNumerator().doubleValue();
double y = this.getDenominator().doubleValue();
return x/y;
}
#Override
public long longValue()
{
return (long)doubleValue();
}
#Override
public int compareTo(RationalTest o) {
if(this.subtract(o).getNumerator().compareTo(BigInteger.ZERO)>0)
return 1;
else if(this.subtract(o).getNumerator().compareTo(BigInteger.ZERO)<0)
return -1;
else
return 0;
}
}
Oh I found out that I have to return string using toString()..
Thanks for your help!
I want to convert String input into int using recursion. This is the code I came up with but if my input is 123456 it only returns 124. If I enter 1234567, it gives an error.
import java.util.*;
public class Problem1 {
static int x =0;
static int counter = 0;
//input
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
String s= scan.nextLine();
System.out.println(recursive(s));
}
//recursive method
public static int recursive(String s){
if(s.length()==1){
x=(x*10)+ Integer.parseInt(s.substring(0,1));
return x;
}
else{
x = (x*10)+Integer.parseInt(s.substring(0,1));
counter++;
return recursive(s.substring(counter,s.length()-1));
}
}
}
import java.util.Scanner;
public class Problem1 {
static int x = 0;
static int counter = 0;
// input
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
System.out.println(recursive(s));
}
// recursive method
public static int recursive(String s) {
if (s.length() == 1) {
x = (x * 10) + Integer.parseInt(s.substring(0, 1));
return x;
} else {
x = (x * 10) + Integer.parseInt(s.substring(0, 1));
counter++;
return recursive(s.substring(1, s.length()));
}
}
}
Look at your static counter variable. You are incrementing it every time. But you only want to have the substring starting at 1 (so cut off the first "letter").
So instead of using:
counter++;
return recursive(s.substring(counter,s.length()-1));
consider using:
return recursive(s.substring(1)); // you even don't really need the length
Because the String s parameter is as follows:
1st call: 1234567
2nd call: 234567
3rd call: 34567
4th call: 4567
...
So, you only have to cut off the first letter.
Btw: your sample "project" is a really funny one ;)
A few notes to start:
If you're doing recursion, you probably don't want to use a member variable. It's not wrong to do so, but not really typical of the pattern (your x variable).
It's often handy to pass in state through the recursion, although you wouldn't have to (that is, current value of x).
Your case is a little odd because you have to change your current parse value for every sub-parse (shifting by 10 each time); makes it a little more complicated.
If you are going to keep x as a member variable (which does seem to make sense in this case), you don't need to return anything from recursive.
Can you really not just use Integer.parseInt()?
Code could be much more simple, something like:
void recursive (String s)
{
if (s.length() == 0) return 0;
x = x * 10 + Integer.parseInt(s.substring(0, 1));
recursive(s.substring(1));
}
recursion("1234567", 0, 1)
The above code will turn the string "1234567" into an int using recursion. You must pass the string you want to convert, and then 0 and 1.
public static int recursion(String s, int result, int place) {
result += place * Integer.parseInt(s.charAt(s.length() - 1) + "");
if(s.length() == 1) {
return result;
}
else {
return recursion(s.substring(0, s.length() - 1), result, place * 10);
}
}
public static int computeStr(String str) {
if (str.equals("")) {
return 0;
}
int x = 1;
for (int i = 0; i < str.length() - 1; i++) {
x = x * 10;
}
x = x * Integer.parseInt(str.substring(0, 1));
return x + computeStr(str.substring(1));
}
For example: "2432" is (2 * 1000) + (4 * 100) + (3*10) + (2*1) = 2432
this algorithm begins at first position (2) from 2432
I know its kind of a late response but you could try something like this :-
private static int stringToInt(String string) {
if (string.length() == 0) {
return 0;
}
int rv;
int num = string.charAt(string.length() - 1) - '0';
String restOfTheString = string.substring(0, string.length() - 1);
rv = stringToInt(restOfTheString) * 10 + num;
return rv;
}
Try something like this:
Subtracting the ASCII code of the '0' character from your character returns an integer:
public class StringRecursion {
static int counter = 0;
public static void main(String[] args) {
System.out.println(convertStringToInt("123456"));
}
public static int convertStringToInt(String input) {
if (input.length() == 1)
return input.charAt(0) - '0';
int value = convertStringToInt(input.substring(0, input.length() - 1));
counter++;
return value * 10 + input.charAt(counter) - '0';
}
}
Try it like this :
public static int conStrToInt(String str) {
if(str.length()==0)
{
return 0;
}
char cc = str.charAt(0);
String ros = str.substring(1);
int factor=1;
for(int i=0;i<str.length()-1;i++)
factor*=10;
factor=factor*(cc-'0');
return factor+conStrToInt(ros);
}
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.
};