1

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");
} 
}
}

1 Answers1

1

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)
}
  • Thanks, so this runs this runs the program, when user enters anything other that a positive integer? – William Giron Nov 15 '16 at 00:44
  • Is it a question? can you explain again the problem? – Ron Shemesh Nov 15 '16 at 08:05
  • Ok so the whole point of this program is to ask the user for a positive integer using recursion. The user can input things like -10, 0, or the word "car". If the user inputs n<0 the program should automatically restart using recursion, as well as if the user inputs the word "car", the program should restart and ask the user for a positive integer. My question is how do I use recursion for the program to restart when the user enters a word like "car". I think I'm suppose to use a while loop. Thanks maybe that is a little more clear. – William Giron Nov 15 '16 at 21:06
  • Tour problem is that you are reading the input as Integer without be sure that it is. the nextInt() call throws exception when it – Ron Shemesh Nov 18 '16 at 16:14
  • sorry about the splited messaged, I accidently click the enter buttom and it send the comment without let me cancel. so back to the solution- the nextInt() call throws exception when it read a string that is not a Integer. you have some option to solve it. the easiest is to use try-catch, you can google it. otherwise you can replace the .nextInt() call with .next(), but then you will have to check by yourself if its an integer or not (check this out http://stackoverflow.com/questions/5439529/determine-if-a-string-is-an-integer-in-java). wish it will help – Ron Shemesh Nov 18 '16 at 16:21