So I have this basic factorial calculator in java but I am having trouble modifying it to fit the exercise. It says: Modify the factorial
method to print its local variable and recursive-call parameter. For each recursive call,display the outputs on a separate line and add a level of indentation. I think Im having trouble understanding where the print statements should go. So does local variable = number and recursion call parameter = number-1. Here is my code so far.
public class Factorial {
private static String s1="";
public static long factorial(long number,long save) {
if (number <= 1) { //test for base case
System.out.printf("%s%d! = %d*%d!= ",s1,save,save,save-1);
s1 = s1 +" ";
return 1;
}
else{ //recursion step
return number * factorial(number - 1,save);
}
}
//output factorial for values 0-21
public static void main(String[] args) {
//calculate factorials 0-21
for (int counter = 0; counter <= 21; counter++){
long x = factorial(counter,counter);
System.out.printf("%d%n",x);
}
}
}
I think Im having trouble understanding where the print statements should go.
Yes, indeed. As you can see, the exercise states
Modify the factorial method to print its local variable and recursive-call parameter.
So, modify factorial instead of main. This way, each time factorial is invoked, you get a new line printed out, just as the exercise asks.
Related
I'm trying to write a recursive method in Java to find the base 2 log for multiples of 2.
I've successfully computed the log using this recursive method.
import java.util.*;
class temp
{
static int log(int number)
{
if(number==1)
return 0;
return log(number/2)+1;
}
public static void main(String s[])
{
Scanner input=new Scanner(System.in);
System.out.println("Enter Multiple of 2:");
System.out.println("Log is:"+log(input.nextInt())); //calling log with return value of nextInt()
}
}
Where I've run aground is trying to implement the same program using a different method , a method where i start multiplying from 2 in recursive calls until it becomes equal to the given number. Here's what i've tried:
class logarithmrecursion
{
static int step=1;
static int log(int number)
{
final int temp=number;
if(number>=temp && step!=1)
return 0;
step++;
return log(number*2)+1;
}
}
During the first call, number is equal to temp so i use a step variable to prevent the execution of the termination condition.If i don't use "number" variable in the recursive call, i don't have a way to accumulate the previous product but number variable is already equal to temp and will trigger the termination condition in the next recursive call , thus always giving output 1.
What can i do to make this program work?
The first, reducing, version has a fixed termination value of 1.
But the second version's termination depends on the number, so you have to pass that into the recursive call. So, your main function calls a private recursive version:
static int log(int number) {
return log(number, 1);
}
private static int log(int number, int current) {
return current < number ? log(number, current * 2) + 1 : 0;
}
Note: Your algorithm rounds the value up. To give the (more expected) rounded down result, which agrees with (int)(Math.log(i) / Math.log(2)), use this variation:
private static int log(int number, int current) {
return current <= number / 2 ? log(number, current * 2) + 1 : 0;
}
This kind of pattern - using a wrapper function - is common where initial state of the recursion needs to setup once, but we don't want to burden the caller with having to know about what is an implementation choice.
Your first method may also be coded as one line:
static int log(int number) {
return number == 1 ? 0 log(number/2) + 1;
}
try this:
import java.util.Scanner;
public class LogTest
{
static int calLog(final int number)
{
if(number < 2) {
return 0;
}
return log(number, 2, 1);
}
static int log(final int number, final int accumulated, final int step)
{
if(accumulated >= number) {
return step;
}
return log(number, accumulated * 2, step+1);
}
public static void main(String s[])
{
Scanner input=new Scanner(System.in);
System.out.println("Enter Multiple of 2:");
System.out.println("Log is:"+calLog(input.nextInt())); //calling log with return value of nextInt()
}
}
So I'm creating a method in that is supposed to print the numbers between two specified numbers. I had it setup before in the main method but i can figure out how to make a method and call it into the main method. What my program does right now is it only prints what "int between" is equal to. I don't want anyone to just type the code out for me, i'm just looking for tips on what i should change. Last time i asked a question someone proceeded to just answer with code and it did not help me to learn anything.
So my question is what is causing the program to only display what between is equal to? I know that I need a value for the if loop to return something, but it needs to return the numbers between num1 & num2. My Professor Also said that the method needs to be "public static void Printer(int num1, int num2)" is that even possible? I kept getting an error so I switched to "int Printer".
package nortonaw_Assignment8;
public class Nortonaw_Assignment8 {
public static void main(String[] args) {
int between;
between = Printer(5, 20);
System.out.println(between);
}
public static int Printer (int num1, int num2){
int between = 0;
for (;num1<=num2; num1++);
return between;
}
}
1) There's a difference between printing out a value and returning a value.
When you"print" a value in a function, you are just writing out the value to screen or some other medium , but when you use the return statement, you are passing what you are returning to the caller of your function as well as control.
** I hope that makes sense to you?
2)"public static void Printer(int num1, int num2)" is possible.
currently your method is designed to return only one single number, so either you return a collection of numbers are you print the numbers inside Printer, in this case you can use the method signature suggested by your professor.
So I would write it like this:
public static void main(String[] args) {
Printer(5, 20);
}
public static void Printer (int num1, int num2) {
for (int i=num1;i<=num2; i++) {
System.out.println(i);
}
}
EDIT:
Note that I introduced a additional counter variable i because I think num1 and num2 should not be changed as they define the boundary of your range.
package printingTasks;
public class Printer {
public static void main(String[] args) {
printInBetween(25, 30); //Would print 26 -> 29
}
/*
* You don't need to return something if you just want to print it out to the console.
* So you can use void as return type
*/
public static void printInBetween(final int leftBoundary, final int rightBoundary){
/**
* Calculate the first number which should be printed.
* This number would be the leftBoundery plus one
* This number will be the starting point of your loop
*/
final int firstNumber = leftBoundary + 1;
// final int firstNumber = leftBoundary; //if you want to include the left boundary
for (
int currentNumber = firstNumber; //Set the counter of the the loop (currentNumber) to the first valid number
currentNumber < rightBoundary; //Run the loop while the loop counter is less than the rightBoundary
// currentNumber <= rightBoundary; //If you want to include the right boundary
currentNumber++ //Increment the loop counter with each iteration
){
/**
* In each iteration you will print the current value of the counter to the console
* Because your counter (currentNumber) will be incremented from the first valid number
* to the last number before the right boundary you will get all numbers between the two
* boundaries.
*/
System.out.println(currentNumber);
}
}
}
Your teacher wants you to print from the Printer method not directly in the main method. All the main method should be doing is calling the Printer method.
Here is the full snippit:
package nortonaw_Assignment8;
public class Nortonaw_Assignment8 {
public static void main(String[] args) {
Printer(5, 20);
}
public static void Printer (int num1, int num2) {
for (int i = num1+1;i<=num2-1; i++) {
System.out.println(i);
}
}
}
I want to write a program which reverses all the integers entered in an array but my code displayed here isn't working properly. Here is my code:
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
public static void main (String[] args) throws Exception {
//code
Scanner ss=new Scanner(System.in);
int[] arr = new int[31];
int T=ss.nextInt();
int rem,p=0;
for(int i=1;i<=T;i++){
int a=ss.nextInt();
if(a<=1000000000){
while(a!=0){
rem=a%10;
p=p*10+rem;
a=a/10;
}
System.out.println(p);
} else
System.out.println("wrong input");
}
}
}
input:
2
56
78
expected output:
65
87
actual output:
65
6578
What is wrong?
Possible solution could be
if(a<=1000000000){
p=0; // reinitialize p
while(a!=0){
rem=a%10;
p=p*10+rem;
a=a/10;
}
For better understanding just add this line System.out.println("P is :"+ p); in if and you will see why p=0; was required.
if(a<=1000000000){
System.out.println("P is :"+ p);
while(a!=0){
rem=a%10;
p=p*10+rem;
a=a/10;
}
OutPut:
2
65
P is :0
56
78
P is :56
5687
There are couple of mistakes in your code (arguably), if reviewed by peer. You are trying to print p, which is not being re-initialized. Lot of unused variables in your code are removed in this answer.
You just declared an array, but never used in your program. Not sure whether you wanted to store the user inputs in the array and once all the inputs are received, you might want to compute the reverse and display or compute the reverse and store them in your array directly. So, I just removed it
The check a <= 1000000000 I believe is to ensure that values entered are within int range. Java provides you a constant for this in Integer wrapper class, Integer.MAX_VALUE (which is 2^31 - 1)
The code was lacking modularity. Hence, I extracted it to the method reverse(int num) which takes care of computation
Importing all classes from the package is not recommended, rather import only those classes that are used in your code.
import java.util.Scanner;
public class GFG {
public static void main(String[] args) throws Exception {
Scanner ss = new Scanner(System.in);
int T = ss.nextInt();
for (int i = 1; i <= T; i++) {
int a = ss.nextInt();
if (a <= Integer.MAX_VALUE) {
a = reverse(a);
System.out.println(a);
} else {
System.out.println("wrong input");
}
}
}
private static int reverse(int num) {
int reverse = 0;
while( num != 0 ) {
reverse = reverse * 10;
reverse = reverse + num % 10;
num = num/10;
}
return reverse;
}
}
On a side note, if you look at GhostCat's answer of converting the number to String and reversing it, the approach fails for negative numbers.
Example: When user input is -51, the output would be 15-
However, it is common practice in industry to store certain long values as String. One such example is credit/debit card numbers
Probably you are just learning how to do things; thus you want to solve this problem "mathematically", but there is a different perspective in here.
It seems that you simply want to reverse the digits within any number; and you treat this as mathematical problem. But one can see this as string manipulation problem; which allows you to use existing functions to solve the problem:
int originalNumber = ....
String originalNumberAsString = Integer.toString(originalNumber);
String reversedNumberAsString = new StringBuilder(originalNumberAsString).reverse().toString();
int reversedNumber = Integer.parseInt(reversedNumberAsString);
Please note: there is also no need to check for the size of your input here; but you probably should check for >=0 (or do what is appropriate in your case for negative numbers).
I'm in a beginning programming class, and a lot of this had made sense to me up until this point, where we've started working with methods and I'm not entirely sure I understand the "static," "void," and "return" statements.
For this assignment in particular, I thought I had it all figured out, but it says it "can not find symbol histogram" on the line in the main method, although I'm clearly returning it from another method. Anyone able to help me out?
Assignment: "You see that you may need histograms often in writing your programs so you decide for this program to use your program 310a2 Histograms. You may add to this program or use it as a class. You will also write a class (or method) that will generate random number in various ranges. You may want to have the asterisks represent different values (1, 100, or 1000 units). You may also wish to use a character other than the asterisk such as the $ to represent the units of your graph. Run the program sufficient number of times to illustrate the programs various abilities.
Statements Required: output, loop control, decision making, class (optional), methods.
Sample Output:
Sales for October
Day Daily Sales Graph
2 37081 *************************************
3 28355 ****************************
4 39158 ***************************************
5 24904 ************************
6 28879 ****************************
7 13348 *************
"
Here's what I have:
import java.util.Random;
public class prog310t
{
public static int randInt(int randomNum) //determines the random value for the day
{
Random rand = new Random();
randomNum = rand.nextInt((40000 - 1000) + 1) + 10000;
return randomNum;
}
public String histogram (int randomNum) //creates the histogram string
{
String histogram = "";
int roundedRandom = (randomNum/1000);
int ceiling = roundedRandom;
for (int k = 1; k < ceiling; k++)
{
histogram = histogram + "*";
}
return histogram;
}
public void main(String[] Args)
{
System.out.println("Sales for October\n");
System.out.println("Day Daily Sales Graph");
for (int k = 2; k < 31; k++)
{
if (k == 8 || k == 15 || k == 22 || k == 29)
{
k++;
}
System.out.print(k + " ");
int randomNum = 0;
randInt(randomNum);
System.out.print(randomNum + " ");
histogram (randomNum);
System.out.print(histogram + "\n");
}
}
}
Edit: Thanks to you guys, now I've figured out what static means. Now I have a new problem; the program runs, but histogram is returning as empty. Can someone help me understand why? New Code:
import java.util.Random;
public class prog310t
{
public static int randInt(int randomNum) //determines the random value for the day
{
Random rand = new Random();
randomNum = rand.nextInt((40000 - 1000) + 1) + 10000;
return randomNum;
}
public static String histogram (int marketValue) //creates the histogram string
{
String histogram = "";
int roundedRandom = (marketValue/1000);
int ceiling = roundedRandom;
for (int k = 1; k < ceiling; k++)
{
histogram = histogram + "*";
}
return histogram;
}
public static void main(String[] Args)
{
System.out.println("Sales for October\n");
System.out.println("Day Daily Sales Graph");
for (int k = 2; k < 31; k++)
{
if (k == 8 || k == 15 || k == 22 || k == 29)
{
k++;
}
System.out.print(k + " ");
int randomNum = 0;
int marketValue = randInt(randomNum);
System.out.print(marketValue + " ");
String newHistogram = histogram (randomNum);
System.out.print(newHistogram + "\n");
}
}
}
You're correct that your issues are rooted in not understanding static. There are many resources on this, but suffice to say here that something static belongs to a Class whereas something that isn't static belogns to a specific instance. That means that
public class A{
public static int b;
public int x;
public int doStuff(){
return x;
}
public static void main(String[] args){
System.out.println(b); //Valid. Who's b? A (the class we are in)'s b.
System.out.println(x); //Error. Who's x? no instance provided, so we don't know.
doStuff(); //Error. Who are we calling doStuff() on? Which instance?
A a = new A();
System.out.println(a.x); //Valid. Who's x? a (an instance of A)'s x.
}
}
So related to that your method histogram isn't static, so you need an instance to call it. You shouldn't need an instance though; just make the method static:
Change public String histogram(int randomNum) to public static String histogram(int randomNum).
With that done, the line histogram(randomNum); becomes valid. However, you'll still get an error on System.out.print(histogram + "\n");, because histogram as defined here is a function, not a variable. This is related to the return statement. When something says return x (for any value of x), it is saying to terminate the current method call and yield the value x to whoever called the method.
For example, consider the expression 2 + 3. If you were to say int x = 2 + 3, you would expect x to have value 5 afterwards. Now consider a method:
public static int plus(int a, int b){
return a + b;
}
And the statement: int x = plus(2, 3);. Same here, we would expect x to have value 5 afterwards. The computation is done, and whoever is waiting on that value (of type int) receives and uses the value however a single value of that type would be used in place of it. For example:
int x = plus(plus(1,2),plus(3,plus(4,1)); -> x has value 11.
Back to your example: you need to assign a variable to the String value returned from histogram(randomNum);, as such:
Change histogram(randomNum) to String s = histogram(randomNum).
This will make it all compile, but you'll hit one final roadblock: The thing won't run! This is because a runnable main method needs to be static. So change your main method to have the signature:
public static void main(String[] args){...}
Then hit the green button!
For starters your main method should be static:
public static void main(String[] Args)
Instance methods can not be called without an instance of the class they belong to where static methods can be called without an instance. So if you want to call your other methods inside the main method they must also be static unless you create an object of type prog310t then use the object to call the methods example:
public static void main(String[] Args)
{
prog310t test = new prog310t();
test.histogram(1);
}
But in your case you probably want to do:
public static String histogram (int randomNum)
public static void main(String[] Args)
{
histogram(1);
}
Also you are not catching the return of histogram() method in your main method you should do like this:
System.out.print(histogram(randomNum) + "\n");
Or
String test = histogram(randomNum);
System.out.print(test + "\n");
Static methods are part of a class and can be called without an instance but instance methods can only be called from an instance example:
public class Test
{
public static void main(String[] args)
{
getNothingStatic();// this is ok
getNothing(); // THIS IS NOT OK IT WON'T WORK NEEDS AN INSTANCE
Test test = new Test();
test.getNothing(); // this is ok
getString(); // this is ok but you are not capturing the return value
String myString = getString(); // now the return string is stored in myString for later use
}
public void getNothing()
{
}
public static void getNothingStatic()
{
}
public static String getString()
{
return "hello";
}
}
Void means the method is not returning anything it is just doing some processing. You can return primitive or Object types in place of void but in your method you must specify a return if you don't use void.
Before calling histogrom (randomNum) you need to either make histogram static or declare the object that has histogram as a method
e.g
prog310t myClass = new prog310t();
myClass.histogram()
I think the constructor is logically correct, I just can't figure out how to call it in the main ! :) Can anyone help please ? If someone would just have a quick look over my code it would be nice :) Thanks a lot !
Also, I am using arrayLists in this implementation and I have to do it this way so I don't wish to change it, even though it is far more easily implemented using only arrays.
import java.util.*;
public class PrimeNumberss {
public static void main(String args []){
PrimeNumberss PrimeNumbers = new PrimeNumberss(10);
}
public PrimeNumberss (int initialCapacity) {
ArrayList<Integer> listOfPrimeNumbers = new ArrayList<Integer>(initialCapacity);
long numberOfPrimes = 0; //Initialises variable numberOfPrimes to 0
int start = 2;
boolean[] isPrimeNumber = new boolean[initialCapacity + 1];
for (int i=0;i==initialCapacity;i++) {//setting all values in array of booleans to true
isPrimeNumber[i] = true;
}
while (start != initialCapacity)
{
if (isPrimeNumber[start])
{
listOfPrimeNumbers.add(start);
//add to array list
numberOfPrimes++;
for (int i = start; start < initialCapacity; i+=start)
{
isPrimeNumber[i] = false;
}
}
start++;
}
}
}
Your algorithm is not correct; you will only find the primes less than N (your initial capacity), not the first N primes.
If you're going to store each prime, you should store them in a class variable not a variable local to the constructor. You won't be able to access them outside the constructor if you do.
You should expose the list using a getter method to provide access to them.
You're not printing anything in the constructor.
i==initialCapacity is clearly wrong.
Everything important is there, its small changes. Right now you are getting primes less than N, so if you want to change it to first N primes that's going to be a real functional difference. For now lets just make N=50 so you'll get well over 10 primes.
public class PrimeNumberss {
private List listOfPrimeNumbers; //add a member variable for the ArrayList
public static void main(String args []){
PrimeNumberss PrimeNumbers = new PrimeNumberss(50);
PrimeNumbers.print(); //use our new print method
}
public PrimeNumberss (int initialCapacity) {
listOfPrimeNumbers = new ArrayList<Integer>(initialCapacity/2); //initialCapacity/2 is an easy (if not tight) upper bound
long numberOfPrimes = 0; //Initialises variable numberOfPrimes to 0
int start = 2;
boolean[] isPrimeNumber = new boolean[initialCapacity + 1];
for (int i=0;i==initialCapacity;i++) {//setting all values in array of booleans to true
isPrimeNumber[i] = true;
}
//.... complete the constructor method as you have it. honestly, i didnt even read it all
public void print() //add this printout function
{
int i = 1;
it = listOfPrimeNumbers.listIterator();
while (it.hasNext())
{
System.out.println("the " + i + "th prime is: " + it.next());
i++;
}
//or just System.out.println(listOfPrimeNumbers);, letting ArrayList's toString do the work. i think it will be in [a,b,c,..,z] format
}
public List getPrimes() {return listOfPrimeNumbers;} //a simple getter isnt a bad idea either, even though we arent using it yet
}
On a side note, you could probably d oa little better with the naming (PrimeNumberss and PrimeNumbers??), but I didnt change any of that. Also, intiialCapacity does not reflect what it really means. Maybe something along the lines of 'top'.