Help with While loop to continuously divide
Hello, I'm working on a program that will accept a positive number typed by user and then tell you how many times that number can be divided by two before it reaches a number less than 1. If a negative number is entered by the user it should tell them it is invalid. This is what I have so far, but the loop isn't behaving like I need it to, not sure what's wrong. Any suggestions would be greatly appreciated.
Code java:
package project6a;
import java.util.Scanner;
public class Bits {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner (System.in);
System.out.println("Enter a positive number: ");
int userNumber = input.nextInt();
int count = 0;
int tempNum = userNumber / 2;
while (tempNum > 1){
tempNum = tempNum / 2;
count++;
System.out.println("The number " + userNumber + " is divisible by two " + count + " times");
}
if (userNumber < 0)
System.out.println("Invalid");
input.close();
}
}
Re: Help with While loop to continuously divide
The while loop must contain all the behaviors that need to be repeated, and that includes getting user input, checking input, and warning if input is bad (negative). Your while loop doesn't have all these things inside it.