Moiz Qazi - 1 year ago 79

Java Question

For my program you must enter a number between 1 and 100. If the number is **odd** you manipulate it using the formula New Number = initial number*6 +2 and if it is **even** than you you use the formula New number = initial number/2

This process continues UNTIL you reach the final number of the sequence. Here is an example output of when you enter 99 in the program:

Welcome to The Sequence Generator---------------------------------Please Enter an positive integer no more than 100: 99

(99) [596] [298] (149) [896] [448] [224] [112] [56] [28] [14] (7) [44] [22] (11) [68] [34] (17) [104] [52][26] (13) [80] [40] [20] [10] (5) [32] [16] [8] [4] [2]

I am having trouble writing code that will execute through the one loop while it is odd and through another loop if it is even. Here is my code so far:

import java.util.Scanner;

public class SequenceGenerator {

`public static void main(String args[]) {`

System.out.println("Welcome to The Sequence Generator");

System.out.println("---------------------------------");

System.out.println("Please Enter an positive integer no more than 100: ");

Scanner input = new Scanner(System.in);

int initial = input.nextInt();

if (initial >= 100 || initial <= 0) {

System.out.println("The input is invalid");

}

if (initial % 2 == 0) {

while (initial % 2 == 0) {

System.out.print("[" + initial + "] ");

initial = initial / 2;

}

}

if (initial % 2 == 1) {

while (initial % 2 == 1) {

System.out.print("(" + initial + ") ");

initial = 6 * initial + 2;

}

}

}

}

When I run the code right now with 99 for example, it only returns 99 and no other values. Basically the next value that should come up is 596 which is even and uses the other loop -- the code doesn't execute this.

Answer Source

Hope this code will help your need

```
private static int handleOddNo(int oddNo){
int initial = oddNo;
while (initial % 2 == 1) {
System.out.print("(" + initial + ") ");
initial = 6 * initial + 2;
if(initial == 1)
break;
}
return initial;
}
private static int handleEvenNo(int evenNo){
int initial = evenNo;
while (initial % 2 == 0) {
System.out.print("[" + initial + "] ");
initial = initial / 2;
if(initial == 1)
break;
}
return initial;
}
public static void main(String args[]) {
System.out.println("Welcome to The Sequence Generator");
System.out.println("---------------------------------");
System.out.println("Please Enter an positive integer no more than 100: ");
Scanner input = new Scanner(System.in);
int initial = input.nextInt();
if (initial >= 100 || initial <= 0) {
System.out.println("The input is invalid");
}
do{
if (initial % 2 == 0) {
initial = handleEvenNo(initial);
}else{
initial = handleOddNo(initial);
}
}while(initial != 1);
}
```