I'm confused i'm suppose to get a positive int from user using recursion, the user can input words, and also numbers.(Words and negative numbers are invalid), Not sure what i'm doing wrong.
I'm sorry forgot to ask the question, well i'm getting compiler error, when I try to compile it, something is wrong with my Scanner, I was reading an it says I have to use an argument for the users input, I'm not sure how to, and the second question was, how do I let the code to repeat if the user inputs n<0 or a word, such as taxes. thank you
import java.util.*;
public class Recursion {
private static int getPositiveInt(Scanner keyboard) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a positive interger, n");
int n = keyboard.nextInt();
if (n > 0) {
return n;
}
else { //here the code should rerun if invalid input, but I cant figure it out
System.out.println("enter a positive number");
}
}
}
If I understood your question correctly, you want this function to run untill it will read a valid number.
To do this all you need to change is:
else { //here the code should rerun if invalid input, but I cant figure it out
System.out.println("enter a positive number");
}
to:
else {
//call the function again
return getPositiveInt(Scanner keyboard)
}
Related
I have been having a problem with this code for a while. The placement of recursive call of the function does not seem right.
i tried running the code and yes it does run into a infinite loop.
// I DEFINE HEAP STRUCTURE AS :
struct heap_array
{
int *array; // heap implementation using arrays(note : heap is atype of a tree).
int capacity; // how much the heap can hold.
int size; //how much size is currently occupied.
void MaxHeapify(struct heap_array *h,int loc) // note : loc is the location of element to be PERCOLATED DOWN.
{
int left,right,max_loc=loc;
left=left_loc_child(h,loc);
right=right_loc_child(h,loc);
if(left !=-1 && h->array[left]>h->array[loc])
{
max_loc=left;
}
if(right!=-1 && h->array[right]>h->array[max_loc])
{
max_loc=right;
}
if(max_loc!=loc) //i.e. if changes were made:
{
//swap the element at max_loc and loc
int temp=h->array[max_loc];
h->array[max_loc]=h->array[loc];
h->array[loc]=temp;
}
MaxHeapify(h,max_loc); // <-- i feel that this recursive call is misplaced. I have seen the exact same code in almost all the online videos and some books i referred to. ALSO I THINK THAT THE CALL SHOULD BE MADE WITHIN THE SCOPE OF condition if(max_loc!=loc).
//if no changes made, end the func right there.
}
In your current implementation, it looks like you don't have a base case for recursion to stop.
Remember that you need a base case in a recursive function (in this case, your MaxHeapify function), and it doesn't look like there is one.
Here is an example of MaxHeap which may be resourceful to look at
// A recursive function to max heapify the given
// subtree. This function assumes that the left and
// right subtrees are already heapified, we only need
// to fix the root.
private void maxHeapify(int pos)
{
if (isLeaf(pos))
return;
if (Heap[pos] < Heap[leftChild(pos)] ||
Heap[pos] < Heap[rightChild(pos)]) {
if (Heap[leftChild(pos)] > Heap[rightChild(pos)]) {
swap(pos, leftChild(pos));
maxHeapify(leftChild(pos));
}
else {
swap(pos, rightChild(pos));
maxHeapify(rightChild(pos));
}
}
}
Here, you can see the basecase of:
if (isLeaf(pos))
return;
You need to add a base case to your recursive function.
I'm new to using recursion and I'm trying to get my palindrome program to work. This is what I am trying to do: if a character is not equal, I return 0. If not, I keep recursing while increasing the i and decreasing the j. If the i is no longer less than the j, i want to say that the recursion is done, so I want to return that the word is a palindrome (=1).
But when I input a word that is not a palindrome, I correctly return a 0. (I can see this when I debug). But-- then at the end, it also returns a 1. I assume this has something to do with the fact that recursion means that the program keeps going, and the 0 gets returned to something I had previously been doing before. But- I want the 0 to go to the very top.
Is there some way around this problem? Or am I doing something wrong? Sorry if this is really basic.
Thanks in advance. Here is my code:
public static int checkIfPalindrome(String s, int i, int j) {
if (i<j) {
if (s.charAt(i) == s.charAt(j)) {
checkIfPalindrome(s, i+1, j-1);
}
else {
return 0;
}
}
return 1;
}
Once you know your pointers haven't collided, and the characters they point to are the same, then the return value of this method is the return value of the recursive call. I've fixed your code to do this below but I have also reorganized it a different way, as there are other ways to go about the problem:
public static int checkIfPalindrome(String s, int i, int j) {
if (i >= j) {
return 1;
}
if (s.charAt(i) != s.charAt(j)) {
return 0;
}
return checkIfPalindrome(s, i + 1, j - 1);
}
So im a pretty new programmer so forgive me if i make any mistakes.
I need to make a higher or lower game for my class but im a little bit stuck now.
The purpose of this whole game is to guess the number which is random generated by the computer. But here's the tricky part, the user only needs to get 8 chances to guess the number right. If not the game must end and print something like: you lost, the number was.....
I came this far;
public static void main(String[] args) {
int timesGuessed = 0;
int randomNummer = (int)(Math.random()*100);
int number;
boolean won = true;
Scanner input = new Scanner(System.in);
do{
System.out.print("Guess the number: ");
number = input.nextInt();
timesGuessed++;
if(timesGuessed == 8){
won = false;
}
if(number > randomNummer){
System.out.println("Lower!");
}
else if(number < randomNummer){
System.out.println("Higher!");
}
}
while(number != randomNummer);
if(won == true){
System.out.println("The number is guessed right in " + timesGuessed + " attemts.");
}
else{
System.out.println("You lost. The number was " + randomNummer + ".");
}
}
Now the game lets you finish even though you already had 8 chances. Thats what i want to change. It needs to stop when you failed the eight time.
Thank you for the help, it would be very appreciated.
You also need to check your won variable in the condition of your loop. You may also want to add an else so it doesn't print "Higher" or "Lower" after the final try.
I don't really understand why this is happening at all. I'm trying to open a file to read some data into my program but failbit gets set instantly, having moved error messages around it seems that failbit actually gets set before I even attempt input.open(). The undeclared variables in the code are globals which live elsewhere (messy but will refine later) Here's the offending function from a larger project:
int read_input()
{
ifstream input;
string value;
int file_complete=0;
int count=0;
if(input.failbit)
printf("Really?\n");
input.clear();
input.open("Input.txt");
while(!file_complete)
{
if(input.failbit)
{
printf("Reading in set-up value number %d failed.", count+1);
getchar();
return 1;
}
else if(input.eofbit)
{
file_complete=1;
}
if(input.get()=='=')
{
getline(input, value);
switch(count)
{
case 0:
n_loci=atoi(value.c_str());
count++;
break;
case 1:
n_founders=atoi(value.c_str());
count++;
break;
case 2:
n_self=atoi(value.c_str());
count++;
break;
// Add more cases later
}
}
}
input.close();
return 0;
}
This program for me turns out:
Really?
Reading in set-up value number 1 failed.
I'm assuming I've done something very stupid but have been at this quite a while now.
P.S I'm compiling with the latest version of g++ on cygwin on top of Windows 7.
OK fixed this myself now:
Failbit seems to be set by EOFs in some implementations so instead I switched to using input.good() and consequently all was good.
There was also some logical error in my program with the checking for "=" part too as ifstream.get() returns it's value as an integer so I needed to cast them back into chars for comparison.
Alright, so I'm trying to make a Java program to solve a picross board, but I keep getting a Stackoverflow error. I'm currently just teaching myself a little Java, and so I like to use the things I know rather than finding a solution online, although my way is obviously not as efficient. The only way I could think of solving this was through a type of brute force, trying every possibility. The thing is, I know that this function works because it works for smaller sized boards, the only problem is that with larger boards, I tend to get errors before the function finishes.
so char[][] a is just the game board with all the X's and O's. int[][] b is an array with the numbers assigned for the picross board like the numbers on the top and to the left of the game. isDone() just checks if the board matches up with the given numbers, and shift() shifts one column down. I didn't want to paste my entire program, so if you need more information, let me know. Thanks!
I added the code for shift since someone asked. Shift just moves all the chars in one row up one cell.
Update: I'm thinking that maybe my code isn't spinning through every combination, and so it skips over the correct answer. Can anyone verify is this is actually trying every possible combination? Because that would explain why I'm getting stackoverflow errors. On the other hand though, how many iterations can this go through before it's too much?
public static void shifter(char[][] a, int[][] b, int[] clockwork)
{
boolean correct = true;
correct = isDone(a, b);
if(correct)
return;
clockwork[a[0].length - 1]++;
for(int x = a[0].length - 1; x > 0; x--)
{
if(clockwork[x] > a.length)
{
shift(a, x - 1);
clockwork[x - 1]++;
clockwork[x] = 1;
}
correct = isDone(a, b);
if(correct)
return;
}
shift(a, a[0].length - 1);
correct = isDone(a, b);
if(correct)
return;
shifter(a, b, clockwork);
return;
}
public static char[][] shift(char[][] a, int y)
{
char temp = a[0][y];
for(int shifter = 0; shifter < a.length - 1; shifter++)
{
a[shifter][y] = a[shifter + 1][y];
}
a[a.length - 1][y] = temp;
return a;
}
Check Recursive call.and give the termination condition.
if(terminate condition)
{
exit();
}
else
{
call shifter()
}