multiplying int and double in recursive method - java

In the following program, the user enters a for how many hours they've worked, and b for their hourly rate, then it calculates their pay.
It was working when both a and b were type int, then I realized my teacher asked for b to be a double.
I tried changing everything for b from int to double, but now it is returning an error.
What am I doing wrong?
import java.util.Scanner;
public class Project61 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("Enter the amount of hours first and then the hourly rate");
int a=in.nextInt();
double b=in.nextDouble();
double res = mult (a, b);
System.out.println("Hours : "+ a);
System.out.println("Rate per hour : "+ "$"+ b);
System.out.println("Pay : "+ "$" +res);
}
public static double mult(int a, double b) {
if(b ==1){
return a;
}
if (b<1) {
return -a + mult(a, b+1);
}
else{
return a + mult(a, b-1);
}
}
}

The problem is that, if b is not equal to an integer (for instance, if b == 2.5), you will never get 1 by repeatedly subtracting 1 from it. So your recursive function will call itself with b == 1.5, then with b == 0.5, then again with b == 1.5, ad infinitum (or at least, ad untilum Javaum runsum outum ofum stackum memoryum). You need to create an exit case that you can guarantee will be triggered eventually.

You have to convert int a to double. You can not multiply double with integer. You could convert int a to double after input or just in
method public static double mult(int a, double b)
{
double aa = a.doubleValue();
if(b ==1)
{
return a;
}
if (b<1)
{
return -aa + mult(aa, b+1);
}
else
{
return aa + mult(aa, b-1);
}
}

Related

Why doesn't the return statement return anything in the calAverage Method

So, I have coded everything, but return statement isn't returning or printing out anything in the output. The return statement is in my calAverage method. And the output should look like this https://gyazo.com/328bcfebfb08709edbc0e62a93ada7f8 but I have everything but the calAverage output. I don't get what I did wrong. I know I have to call the method like this: sc.calAverage(a, b, c); and then assign the return value to a variable and the print it out but I don't know how to do it with the calAverage method since it has three arguments.
import java.util.Scanner;
public class SecretCode
{
//no instance variables
public SecretCode(){
}
public double calAverage(int a, int b, int c){
double average = 0.0;
//your work - step 2
average = (a + b + c) / 3.0;
return average;
}
public void decodeMe(String s1){
//your work here step 4
//This method will take in a String and then process the string to produce output withe the following rules:
// The first 5 characters are needed but must be uppercase()
// The first integer will decrease by 121
// The last number only takes the last 2 decimals
// Print out 3 lines of data as followed:
// XXXXX
// XXX
// XX
String s = "Delta 230 ATA 23.75";
s1 = s.substring(0, 5);
String s2 = s1.toUpperCase();
int wholeNumber = Integer.parseInt(s.substring(6, 9));
int finalNumber = wholeNumber - 121;
int lastNumber = Integer.parseInt(s.substring(17,19));
System.out.println(s2 + "\n" + finalNumber + "\n" + lastNumber);
}
public static void main(String args[]){
int a, b, c;
String s;
SecretCode sc = new SecretCode();
Scanner myObj = new Scanner(System.in);
System.out.println("Enter 3 numbers separated by space ");
//your work step 3
// receive 3 integer values and call calAverage() method
// print out the average
a = myObj.nextInt();
b = myObj.nextInt();
c = myObj.nextInt();
sc.calAverage(a, b, c);
//
Scanner myObj1 = new Scanner(System.in);
System.out.println("Enter a secret code below ");
//Step enter the code: Delta 230 ATA 23.75
s = myObj1.nextLine();
sc.decodeMe(s);
//
}
}
You should change
sc.calAverage(a, b, c)
to
double avg = sc.calAverage(a, b, c)
System.out.println(avg);
in your main method if you want to print the value returned by the calAverage method.
Or print the average after calculating it in the method calAverage.
public double calAverage(int a, int b, int c) {
double average = 0.0;
//your work - step 2
average = (a + b + c) / 3.0;
System.out.println(average);
return average;
}
Save the response of the function in a variable:
double averageValue = sc.calcAverage(5, 3, 2);

Java Fraction Calculator

I don't know why my fractions won't reduce. I think it's because I didn't call it but I don't know where to call it. (sorry the spacing is so bad. they never check that at school)
import java.util.*;
public class FracCalc_Egg {
public static String f1;
public static String op;
public static String f2;
public static int w1;
public static int w2;
public static int n1;
public static int n2;
public static int d1;
public static int d2;
public static void main(String[] args) {
System.out.println("Welcome to the Fraction calculator!");
Scanner console = new Scanner(System.in);
System.out.print("Enter an expression (or \"quit\"): ");
//get the first fraction, or quit
f1 = console.next();
//test fraction1 to see if the user types "quit"
if(f1.equalsIgnoreCase("quit")){
System.out.println("Goodbye!");
}
while(!f1.equalsIgnoreCase("quit")){
op = console.next();
f2 = console.next();
processFractions(f1, op, f2);
System.out.print("Enter an expression (or \"quit\"): ");
f1 = console.next();
if(f1.equalsIgnoreCase("quit")){
System.out.println("Goodbye!");
}
}//end while loop
//while loop continues the calc until the user types "quit"
}//end of main
public static void processFractions(String f1, String op, String f2){
//get int variables from fractions
//testing fraction 1 to get int values
if(f1.contains("_")){ //testing for mixed number
w1=Integer.parseInt(f1.substring(0,f1.indexOf("_")));
n1=Integer.parseInt(f1.substring(f1.indexOf("_")+1,f1.indexOf("/")));
d1=Integer.parseInt(f1.substring(f1.indexOf("/")+1));
n1=(w1*d1)+n1; //making mixed number improper
} else if(f1.contains("/")) { //testing for fraction
n1=Integer.parseInt(f1.substring(0,f1.indexOf("/")));
d1=Integer.parseInt(f1.substring(f1.indexOf("/")+1));
} else {//testing for whole number
w1=Integer.parseInt(f1.substring(0));
n1=w1;
d1=1;
}//end if, else if, else method
//testing fraction 2 to get int values
if(f2.contains("_")){ //mixed fraction
w2=Integer.parseInt(f2.substring(0,f2.indexOf("_")));
n2=Integer.parseInt(f2.substring(f2.indexOf("_")+1,f2.indexOf("/")));
d2=Integer.parseInt(f2.substring(f2.indexOf("/")+1));
n2=w2*d2+n2;
} else if(f2.contains("/")) { //fraction
n2=Integer.parseInt(f2.substring(0,f2.indexOf("/")));
d2=Integer.parseInt(f2.substring(f2.indexOf("/")+1));
} else { //whole number
w2=Integer.parseInt(f2.substring(0));
n2=w2;
d2=1;
}//end if, else if, else method
dotheMath(n1, n2, d1, d2, op);
}//end processFraction method
//dotheMath detmerines the operator
public static void dotheMath(int n1, int n2, int d1, int d2, String op) {
if(op.equals("+")){
System.out.println(add(n1, n2, d1, d2));
} else if(op.equals("-")) {
n2=-1*n2;
System.out.println(add(n1, n2, d1, d2));
} else if(op.equals("*")) {
System.out.println(multiply(n1, n2, d1, d2));
} else {
int x = n2;
int y = d2;
d2=x;
n2=y;
System.out.println(multiply(n1, n2, d1, d2));
} //end the if, else if, else statement
}//end dotheMath method
public static String add(int n1, int n2, int d1, int d2) {
int newn = (n1*d2) + (n2*d1);
int newd = d1*d2;
int divisor = reduce(newn,newd);
newn/=divisor;
newd/=divisor;
String answer = newn+"/"+newd;
return answer;
}//end add method
public static String multiply(int n1, int n2, int d1, int d2) {
int newn = n1*n2;
int newd = d1*d2;
int divisor = reduce(newn,newd);
newn/=divisor;
newd/=divisor;
String answer = newn+"/"+newd;
return answer;
}//end multiply method
public static int lcd(int n1,int d1, int n2, int d2){
int dividend=(d1*n2)+(n1*d2);
int divisor = d1*d2;
int rem = dividend % divisor;
while (rem != 0){
dividend = divisor;
divisor = rem;
rem = dividend % divisor;
}
return divisor;
} //end lcd
public static int reduce (int newn, int newd) { //
int newn_abs = Math.abs (newn);
int newd_abs = Math.abs (newd); //
int min_num = Math.min (newn_abs, newd_abs);
int divisor = 1;
for (int i = 1; i <= min_num; i++) {
if (newn%i == 0 && newd%i == 0){
divisor = 1;
}//end if
}//end for
return divisor;
}//end reduce
}//end of class
example-
Welcome to the Fraction calculator!
Enter an expression (or "quit"): 1/4 + 1_1/2
14/8
the expected output is 1_3/4
and I'm stuck right at the reduce method. someone told me in class that I didn't call that method but I don't know what they mean. They told me to call it in the add and multiply method but how/where do you do that?
When you class mates tell you, that you didn't call the reduce method, they mean, that you never use the reduce method.
Your add-method should look somewhat like this:
public static String add(int n1, int n2, int d1, int d2) {
int newn = (n1*d2) + (n2*d1);
int newd = d1*d2;
int divisor = reduce(newn, newd);
newn/=divisor;
newd/=divisor;
int integerComponent=0;
while(newn >= newd) {
integerComponent++;
newn-=newd;
}
String answer ="";
if(integerComponent>0) {
answer += integerComponent +"_";
}
if(newn!=0) {
answer += newn+"/"+newd;
}
return answer;
}
and the multiply method should look like this:
public static String multiply(int n1, int n2, int d1, int d2) {
int newn = n1*n2;
int newd = d1*d2;
int divisor = reduce(newn, newd);
newn/=divisor;
newd/=divisor;
int integerComponent=0;
while(newn >= newd) {
integerComponent++;
newn-=newd;
}
String answer ="";
if(integerComponent>0) {
answer += integerComponent +"_";
}
if(newn!=0) {
answer += newn+"/"+newd;
}
return answer;
}
Remember that you also have to change your reduce method, as it always returns 1 right now!
Edit: Added code to print fraction as mixed fraction.
Before I get to my answer, I just have one request, please, please fix your indentation. By providing newly formatted, easy to code in your question, you're much more likely to get an answer and much more likely to get a high quality answer.
Now, for my answer. This is a school project, you're supposed to learn through it. On that note, I won't give you the full answer but I will try to guide you. So, a couple of things, firstly, your friend is right, and secondly, your reduce function is incorrect. You are generating a function in two places, in your add function and in your multiply function at the line:
String answer = newn+"/"+newd;
What you have to do instead at this step is call your reduce function in
String answer = reduce(newn, newd);
Now, it's up to you to change the reduce function to properly reduce the fraction and handle improper fractions.

Using the Scanner to read the user's input, is there a way to tell what kind of data he has just typed in? (char, int,String)

In this exercise i'm being asked to create 3 functions, which are the same but are meant for different types of data:
String
static String concatenamento(String a, String b, String c) {
String d = a + b + c;
return d;
}
Int
static int sommainteri(int a, int b, int c) {
int d = a + b + c;
return d;
}
Double
static double sommadouble(double a, double b, double c) {
double d = a + b + c;
return d;
}
I'm being asked to ask the user's for input continuously, and given it's inputs the program must, (as soon as 3 inputs are given with the same data type), choose a function and execute it. End of the program.
I'm not sure this is clear, so i'll try to explain it better. Let's say that the user has just inserted, in a row, three integers (f.ex. 3, 4 and 9), the program must understand to use the function made for integers.
I have no idea how to do it. Thank you for your help :)
Checkout Scanner's hasNextInt() hasNextDouble()
Simple Example Usage:
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
if(s.hasNextInt()) {
int x = s.nextInt();
System.out.println("Is an Int: " + x);
} else if(s.hasNextDouble()) {
double x = s.nextDouble();
System.out.println("Is a Double:" + x);
} else {
String x = s.nextLine();
System.out.println("Is A String: " + x );
}
}

Concerning multiple constructors in Java

I have a question about multiple instances of a constructor in Java.
My assignment is to receive two fractions and then multiply and divide those fractions.
I am unsure as to how to go about having separate values for the instances of the class objects themselves.
Here is the sample code of where I am having the issue:
import java.util.Scanner;
public class TextLab05
{
static int num1, den1; // numerator and denominator of the 1st rational number
static int num2, den2; // numerator and denominator of the 2nd rational number
public static void main (String args[])
{
enterData();
Rational r1 = new Rational(num1,den1);
Rational r2 = new Rational(num2,den2);
}
}
class Rational
{
private int firstNum; // entered numerator
private int firstDen; // entered denominator
private int num; // reduced numerator
private int den; // reduced denominator
public Rational()
{
}
public Rational(int n, int d)
{
n = TextLab05.num1;
d = TextLab05.den1;
//Here specifically is where I am having comprehension issues. How can I include num2 and den2 if I only have int n and int d?
}
}
If this is hard to understand out of context, here is the entire starting code I was given:
import java.util.Scanner;
public class TextLab05
{
static int num1, den1; // numerator and denominator of the 1st rational number
static int num2, den2; // numerator and denominator of the 2nd rational number
public static void main (String args[])
{
enterData();
Rational r1 = new Rational(num1,den1);
Rational r2 = new Rational(num2,den2);
Rational r3 = new Rational();
r3.multiply(r1,r2);
System.out.println("\n\n" + r1.getOriginal() + " * " + r2.getOriginal() + " = " + r3.getRational());
r3.divide(r1,r2);
System.out.println("\n" + r1.getOriginal() + " / " + r2.getOriginal() + " = " + r3.getRational());
// 100 Point Version Only
// r3.add(r1,r2);
// System.out.println("\n" + r1.getOriginal() + " + " + r2.getOriginal() + " = " + r3.getRational());
// r3.subtract(r1,r2);
// System.out.println("\n" + r1.getOriginal() + " - " + r2.getOriginal() + " = " + r3.getRational());
System.out.println();
}
public static void enterData()
{
Scanner input = new Scanner(System.in);
System.out.print("\nEnter the 1st numerator ----> ");
num1 = input.nextInt();
System.out.print("\nEnter the 1st denominator --> ");
den1 = input.nextInt();
System.out.print("\nEnter the 2nd numerator ----> ");
num2 = input.nextInt();
System.out.print("\nEnter the 2nd denominator --> ");
den2 = input.nextInt();
}
}
class Rational
{
private int firstNum; // entered numerator
private int firstDen; // entered denominator
private int num; // reduced numerator
private int den; // reduced denominator
public Rational()
{
}
public Rational(int n, int d)
{
n = TextLab05.num1;
d = TextLab05.den1;
}
private int getGCF(int n1,int n2)
{
int rem = 0;
int gcf = 0;
do
{
rem = n1 % n2;
if (rem == 0)
gcf = n2;
else
{
n1 = n2;
n2 = rem;
}
}
while (rem != 0);
return gcf;
}
public int getNum()
{
return TextLab05.num1;
}
public int getDen()
{
return TextLab05.den1;
}
public double getDecimal()
{
return (double)TextLab05.num1 / TextLab05.den1;
}
public String getRational()
{
String rational = "" + TextLab05.num1 + "/" + TextLab05.den1;
return rational;
}
public String getOriginal()
{
String original = "" + TextLab05.num1 + "/" + TextLab05.den1;
return original;
}
public void reduce()
{
}
public void multiply(Rational r1, Rational r2)
{
}
public void divide(Rational r1, Rational r2)
{
}
public void add(Rational r1, Rational r2)
{
}
public void subtract(Rational r1, Rational r2)
{
}
}
When you call:
Rational r1 = new Rational(num1, den1);
Rational r2 = new Rational(num2, den2);
in the main method of your program you are creating two instances of the Rational class, one named r1 and one named r2. Because you are passing int values to the Rational constructors, the constructor that will be called is the constructor which requires two integer arguments:
public Rational(int n, int d)
{
...
}
The compiler knows this because it matches the name of the Constructor as well as the types of the arguments passed (known as matching the "signature" of the Constructor).
In the code you have provided, the Rational Constructor code doesn't really make sense - this code:
public Rational(int n, int d)
{
n = TextLab05.num1;
d = TextLab05.den1;
}
should probably look something like this:
public Rational(int n, int d)
{
this.firstNum = n;
this.firstDen = d;
}
The values n and d are passed to the constructor, and then in the body of the constructor the instance variables firstNum and firstDen (which are declared in the private part of the Rational class and effectively "belong" to the instance being created) would then be initialised to the values of n and d.
Everywhere within the body of the Rational class you should refer to the member variables firstNum and firstDen, rather than variables that do not "belong" to the class instance.
I assume the Rational class is supposed to represent a rational number. You say:
//Here specifically is where I am having comprehension issues. How can I include num2 and den2 if I only have int n and int d?
You don't need to store two numerators and two denominators in the Rational class. You just need to creat two Rational objects. One to store num1 and den1, the other to store num2 and den2. You are already doing this:
Rational r1 = new Rational(num1,den1);
Rational r2 = new Rational(num2,den2);
It does not make sense to store two numerators and two denominators in Rational. A rational number only has one of each.
In summary: r1 stores num1 and den1, while r2 stores the other two. When you create a new Rational, n and d refer to the numerator and denominator of that particular instance you are creating.
I am not sure if your implementation of Rational is what you intend, but the constructor is not limited to local varables, it can access any static variables from other classes it can access.
public Rational(int n, int d)
{
n = TextLab05.num1;
d = TextLab05.den1;
}
n and d are local variables, num1 and den1 are static variables in class TextLab05.
So you are assigning the local variables with the static values from the other class.
The code doesn't make sense, as you don't do anything with the values after assigning them to local variables that are disposed when the method ends.
The most important thing to do is understand the concept. You are going to store a rational number in your Rational class. When you do this:
Rational r1 = new Rational(num1,den1);
You are making a single instance of a Rational and naming it r1. r1 should now contain a numerator and a denominator (in this case num1 and den1).
Let's say you want to make the number one half, or 1/2. You could do this:
Rational oneHalf = new Rational(1,2);
Realize that new Rational(1,2) is calling the constructor of your Rational class. In your constructor you need to assign num and den to the passed values (in this case 1 and 2). So you would need something like this:
this.num = num1;
this.den = den1;
So if you want to have the ability to multiply one Rational with another Rational you would need a method or function to do that. In your Rational class, create a method called multiply(Rational anotherRational).
That function would do something like this:
this.num = this.num * anotherRational.num;
this.den = this.den * anotherRational.den;
I gave away half the answer, I'll let you do the rest. Don't just copy what you find here, think about what you're doing.

How to make main method calculate return value?

I wanted the user to enter the pay rate and hours worked. If the hours are 40 or below, it is to multiply the pay rate and the hours together. All of that is to happen in one method and the main method is supposed to call this. However, my program does nothing with the values.
package homework6;
import java.util.Scanner;
public class Homework6 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Enter your pay rate.");
double r = console.nextDouble();
System.out.println("How many hours did you work this week?");
int h = console.nextInt();
double T1 = getTotalPay(r, h);
}
public static double getTotalPay(double r, int h){
/*If the number of hours is less than or equal to 40, it simply
multiplies them together and returns the result.*/
if (h <= 40) {
return r*h;
}
}
}
Most likely, you simply need to print the returned value:
...
double T1 = getTotalPay(r, h);
System.out.println("Total pay: " + T1);
As a matter of style, Java variables should start with a lower letter. You should change the name T1 to t1 (or, better, to something like totalPay that is more comprehensible).
Just to clarify: the above goes inside your main() method.
If you want to be fancy, you can format the result as currency:
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Enter your pay rate.");
double r = console.nextDouble();
System.out.println("How many hours did you work this week?");
int h = console.nextInt();
double totalPay = getTotalPay(r, h);
System.out.println("Total pay: " +
NumberFormat.getCurrencyInstance().format(totalPay)
);
}
First of all, you need to print this returned value:
System.out.println(T1);
Second of all, your getTotalPay(double r, int h) method must always return something or throw an exception if the return type declared is not void. Right now it only returns something when the condition is satisfied. Did you even get this to compile? This method should look something like this:
public static double getTotalPay(double r, int h){
if (h <= 40){
return r*h;
} else {
return 0;
}
}

Categories