Printing Pattern Using Recursion
Jul 16, 2014
The program I'm working on is supposed to read input from a file and using recursion, print the pattern of asterisks for each value until the value is either < 0 or > 25.For example, if the value was 4, the pattern would look like this
*
* *
* * *
* * * *
* * *
* *
*
The values are stored in a file entitled prog3.dat which looks like this
4
3
15
26
0
I've never used recursion before and haven't been able to find anything showing how it would work with this particular type of problem.Here is what I've been able to come up with so far, but I'm having problems still which I will show following the code.
import java.util.Scanner;
import java.io.*;
public class Program3 {
public static void main(String[] args) throws Exception {
int num = 0;
java.io.File file = new java.io.File("../instr/prog3.dat");
Scanner fin = new Scanner(file);
[code]...
It appears to be reading the file correctly, but is only printing the top half of the pattern. Also, like I said, I'm not very familiar with recursion, so am not sure if this is actually recursion?
View Replies
ADVERTISEMENT
Jul 16, 2014
The program I'm working on is supposed to read input from a file and using recursion, print the pattern of asterisks for each value until the value is either < 0 or > 25. For example, if the value was 4, the pattern would look like this
*
* *
* * *
* * * *
* * *
* *
*
The values are stored in a file entitled prog3.dat which looks like this
4
3
15
26
0
I've never used recursion before and haven't been able to find anything showing how it would work with this particular type of problem. Here is what I've been able to come up with so far, but I'm having problems still which I will show following the code.
import java.util.Scanner;
import java.io.*;
public class Program3 {
public static void main(String[] args) throws Exception {
int num = 0;
java.io.File file = new java.io.File("../instr/prog3.dat");
Scanner fin = new Scanner(file);
[Code] ....
Output:
Please enter an integer
*
* *
* * *
* * * *
Please enter an integer
*
* *
* * *
Please enter an integer
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * * * *
Please enter an integer
Please enter an integer
As you can see, I don't know how to make it print the pattern like in the example and am honestly not even sure if this is recursion since I've never actually worked with recursion before.
View Replies
View Related
Mar 10, 2014
I want to know how to print this type of pattern when a name is given ???
Example:
name given TEJA
Capture.PNG
View Replies
View Related
Feb 13, 2014
I don't know how to write a program based on for loop like pattern printing.etc
View Replies
View Related
Jan 19, 2015
I built a java code to print the following pattern using nested loop:
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 6 5 4 3 2 1
1 2 3 4 5 6 5 4 3 2 1
1 2 3 4 5 4 3 2 1
1 2 3 4 3 2 1
1 2 3 2 1
1 2 1
1
And here is my code
public static void main(String[] args) {
for(int i=1; i<=8;i++)
{
for(int k=1;k<=i;k++)
{
System.out.print(" ");
[Code] .....
which gives the partially true output:
123456781
123456721
123456321
123454321
123454321
123654321
127654321
187654321
I couldn't figure out how to place the spaces.I have made some changes on the code, but it didn't work.
View Replies
View Related
Nov 3, 2014
The only problem I have now is getting a method to return the median element of a LinkedList without using loops of any kind or by using a global counter anywhere.
I've pretty easily figured out how to get the index value for the median number (there is some lee way allowed. If the list has an even size, any of the middle values are accepted) but I can't figure out how to print it without loops.
I'm sure I need to make a method that finds an element at the given index value, but I don't know how to do it without loops.
Here's all of my code. Inside is my Assignment3 class I use for testing, StudentList which contains the LinkedList head and other List methods, and StudentNode which is obviously, the Node class. Also I've attached the first test1.txt file as well.
import java.io.FileNotFoundException;
import java.util.*;
public class Assignment3 {
public static void main (String []args){
StudentList<StudentNode> myList = new StudentList<StudentNode>();
[Code] .....
I tried making a method that basically counts up the list recursively then a second method that counts down recursively and is supposed to stop once it hits the middle number, then print that node.
Attached File(s) : test1.txt (106bytes)
View Replies
View Related
Apr 29, 2014
I am trying to make a game, for some reason i have begun to get a java.lang.StackOverflowError.
I am not exactly sure how i can fix it. only removing line 14 from infopannel1 (and everything that used that class.) seems to work. im not sure what else i can do to fix it. or why its resulting in stack overflow for that matter.
I am putting in a link for the files i wrote this using bluej (several classes have no relevance, errorv2, demonstration, folderreadertest, ReadWithScanner, saveloadtest, menutest,rannum, and menutestTester. are all irrelivent to my problem.)
[URL] .....
View Replies
View Related
Dec 13, 2014
how does recursion works, I don't understand why it prints al numbers going up again?This is the code
void print2(int n){
if (n<0){
out.printf(" %d",-1);
return;
}
out.printf(" %d", n);
print2(n-1)
out.printf(" %d", n);
}
this should be the output if n is 6: 6 5 4 3 2 1 0 -1 0 1 2 3 4 5 6.
View Replies
View Related
Mar 25, 2015
How to add the sum of an array with a recursion, but I don't understand how to use recursion. I just understand that it calls back the method. I am nearly done with the code.
import java.util.Scanner;
class Question1{
public static void main(String[]args){
Scanner s = new Scanner(System.in);
int size, sum;
System.out.println("Please input how many numbers will be used");
size=s.nextInt();
[Code] .....
View Replies
View Related
Aug 6, 2014
public void myFunc(MyNode n, ArrayList<MyNode> path) {
boolean hasChildren = false;
path.add(n);
int index = path.indexOf(n);
ArrayList<MyNode> statefulPath = new ArrayList<MyNode>();
[Code] ....
I have similar code that I stepped through in a debugger. After running the code I found that it built the desired tree, in this case a root node H with left child L and right child P. I want list of lists to contain all paths from root to leaf. I expected [H, L] and [H, P]. I discovered that statefulPath is not stateful; after a recursive stack frame pops, statefulPath still contains n! But that stack frame just popped! I expected to see statefulPath be [H] in the debugger and it was [H, L]! So I later have a list [H,L,P] which I don't want. How do I make the statefulPath list I want for my algorithm?
View Replies
View Related
Mar 22, 2015
I have a question related to the code below, that I do not understand. The aim is to count all files and subdirectories in an ArrayList full of files and subdirectories. So I have to count every file and every subdirectory.
The code concerning counting files is clear to me - every time d is of the type file I have to increment n by one. However I thought that I have to do the same thing in case d is a directory, so I would have written the same code for directories.
So what does "n += ((Directory) d).countAllFiles();" mean? In my understanding the method countAllFiles() is applied again on the object Directory ( as Directory is the class that contains this method), but how is n incremented by this? I thought n should be incremented by one as we did with files.
public int countAllFiles() {
int n = 0;
for(SystemFile d : content) {
if(d instanceof File) {
n++;
[Code] ....
View Replies
View Related
Jun 5, 2014
How the recursion works. I tried to figure out writing down low, mid, high at each recursive call. But I seem to be making a mistake somehow. I don't understand where the values are returned to in
if(leftmax>rightmax){
return leftmax;}
else
return rightmax;
Here's the code:
public class Maximum{
public static int max(int[] a,int low,int high){
int mid,leftmax,rightmax;
if(low==high)
return a[low];
[Code] ....
firstly leftmax=max(a,0,4)
Then what is the next line executed?Is it rightmax=max(a,5,8).
After this is it leftmax=max(a,5,6)
rightmax=max(a,7,8)
I tried to understand what these recursion calls by writing them down.But I somehow make a mistake.
View Replies
View Related
Oct 20, 2014
I just started studying recursion and I wanted to know how to create a palindrome number going up from 1 to n then back to 1 like this: "12345...n...54321".
I've done one going downwards and then upwards like this: "n...4321234...n".
Here's my code:
Java Code: import java.util.*;
public class PalindromeTest
{
public static void downPalindrome(int n)
[Code].....
View Replies
View Related
Apr 26, 2015
I was asked to create a word pyramid program using recursion. I understand the concept of recursion (i.e. a method calling itself with the problem it is solving getting simpler and simpler each time) but I am having issues writing the program. Here is my code:
public static void main(String[] args) {
//This program will create a word pyramid by using a recursive algorithm.
//For example, the output of "DOGGY" should be:
//DOGGY
//OGG
//G
//This program will also use a recursive algorithm to accomplish this.
String userWord = JOptionPane.showInputDialog(null, "Hello and welcome to the Word Pyramid program."
[Code] .....
So, if I input HORSE the output should be:
HORSE
ORS
R
View Replies
View Related
Nov 6, 2014
We are supposed to create a MergeSort method without the using recursion. Most of the code is already completed, the only thing that I believe I need are two for loops (an inner and an outter) that will make calls to the merge method. I need implementing the sort method of the merge sort algorithm without recursion, where the length of the array is a power of 2. Keep merging adjacent regions whose size is a power of 2. For ex: lengths will be 1, 2, 4, 8, 16,.
public class MergeSorter {
public static void sort(int[] a) {
//for(int i = 1; i <= a.length; i++) the parameters for the for loop are wrong.
{
merge(0,0,1,a);
merge(1,1,2,a);
merge(2,2,3,a);
[Code]...
View Replies
View Related
Nov 26, 2014
Here is what I have so far:
/**
* This class encapsulates a simple dice game. The number of dice and number of sides on those dice are given by instance variables. The outcomes ArrayList holds a list of all possible outcomes of throwing that number of dice with that number of sides.
*
* If there were 2 dice, each with 6 sides, then possible outcomes would include 1 1, 1 2, 1 3, 1 4, 1 5, 1 6, 2 1, 2 2, 2 3, and so on.
*
* Your task is to complete the methods that calculate the possible outcomes. One method calculates outcomes allowing for repeated numbers. One method calculates the outcomes of a fictional dice game where repeated numbers cannot occur.
*
* You must use recursion. This is a variation on the permutations problem from the book.
*/
public class Dice
{
private static int numberOfSides;
private static int numberOfDice;
public ArrayList<String> outcomes;
[code]...
I manage to calculate the numberOfOutcomes correctly, but then get a nullPointerException. Also, is there a way that I can use getNumberOf Outcomes without making it static? The testing code that the teacher provided is using it in another class and if I make it static, then it doesn't work in that file.
View Replies
View Related
Feb 26, 2014
I have this method
Java Code:
public static int[] oddNums(int n){
} mh_sh_highlight_all('java');
When a number is passed in, this method returns an array of odd numbers the amount of the number passed in.
So
Ex: Class.oddNums(5) would return [ 1, 3, 5, 7, 9 ]
Class.oddNums(2) would return [ 1, 3]
View Replies
View Related
Aug 7, 2014
how the code is getting all the permutations of a string with recursion. The following code works correctly but I am having trouble grasping what it is doing.
public class Main {
private static void permutation(String prefix, String str){
int n = str.length();
if (n == 0)
System.out.println(prefix);
else {
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i),
str.substring(0, i) + str.substring(i+1));
}
}
public static void main(String[] args) {
permutation("", "ABCD");
}
}
I see that each character is being appended to prefix through each iteration. So I know it adds "A" then "B" etc etc. I can follow it up until the "D" is appended to the prefix string. After that I don't understand how the D moves back to the str string and then the C moves back to str followed by the D moving back to the prefix string. I have stepped through the code many times in my debugger but still don't see how it moves back to str and knows to send D to prefix and not to send C. I feel I don't understand how recursion behaves therefore I can't follow.
View Replies
View Related
Apr 12, 2014
From a two-dimensional grid 5x5 that looks like this:
(0,0)(0,1)(0,2)(0,3)(0,4)
(1,0)(1,1)(1,2)(1,3)(1,4)
(2,0)(2,1)(2,2)(2,3)(2,4)
(3,0)(3,1)(3,2)(3,3)(3,4)
(4,0)(4,1)(4,2)(4,3)(4,4)
We have Starting point that is (3,0) and an ending point is (1,3). We can only move up and right to get to the ending point by using recursion. We have to list all possible paths from (3,0) to (1,3)
Example: paths:(3,0)(2,0)(1,0)(1,1)(1,2)(1,3)
(3,0)(2,0)(2,1)(1,1)(1,2)(1,3)
etc...
I was able to get from (3,0) to (1,3) but how to list the other paths. This is my code so far
public class Program7 {
public static void main(String[] args){
int size = 5;
int x1 = 3;
int y1 = 0;
int x2 = 1;
int y2 = 3;
System.out.println(x1+" "+y1);
System.out.println(x2+" "+y2);
int [][] path = new int[size][size];
grid(path,x1,y1,x2,y2);
[code].....
View Replies
View Related
Apr 12, 2014
From a two-dimensional grid 5x5 that looks like this:
(0,0)(0,1)(0,2)(0,3)(0,4)
(1,0)(1,1)(1,2)(1,3)(1,4)
(2,0)(2,1)(2,2)(2,3)(2,4)
(3,0)(3,1)(3,2)(3,3)(3,4)
(4,0)(4,1)(4,2)(4,3)(4,4)
We have Starting point that is (3,0) and an ending point is (1,3). We can only move up and right to get to the ending point by using recursion. We have to list all possible paths from (3,0) to (1,3)
Example: paths:(3,0)(2,0)(1,0)(1,1)(1,2)(1,3)
(3,0)(2,0)(2,1)(1,1)(1,2)(1,3)
etc...
I was able to get from (3,0) to (1,3) but how to list the other paths. This is my code so far
public class Program7 {
public static void main(String[] args){
int size = 5;
int x1 = 3;
int y1 = 0;
int x2 = 1;
int y2 = 3;
System.out.println(x1+" "+y1);
System.out.println(x2+" "+y2);
[Code] ....
View Replies
View Related
Jul 7, 2014
I found an open-source recipe for converting numbers to words.
I modified it a bit since the requirement is only for integers until 999:
public class NumberToWordsConverter {
private String[] ones = {"zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"};
[Code] .....
From robosoul's response at StackOverflow, I simply inserted a condition for negative integers (line 12). True enough, the code worked and I was able to trace (pen and paper method) how it is converting the 0 and positive integers to words.
However, I am a bit lost on how it is doing the conversion for negative integers. How it is successfully converting the negative?
View Replies
View Related
Sep 4, 2012
I have to alter my Sentence class to find the index of the substring "sip" in Mississippi but I'm really not sure where to begin. This is what I have...
Sentence.java
public class Sentence {
private boolean outcome;
private String sentence;
public Sentence(String aSentence) {
sentence = aSentence;
[Code] ....
I know that I need to change public boolean find(String t) to public int indexOf(String t) but I'm not sure what to start doing to get the index of "sip".
View Replies
View Related
Jan 11, 2015
i'm trying to exit the recursion of a void method but some funny things are happening before and after the return statement.
public static void main(String args[])
{
//code
rec(x,y);
System.out.println("HEllooooooo");}
public static void rec(int x,int y)
{
try
{
System.out.println(x+" "+y+" "+check);
if(x==fx && y==fy)
[code]....
View Replies
View Related
Nov 16, 2014
Recursion in a MineSweeper game. So far, when a user clicks on a square and it has a bomb on it, I reveal the bomb to the user - see clicked(). I also have the ability to show the user if the squares surrounding them have any adjacent bombs - see countAdjacentSquares().
However, I am having trouble with my fillZeros() recursive method. When a user clicks on a square that has zero bombs in its surrounding squares, it not only reveals that square, but also any adjacent squares (horizontally, vertically or diagonally adjacent) that also have zero bombs in its surrounding squares.
I don't have any recursion, if I click on a square with no bombs all it does it set the square to 0, but doesn't continue to check for other empty squares.
Java Code:
import javax.swing.*;
import java.awt.*;
import java.util.*;
public class Square extends GameSquare
{
private boolean revealed = false;
private boolean squareHasBomb = false;
public static final int MINE_PROBABILITY = 10;
public int mineCount = 0;
[Code] ....
View Replies
View Related
Nov 26, 2014
Here is the code I have at the moment:
/**
* Use selection sort to sort the tracks by name. Return a new, sorted ArrayList of tracks.
*
* @return an ArrayList containing the tracks sorted by name, or null if no tracks exist
*/
public ArrayList<Track> getTracksSortedByName() {
// YOUR CODE HERE
if(tracks == null)
return tracks;
[Code] ....
Here are my 2 issues (there are 2 lines with compiler errors): I feel like I understand selection sort and binary search, but am not sure how to apply it to the more abstract idea of a Track ArrayList (hence the 2 compiler errors). What should I use to make it work. Lastly, I'm very uncomfortable with recursion, so my guess is there is also probably some logical issue with it in the getTracksSortedByName method.
View Replies
View Related
Jan 2, 2015
I created this code, seems like it should be working properly and the code is right, but the output is not what it should be.The action gets a List<Integer> and should make it reversed.
As example: 1 2 3 4 5 ---> 5 4 3 2 1
The Nodes in the new list (lst2) should be in a reversed position.The code does compile with no errors.I do have Node<T> and List<T> classes
Java Code:
public class NodeReverse
{
public static void reverse (List<Integer> lst, Node<Integer> node, int counter, List<Integer> lst2, Node<Integer> pos) // Should make lst = lst2 while lst2 is the opposite to lst
{
node = node.getNext();
counter++;
if(node.getNext()!=null)
reverse(lst, node, counter, lst2, pos);
[code]....
View Replies
View Related