David Bang David Bang - 1 year ago 60
Java Question

How to recurse back to start?

I'm a noob programmer, but I've been stuck on this one bit of code. How do you recurse back to start? I've tried several different methods but they all either take a ridiculous amount of code or don't work properly. I've been trying to implement this "simple" piece of code in all of my programming assignments, but it hasn't been working out. Thanks!

p.s. I've already finished the assignment. I'm just trying to make it more "complete".

public class OddProduct {

public static void main(String[] args) {
//Inputs from user
System.out.println("Enter an odd number");
Scanner input_odd = new Scanner(System.in);
int odd = input_odd.nextInt();

int oddproduct = 1;

//Multiplies all odd integers
for (int counter = 1; counter <= odd; counter = counter + 2){
oddproduct = oddproduct * counter;
}//end of for- loop
System.out.printf("\nThe product of all the odd integers up to %d is %d\n",
odd, oddproduct);

if (odd%2 == 1){ proceed normally}
else if (odd%2 != 1) { HOW TO LOOP BACK???}
else { println = "Application closed"}
}//end of main method

}//end of OddProduct class

Answer Source

Based upon your Notes I think this is what you require

   Scanner input_odd = new Scanner(System.in);
   int odd = 0; 

   while (odd % 2 != 1) {  // fails first time && if user enters even number
       System.out.println("Enter an odd number");
       odd = input_odd.nextInt(); 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download