TRYING TO USE A WHILE LOOP WITH INPUT.

Samuel Fernandes

Total Post:159

Points:1117
Posted by  Samuel Fernandes
Java  Loop 
 778  View(s)
Ratings:
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);
         
    }
        else
            System.out.println("the number is bigger than 100:" + nmbr);
//nmbr ++;  
}
}
}


  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: Trying to use a while loop with input.

    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.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!