void recur(int i)
{
if(i==n)
return;
String sub="";
for(int j=i+1;j<n;j++)
{
sub=s.substring(i,j);
if(isPalindrome(sub))
System.out.println(sub);
}
recur(i++);
}
I am encountering a StackOverflowError at the
sub=s.substring(I,j);
statement.
s="geeks", initial value of I=0;
recur(i++);
The value of the expression i++ is the value of i at the current time; and afterwards you increment it.
As such, you are basically invoking:
recur(i);
i++;
And so you are just invoking recur again with the same parameter.
Try:
recur(++i);
Try This
public class P {
public static final String s="geeks";
static void recur(int i){
int n=6; //Size of string
if(i==n)
return;
String sub="";
for(int j=i+1;j<n;j++)
{
sub=s.substring(i,j);
//Any Function
System.out.println(sub);
}
recur(++i);
}
public static void main(String[] args) {
P.recur(0);
}
}
Related
Here are my instructions:
Write a recursive method called printStar(int n) which will print the following when n=4:
****
***
**
*
*
**
***
****
This is what I did so far:
public class Stars{
public static void main (String[] args){
printStars(4);
}
public static void printStars(int count){
if (count==0){
System.out.println("");
}
else{
System.out.print("*");
printStars(count-1);
}
}
}
My attempt only prints one line of the given number of stars. I don't know how to print multiple lines with only one call of the method. Any help is appreciated.
This one uses tail recursion, is split into helper function, and uses loop only to get the character as required.
public class JavaR {
public static void main(String[] args) {
System.out.println(star(4, new StringBuilder()));
}
public static StringBuilder star(int times, StringBuilder builder) {
return getStars(times, builder, times);
}
public static StringBuilder getStars(int currentIteration, StringBuilder builder, int times) {
if (currentIteration < -1 * times) return builder;
else if (currentIteration != 0) {
builder.append(getNTimes(Math.abs(currentIteration)));
return getStars(currentIteration - 1, builder, times);
} else {
return getStars(currentIteration - 1, builder, times);
}
}
public static String getNTimes(int count) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < count; i++) {
builder.append("*");
}
return builder.append("\n").toString();
}
}
Your program is incorrect, see the below program and analyze it -
public class Stars{
public static void main (String[] args){
printStars(4);
}
public static void printStars(int count){
if (count==0){
// System.out.println("");
}
else{
int tempCount = count;
while(tempCount>0){
System.out.print("*");
tempCount--;
}
System.out.println();
printStars(count-1);
while(tempCount<count){
System.out.print("*");
tempCount++;
}
System.out.println();
}
}
}
Explanation - I am using two while loops to print stars, first to print the start in asc order and second to print in reverse order. Using variable tempCount to get the current counter.
Try this
public static void printStars(int count){
if (count == 0){
return;
}
printStarNTimes(count);
printStars(count-1);
printStarNTimes(count);
}
private static void printStarNTimes(int n) {
for (int i = 0; i < n; i++) {
System.out.print("*");
}
System.out.println();
}
Logic is in printing star count times in the current call and when the recursive call returns.
The method needs information about the max number of *, as well as direction (is number of * increasing or decreasing)
Since the requested method signature includes only one argument, you have a few alternatives to define the additional needed information:
Use a partially recursive method like in this and this answers, or use a helper method:
public static void printStars(int count){
printStars(count, count, -1);
}
public static void printStars(int count , int max, int increment){
for(int i =0; i< count; i++) {
System.out.print("*");
}
count += increment;
if(count ==0 ) { //lower limit reached
increment = -increment;
}else {
System.out.println("");
}
if (count > max){ //upper limit reached
return;
}
printStars(count, max, increment);
}
My teacher gave me some java code and asked me to rewrite it in python. I'm not asking for help with rewriting it, but when I entered the code into my Java compiler I got this error:
Exception in thread "main" java.lang.StackOverflowError
at
java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:449)
at java.lang.StringBuilder.append(StringBuilder.java:136)
at java.lang.StringBuilder.<init>(StringBuilder.java:113)
at Permutations.perm1(Permutations.java:12)
at Permutations.perm1(Permutations.java:4)
Any help is greatly appreciated, here is the code:
public class Permutations {
public static void perm1(String s) {
perm1("", s);
}
private static void perm1(String prefix, String s){
int N=s.length();
if(N==0){
System.out.println(prefix);
}else{
for(int i=0; i<N; i++){
perm1(prefix+s.charAt(i)+s.substring(0, i)+s.substring(i+1,
N));
}
}
}
public static void perm2(String s){
int N=s.length();
char[] a = new char[N];
for(int i=0;i<N;i++){
a[i]=s.charAt(i);
perm2(a,N);
}
}
private static void perm2(char[] a, int n){
if(n==1){
System.out.println(a);
return;
}
for(int i=0; i<n;i++){
swap(a,i,n-1);
perm2(a,n-1);
swap(a,i,n-1);
}
}
private static void swap(char[] a, int i, int j) {
char c;
c=a[i];
a[i]=a[j];
a[j]=c;
}
public static void main(String[] args) {
int N=5;
String alphabet="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
String elements = alphabet.substring(0,N);
perm1(elements);
System.out.println();
perm2(elements);
}
}
There is an error in this line:
perm1(prefix+s.charAt(i)+s.substring(0, i)+s.substring(i+1,
N));
Should look like this:
perm1(prefix + s.charAt(i), s.substring(0, i) + s.substring(i + 1, N));
Compere with this code:
http://introcs.cs.princeton.edu/java/23recursion/Permutations.java.html
Stepping through the code with a debugger shows that you get a stack overflow error because of this section:
for(int i=0; i<N; i++){
perm1(prefix+s.charAt(i)+s.substring(0, i)+s.substring(i+1,N));
}
perm1 is called repeatedly, but the input doesn't change - it's always passed "abcde" with no prefix, and the result of prefix+s.charAt(i)+s.substring(0, i)+s.substring(i+1,N) is still "abcde". Since the call is recursive, and the input doesn't change with each iteration, it just repeats and takes up increasingly more space on the stack until it overflows and throws an exception.
So I need to write a method which accepts one String object and one integer and repeat that string times integer.
For example: repeat("ya",3) need to display "yayaya"
I wrote down this code but it prints one under the other. Could you guys help me please?
public class Exercise{
public static void main(String[] args){
repeat("ya", 5);
}
public static void repeat(String str, int times){
for(int i = 0;i < times;i++){
System.out.println(str);
}
}
}
You are printing it on new line, so try using this :
public static void repeat(String str, int times){
for(int i = 0;i < times;i++){
System.out.print(str);
}
}
You're using System.out.println which prints what is contained followed by a new line. You want to change this to:
public class Exercise{
public static void main(String[] args){
repeat("ya", 5);
}
public static void repeat(String str, int times){
for(int i = 0; i < times; i++){
System.out.print(str);
}
// This is only if you want a new line after the repeated string prints.
System.out.print("\n");
}
}
Change System.out.println() to System.out.print().
Example using println():
System.out.println("hello");// contains \n after the string
System.out.println("hello");
Output:
hello
hello
Example using print():
System.out.print("hello");
System.out.print("hello");
Output:
hellohello
Try to understand the diference.
Your example using recursion/without loop:
public class Repeat {
StringBuilder builder = new StringBuilder();
public static void main(String[] args) {
Repeat rep = new Repeat();
rep.repeat("hello", 10);
System.out.println(rep.builder);
}
public void repeat(String str, int times){
if(times == 0){
return;
}
builder.append(str);
repeat(str, --times);
}
}
public class pgm {
public static void main(String[] args){
repeat("ya", 5);
}
public static void repeat(String str, int times){
for(int i = 0;i < times;i++){
System.out.print(str);
}
}
}
I am a new member here, and I am also a beginner in JAVA. The thing that seems the most abstract to me is recursion, and so I have some difficulties finishing a program that should have this output if we write 3 for example:
1
12
123
12
1
Or if we write 5 for example it should print out this:
1
12
123
1234
12345
1234
123
12
1
And I can do this program with for loop, but I have to use recursion, and here is what I have done so far:
public class Aufgabe3 {
private static void printSequenz(int n) {
if(n<1){
return;
}
printMany(n);
printSequenz(n-1);
}
private static void printMany(int n){
for(int i=1;i<=n;i++){
System.out.print(i);
}
System.out.println();
}
public static void main(String[] args) {
printSequenz(5);
}
}
I would be really happy if someone would help me :).
You need to implement two recursive functions:
void printLoToHi(int n)
{
if (n < 1)
return;
printLoToHi(n-1);
printMany(n);
}
void printHiToLo(int n)
{
if (n < 1)
return;
printMany(n);
printHiToLo(n-1);
}
Then, you need to call them sequentially:
printSequenz(int n)
{
printLoToHi(n);
printHiToLo(n-1); // -1 in order to avoid printing the highest twice
}
Or in a more "symmetrical manner":
printSequenz(int n)
{
printLoToHi(n-1); // print lowest to second highest
printMany(n); // print the highest
printHiToLo(n-1); // print second highest to lowest
}
You could do it like this:
private static void printSequenz(int n) {
printSequenz(1,n, true);
}
private static void printSequenz(int current, int total, boolean goingUp) {
if(!goingUp && current<1){
return;
}
printMany(current);
if(current+1>total){
goingUp=false;
}
if(goingUp){
printSequenz(current+1,total,goingUp);
} else {
printSequenz(current-1,total,goingUp);
}
}
private static void printMany(int n) {
for (int i = 1; i <= n; i++) {
System.out.print(i);
}
System.out.println();
}
public static void main(String[] args) {
printSequenz(5);
}
public class Test {
public static void main(String args[]) {
int seq = 6;
for(int i=1; i<=seq; i++) {
System.out.println("");
int low =seq-(seq-i);
printIncreasing(i,low);
}
for(int i=seq-1; i>=1; i--) {
System.out.println("");
int low = seq-i;
printDecreasing(i,low);
}
}
public static void printIncreasing(int high, int low) {
for(int i = 1; i<=high;i++ ) {
System.out.print(i);
}
}
public static void printDecreasing(int high, int low) {
for(int i = 1; i<=high;i++ ) {
System.out.print(i);
}
}
}
class max{
public int buy;
public int sell;
public max(int n){
buy=0;
sell=0;
}
}
public class MaxProfit{
public void stock(int a[],int n){
max[] sol=new max[n/2+1];
if(n==1||n==0)
{
return;
}
int i=0,count=0;
while(i<n-1){
while((i<n-1)&&(a[i+1]<=a[i]))
i++;
if(i==n-1)
break;
//System.out.println(sol[count].buy=i++);
sol[count].buy=i++;
i++;
while((i<n)&&(a[i]>=a[i-1]))
i++;
sol[count].sell=i-1;
count++;
}
for(int k=0;k<count;k++)
System.out.println(sol[k].buy +sol[k].sell);
}
public static void main(String []args){
MaxProfit f=new MaxProfit();
int arr[]={20,100,260};
f.stock(arr,arr.length);
System.out.println("Hello World");
}
}
A Exception is coming which is exception in thread "main" java.lang.NullPointerException
at MaxProfit.stock(MaxProfit.java:15)
at MaxProfit.main(MaxProfit.java:32)
I am not able to solve this I have initialized array of max still I am getting null pointer exception Please help
You should initialize the elements of max[] sol maybe in a loop.
for(int i=0;i<sol.length;i++){
sol[i]=new max(aValue);
}
You are declaring an array (sol) but you are not filling your array with objects max. before using your array fill it first. Just add this to initialize your array:
max[] sol=new max[n/2+1];
for(int i = 0; i < sol.length; i++) {
sol[i] = new max(i /* or whatever the value that must be here */);
}
max[] sol=new max[n/2+1];
just defines and array with no (null) contents. You must put valid max objects in it. Like
max[i] = new max(/*param*/);
sol[count].buy=i++;
is throwing the NPE
public void stock(int a[],int n){
max[] sol=new max[n/2+1];
if(n==1||n==0)
{
return;
}
for (int k = 0; k < sol.length; k++) {
sol[k]= new max(k);
}
int i=0,count=0;
while(i<n-1){