Print my recursive factorial result - java

I need to print my final answer for my method. However, it shows the whole calculation to the end! How can I eliminate the process to get only the result?

Instead, call your method from another one and only print the final value:
System.out.println(getFactorial(5));
If you really need to do it from inside the method you can create a sort of "trampoline" method, like so:
private static int getFactorial(int userInput) {
int fact = _getFactorial(userInput);
System.out.println(fact);
return fact;
}
private static int _getFactorial(int userInput) {
// real implementation
}

This is a recursive function call, which is executed in all the cases without special condition checks.
printing from another method is a good option.
private static int getFactorial(int userInput){
int ans = userInput;
if(userInput >1 ){
ans*= (getFactorial(userInput-1));
}
return ans;
}
// New method;
private static void printFactorial(int userInput){
System.out.println("The value of " + userInput + "! is " + getFactorial(userInput));
}

// Calculate the factorial value
private static int getFactorial(int userInput){
int ans = userInput;
if(userInput >1 ){
ans*= (getFactorial(userInput-1));
}
return ans;
}
and print outside the function
System.out.println("The value of "+ b +"! is "+ getFactorial(b));
Print only once, when you got the final answer.

Since you don't like the idea of just returning a value and printing from the caller code, you can add a "print the answer" flag as an argument:
// Calculate the factorial value
private static int getFactorial(int value, boolean print){
if (value > 1) {
value *= getFactorial(value-1, false);
if (print) {
System.out.println("The value of "+ b +"! is "+ value);
}
}
return value;
}
Personally, though, I'd prefer the "trampoline method" of Jake King's answer.

// Calculate the factorial value
private static int getFactorial(int userInput){
int ans = userInput;
if(userInput >1 ){
ans*= (getFactorial(userInput-1));
//System.out.println("The value of "+ b +"! is "+ ans);
}
return ans;
}
public static void main(String[] args)
{
int ans;
//get input
ans = getFactorial(input);
System.out.println("The value of "+ b +"! is "+ ans);
}

Related

Get int variables within a String method Java

This is homework. Just going to put that out there. I feel it is best to show my code first and explain what I'm attempting to do
import java.util.Scanner;
public class Question1 {
public static void main(String[] args){
int length, odd, even, largest;
int n = getNumber();
length=odd=even=largest=initialize();
String sequence=createSequence(n, largest, odd, even, length);
displaySequence(sequence);
displayStatistics(largest, length, odd, even);
}
private static int getNumber(){
Scanner kb = new Scanner(System.in);
System.out.println("Enter the value of the number: ");
int number = kb.nextInt();
return number;
}
private static int initialize(){
return 0;
}
public static String createSequence(int n, int largest, int odd, int even, int length){
String sequence="";
sequence+=n+" ";
while (n!=1){
n = (n%2==0) ? n/2 : 3*n+1;
System.out.print(", "+n);
sequence+=n+" ";
if(n%2==0){ even++;
}else{ odd++;}
if(n>=largest){ largest = n;
}
length++;
}
return sequence;
}
private static void displaySequence(String sequence){
System.out.println(sequence);
}
public static String displayStatistics(int length, int even, int odd, int largest){
String nil = "";
System.out.println("The largest number in the sequence was "+largest);
System.out.println("The length of the sequence was "+length);
System.out.println("There were "+odd+" odd numbers");
System.out.println("There were "+even+" even numbers");
return nil;
}
}
I need attempting to display the largest number in the sequence, the length of the sequence, how many even numbers there were in the sequence and how many odd numbers there were in the sequence. But since I cannot return an int value in the createSequence method, I cannot get the new values for each statistic. Preventing me from displaying said statistics. How would I access these new variables to be used in the final method?
Note:
Requirements:
Declare variables in main
Initialize variables in Initialize()
createSequence (Create the sequence)
displaySequence (Then display the sequence in a separate method)
finally displayStatistics i.e. length, evens, odds, largest (in its own method), this is the one that's troubling me
Try reimplementing your code off of my basecode
public class Question{
public class NumberStats {
int len;
boolean isOdd;
}
private ArrayList<NumberStats> stats = new ArrayList<>();
public static void main(String[] args){
Question q = new Question();
Scanner kb = new Scanner(System.in);
String number = "";
do {
System.out.println("Enter a series of numbers or q to quit: ");
number = kb.next();
q.stats.add(q.parseNumber(number));
} while (number.equals("q")==false);
q.printSummary();
}
private void printSummary(){
int oddCount = 0;
int evenCount = 0;
int longestNumber = 0;
for (NumberStats s : stats){
if (longestNumber<s.len){
longestNumber = s.len;
}
if (s.isOdd){
oddCount+=1;
} else {
evenCount+=1;
}
}
System.out.println(String.format("Longest number length was : %i, Odd Numbers: %i, Even Numbers: %i",longestNumber,oddCount,evenCount));
}
private NumberStats parseNumber(String number){
NumberStats stats = new NumberStats();
Integer lastNumber = Integer.parseInt(String.valueOf(number.charAt(number.length()));
stats.isOdd = true;
if (lastNumber%2==0){
stats.isOdd = false;
}
stats.len = number.length();
return stats;
}
}
Your teacher may be a bit more impressed if you created a Sequence class. The class attributes would be the stats (which could be accessed via getter methods). The createSequence method would become the constructor. And you could implement a toString method to return a string representation of the contents.

Java return (value) error

I tried different things in my code, but I always get errors.
The instructions for the program is that I need to have a function (besides from main) that receives arguments for an array of integer values and a second argument telling the desire value to look in the array by the user.
It must also return how many times the desire value is repeated on the array.
The errors are related to the counter and also some are in the main function.
I think I am not returning the counter value correctly.
This is my current code:
import java.util.Scanner;
import java.util.Arrays;
public class ArregloBusqueda2
{
static int findRepetition(int listOfValues[], int targetValue, int counter)
{
int i;
boolean found = false;
for(i=0; i<listOfValues.length; i++)
{
while((counter < listOfValues.length))
{
if(listOfValues[i] == targetValue)
{
counter = counter + 1;
}
}
}
return counter;
}
public static int main(String[] args)
{
Scanner input = new Scanner (System.in);
int targetValue;
int listOfValues[] = {1,6,3,8,5,8,3,4,8,3};
System.out.println("Please enter the desire number to look for: ");
targetValue=input.nextInt();
findRepetition(targetValue, counter);
if(counter != 0)
{
System.out.println("The frequency of the number " + targetValue + " is: " + counter);
}
else
{
System.out.println ("The number " + targetValue + " is not contained in the array list");
}
}
}
Multiple issues in your code.
public static int main(String[] args) should be public static
void main(String[] args)
findRepetition takes three arguments,
but you are passing two agruments
counter variable is not declared
Logical flaw, while((counter < listOfValues.length)) will keep on executing if counter value is less than listOfValues.
static int findRepetition(int listOfValues[], int targetValue) {
int i;
int counter = 0;
for (i = 0; i < listOfValues.length; i++) {
if (listOfValues[i] == targetValue) {
counter = counter + 1;
}
}
return counter;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int targetValue;
int listOfValues[] = { 1, 6, 3, 8, 5, 8, 3, 4, 8, 3 };
System.out.println("Please enter the desire number to look for: ");
targetValue = input.nextInt();
int counter = findRepetition(listOfValues, targetValue);
if (counter != 0) {
System.out.println("The frequency of the number " + targetValue + " is: " + counter);
} else {
System.out.println("The number " + targetValue + " is not contained in the array list");
}
}
You made your method accept three parameters.
static int findRepetition(int listOfValues[], int targetValue, int counter)
Ask yourself - do you want to "pass in a counter", or only return it? The instructions say the latter.
When you call this method, you are not providing the correct inputs.
findRepetition(targetValue, counter);
What about the listOfValues? You want to findReptition on listOfValues for targetValue, right? So provide the correct parameters into that method call.
Again, you likely do not need the counter passed-in. Because Java is always pass-by-value
Rather, you want to return counter, as you have written. You are looking for this.
int counter = findRepetition(listOfValues, targetValue);
Fixing the remainder of the code is a learning exercise.
You are not calling findRepetition() with required parameters, findRepetition method takes 3 arguments, but you are passing only 2 arguments.

Beginner to java and not sure what this means

import java.util.*;
public class decimalToBinaryTest {
public static void main(String[] args) {
int number;
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive interger");
number = in.nextInt();
if (number < 0) {
System.out.println("Not a positive interger");
}
else {
System.out.print("Convert to binary is: ");
System.out.print(binaryform(number) + ".");
}
}
private static Object binaryform(int number) {
int remainder;
if (number <= 1) {
System.out.print(number);
return null;
}
remainder = number % 2;
binaryform(number >> 1);
System.out.print(remainder);
{
return " ";
}
}
}
In the main part of a program an int variable was created. In the next part is says private static Object binaryform ( int number ). Is the int number in the Objectrelating to the variable I the main method?
Yes and no. The variable name number has nothing to do with the main method. It is a formal parameter to the method named binaryform. The parameter number only exists within the method itself. However, when binaryform is called, the actual value of the variable (or constant) used in the call becomes the value of number while the method is executing.
public class Example {
public static void main(String[] args) {
int n = 3; // the name could be "number" and no behavior would change
Object bf = binaryForm(n);
// do something with bf
}
private static Object binaryform(int number) {
// from the call above, number will have the value 3
Object o = . . .;
// generate or modify o from the value of number
return o;
}
}

Passing integer from one method to another

Trying to write a program with two methods. First one takes an integer and prints its divisors as well as the sum of its divisors, the second is a boolean function that returns if the given integer is equal to the sum of its divisors (a perfect number).
I have the first method done fine but I want to take the integer sum from it and use it in the second method, is this even possible? Iv spent about quite a while trying to research it with no success.
As usual any and all advice appreciated. Code so far is below.
import java.util.Scanner;
import java.io.*;
class arrayTest {
public static int sumFacs(int n) {
int sumDiv[] = new int[50];
int c = 0;
int sum=0;
if(n<0){
System.out.println("Sorry I dont do negatives!");
}
else {
for(int i=1; i<=n; i++){
int j = n%i;
if(j==0){
System.out.println( i + " is a divisor of " + n + "\n");
sumDiv[c] = i;
c++;
}
}
for (int i=0; i<sumDiv.length; i++){
sum += sumDiv[i];}
System.out.println("The sum of the divisors of " + n + " is: " + sum);
}
return sum;
}
public static boolean isPerfect(int n, int sum) {
boolean b = (n == sum);
if(b){
System.out.println( n + " is a perfect number.");
}
else {
System.out.println( n + " is not a perfect number.");
}
}
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a positive integer.");
int n = scanner.nextInt();
sumFacs(n);
int sumDivisors = sumFacs(n);
System.out.println(isDivisors(sumFacs(n), n));
isPerfect(n, sum);
}
}
Your sumFacs returns an integer, so you can definitely use whatever it yields in your isPerfect method. As you are doing it now, you are passing the same number to the methods. To do what you want, you will need to do something like so:
int sumFacsResult = sumFacs(n); //Take whatever value sumFacs yields, store it in sumFacsResult
System.out.println(isPerfect(sumFacsResult, n); //Take the result of sumFacs and pass it to the isPerfect method
or shorthand:
System.out.println(isPerfect(sumFacs(n), n)); //It is usually recommended to use the other approach, for readability purposed.
And your isPerfect method should be something like so:
public static boolean isPerfect(int sum, int number)
{
return sum == number;
}
your sumFacs(int n) has a return type of int and you are returning sum but where you call that method you are not setting it to anything so what you want to do is:
int foo = sumFacs(n);
isPerfect(n,foo);
and make your isperfect class
public static void isPerfect(int n, int foo)
{
if((n==foo)
{
System.out.println( n + " is a perfect number.");
}else{
System.out.println( n + " is not a perfect number.");
}
}
However this would all be easier in one class not two

Java Overloaded Methods

I am trying to use one file to create a menu in the command window. The user selects from those menu options. They are prompted to enter a number. The number is passed to two overloaded methods which determine if the number is an integer or a float. After the calculation is done the result is printed to the screen and the menu reappears. Here is the code from my two files.
MyMathOpsTest class:
import java.util.Scanner; // import Scanner class
public class MyMathOpsTest
{
//method to pause until a key is pressed
public static void pause()
{
try
{
System.out.print("Press <Enter> to continue...");
System.in.read();
}
catch (Exception e)
{
System.err.printf("Error %s%c\n",e.getMessage(),7);
}
}//end pause
public static void main( String args[] )
{
//variables to capture keyboard input
Scanner keyBd = new Scanner( System.in );
char selection;
//int selection;
do{//display menu
System.out.println( "1. Square a Number");
System.out.println( "2. Cube a Number");
System.out.println( "3. Raise a Number to a Power");
System.out.println( "4. Maximum of Three Numbers");
System.out.println( "5. Minimum of Three Numbers");
System.out.println( "6. Exit");
System.out.print( "Selection[1-6]: " );
//get menu selection
selection = keyBd.next().charAt(0);
//selection = keyBd.nextInt();
//process menu selection
switch (selection){
case '1':
MyMathOpsTest.squareTheNumber();
pause();
break;
case '2':
MyMathOpsTest.cubeTheNumber();
pause();
break;
case '3':
MyMathOpsTest.raiseTheNumber();
pause();
break;
case '4':
MyMathOpsTest.maximumNumber();
pause();
break;
case '5':
MyMathOpsTest.minimumNumber();
pause();
break;
case '6':
//recognize as valid selection but do nothing
break;
default :
System.out.printf("%c\n",7);
System.out.println("Invalid Selection");
}//end switch
}while( selection != '6');
} // end method main
public static void squareTheNumber()
{
}
public static void cubeTheNumber()
{
}
public static void raiseTheNumber()
{
}
public static void maximumNumber()
{
MyMathOps.maximum();
}
public static void minimumNumber()
{
}
} // end class MyMathOpsTest
MyMathOps class:
import java.util.Scanner;
public class MyMathOps
{
public static int square(x:Integer):Integer
{
}
public static double square(x:Double):Double
{
}
public static int cube(x:Integer):Integer
{
}
public static double cube(x:Double):Double
{
}
public static int maximum(x:Integer, y:Integer, z:Integer):Integer
{
// create Scanner for input from command window
Scanner input = new Scanner( System.in );
// obtain user input
System.out.print( "Enter three integer values separated by spaces: ");
int numberl = input.nextInt();
// read first integer
int number2 = input.nextInt();
// read second double
int number3 = input.nextInt();
// read third double
// determine the maximum value
int result = maximum( numberl, number2, number3 );
// display maximum value
System.out.println( "Maximum is: " + result );
} // end method maximum
public static double maximum(x:Double, y:Double, z:Double):Double
{
// create Scanner for input from command window
Scanner input = new Scanner( System.in );
// obtain user input
System.out.print( "Enter three floating-point values separated by spaces: ");
number1 = input.nextDouble();
// read first double double
number2 = input.nextDouble();
// read second double
double number3 = input.nextDouble();
// read third double
// determine the maximum value
double result = maximum( numberl, number2, number3 );
// display maximum value
System.out.println( "Maximum is: " + result );
} // end method maximum
public static int minimum(x:Integer, y:Integer, z:Integer):Integer
{
// create Scanner for input from command window
Scanner input = new Scanner( System.in );
// obtain user input
System.out.print( "Enter three integer values separated by spaces: ");
int numberl = input.nextInt();
// read first integer
int number2 = input.nextInt();
// read second double
int number3 = input.nextInt();
// read third double
// determine the minimum value
int result = minimum( numberl, number2, number3 );
// display minimum value
System.out.println( "Minimum is: " + result );
} // end method minimum
public static double minimum(x:Double, y:Double, z:Double):Double
{
// create Scanner for input from command window
Scanner input = new Scanner( System.in );
// obtain user input
System.out.print( "Enter three floating-point values separated by spaces: ");
number1 = input.nextDouble();
// read first double double
number2 = input.nextDouble();
// read second double
double number3 = input.nextDouble();
// read third double
// determine the minimum value
double result = minimum( numberl, number2, number3 );
// display minimum value
System.out.println( "Minimum is: " + result );
} // end method minimum
} // end class MyMathOps
This code is a combination of code I type myself and example code from my text book. This will not compile for me in jGRASP. I get these errors.
MyMathOps.java:10: <identifier> expected
public static int square(x:Integer):Integer
^
MyMathOps.java:96: ')' expected
} // end method minimum
^
2 errors
----jGRASP wedge: exit code for process is 1.
----jGRASP: operation complete.
What am I doing wrong here? I have spent hours working on this and reading in my textbook. If I do not get this right. I will get a bad grade. I need to get a good grade in this class so I can get into a top notch Computer Science University. Thanks for your help.
In the unlikely event that my instructor or any administrator from Salt Lake Community College ever comes across this question, let me make my intentions clear. This question is posted in the greatest spirit of academic honesty. I ask this question to seek general advice and help in understanding the proper way to use the Java programming language. I in no way use the work of others and represent it as my own work. I use the answers provided here as a general aid in my understanding. I do all my own work and do not copy work provided by people answering my question.
The lines like this are not valid Java syntax:
public static int square(x:Integer):Integer
public static int maximum(x:Integer, y:Integer, z:Integer):Integer
...
This looks like a UML or pseudo-code syntax. "x:Integer" is "language-agnostic" notation that means that x is an Integer type (which maps to an int or Integer object in Java). The ":Integer" at the end means that the method returns an Integer type, which you are doing correctly already.
Try changing all your method declarations to look like this:
public static int square(int x) // Or "Integer x" if you want to use the Integer class, rather than the primitive int
public static int maximum(int x, int y, int z)
....
I am guessing that you are used to Pascal (or a derivative).
public static int square(x:Integer):Integer
in Java that is
public static int square(int x)
Also since the code is inside of "MyMathOpsTest" you do not need to prefix the method calls with "MyMathOpsTest.".
Also, why call it "MyMathOps" instead of "MathOperationsTest"? Of course it is yours - it doesn't be long to me or anyone else! Pick names that have meaning, try to avoid shorthands like "Ops", unless it is common for the field you are working in (URL is a good one, "Ops" isn't).
And now for the generl programming advice for a beginner:
write a single line of code
get that line of code to compile
once that line of code compiles work on the next one
get the next line of code to compile
keep doing that until the program is done.
There is no point in making the same mistakes over and over again - all you get good at is making mistakes, and that isn't much fun.
So to get you started...
Step 1:
public class MathOperations
{
public static int maximum(final int x, final int y, final int z)
{
}
}
(compile the above code)
Step 2:
public class MathOperations
{
public static int maximum(final int x, final int y, final int z)
{
final Scanner input;
}
}
(compile the above code)
Step 3:
public class MathOperations
{
public static int maximum(final int x, final int y, final int z)
{
final Scanner input;
intput = new Scanner(System.in);
}
}
(compile the above code)
and then keep going one line at a time. Once you get the hang of it you can do more than one line, but at the start, doing it one line at a time will show you immediately when you make a mistake. Make sure that you fix ALL of the mistakes before you move on to the next line.
Also, at the end of the first method pause(), you need another curly brace:
public static void pause()
{
try
{
System.out.print("Press <Enter> to continue...");
System.in.read();
}
catch (Exception e)
{
System.err.printf("Error %s%c\n",e.getMessage(),7);
}
}<-- this one is missing in yours
Hope this helps!
I don't know what the point of the exercise is - the math ops, the overloading, or the menu. But I'd recommend that you start over with these as your basis. At least they compile and run:
public class MyMathOps
{
public static int square(int x)
{
return x*x;
}
public static double square(double x)
{
return x*x;
}
public static int cube(int x)
{
return x*x*x;
}
public static double cube(double x)
{
return x*x*x;
}
public static int maximum(Integer... values)
{
Integer maxValue = Integer.MIN_VALUE;
for (Integer value : values)
{
if (value.compareTo(maxValue) > 0)
{
maxValue = value;
}
}
return maxValue;
}
public static double maximum(Double... values)
{
Double maxValue = Double.MIN_VALUE;
for (Double value : values)
{
if (value.compareTo(maxValue) > 0)
{
maxValue = value;
}
}
return maxValue;
}
public static int minimum(Integer... values)
{
Integer minValue = Integer.MAX_VALUE;
for (Integer value : values)
{
if (value.compareTo(minValue) < 0)
{
minValue = value;
}
}
return minValue;
}
public static double minimum(Double... values)
{
Double minValue = Double.MIN_VALUE;
for (Double value : values)
{
if (value.compareTo(minValue) < 0)
{
minValue = value;
}
}
return minValue;
}
}
and the test class (simplified):
public class MyMathOpsTest
{
public static void main(String args[])
{
Integer [] intValues = { 1, 2, 3, };
Double [] doubleValues = { 11.0, 14.0, -6.0 };
for (Integer value : intValues)
{
System.out.println("value : " + value);
System.out.println("squared: " + MyMathOps.square(value));
System.out.println("cubed : " + MyMathOps.cube(value));
System.out.println("min : " + MyMathOps.minimum(intValues));
System.out.println("max : " + MyMathOps.maximum(intValues));
}
for (Double value : doubleValues)
{
System.out.println("value : " + value);
System.out.println("squared: " + MyMathOps.square(value));
System.out.println("cubed : " + MyMathOps.cube(value));
System.out.println("min : " + MyMathOps.minimum(doubleValues));
System.out.println("max : " + MyMathOps.maximum(doubleValues));
}
}
}
When this is done running, you'll know that your methods are correct. Spare yourself the difficulties of reading in values on the first try.

Categories