Home > DeveloperSection > Forums > Trying to use a while loop with input.
Samuel Fernandes
Samuel Fernandes

Total Post:159

Posted on    April-28-2015 12:12 AM

 Java Java  Loop 

 1 Reply(s)
 747  View(s)
Rate this:
Here is my code so far. I am trying to get the WHILE LOOP to work so the user inputs a number, the if statement prints the output and then it returns to ask for another number and goes again and again looping : 

import java.util.Scanner;
public class ifwhileloop {
    static Scanner sc = new Scanner(System.in);
    public static void main(String[] args)
    double nmbr;
    *********** while(nmbr < 101){     ---- this gives me the error!!!
    System.out.print("Enter the number:");      
    nmbr = sc.nextDouble();
        if(nmbr <= 5){
    System.out.println("the number is between 0 and 5 and is: " + nmbr);        
        else if(nmbr >= 6 && nmbr <=9) {
            System.out.println("the number is between 6 and 9 and is: " + nmbr);
        else if(nmbr >= 10 && nmbr <= 100 ) {
            System.out.println("the number is between 10 and 100 and is: " + nmbr);
            System.out.println("the number is bigger than 100:" + nmbr);
//nmbr ++;  

Mayank Tripathi
Mayank Tripathi

Total Post:397

Posted on    April-28-2015 7:07 AM

Java requires that local variables be initialized before it can be used. At this point, the nmbr variable has not been initialized (set) 

that just declares the variable, but it does not initialize it to any value yet. You have to assign a value to it, for example: 
double nmbr = 0.0;
Note that there is a difference between local variables (inside a method) and member variables (at class level). Local variables must be initialized explicitly, but member variables are automatically initialized with a default value when not initialized explicitly.

Don't want to miss updates? Please click the below button!

Follow MindStick