deco99
deco99

Reputation: 1

Prompting user for only positive number

this basic JAVA program should prompt the user, and print "Negative numbers are not allowed" until user enters a positive number. This must be handled by using while loop. how does it work ? This is my first post in stack overflow.

  public static void main(String[] args) 
  {
        System.out.print("Welcome to Box Price Calculator");
        System.out.print(System.lineSeparator());
        System.out.print(System.lineSeparator());
        
        int boxVol = 20 ;
        double price_each_box = 2.99;
        System.out.print("Bottles :");
        Scanner input = new Scanner(System.in);
        int numberOfbottles = 1;
        numberOfbottles = input.nextInt();
        
        boolean valid = false;
        
      
        while (input.nextInt() < 0){
            System.out.println("Negative numbers are not allowed");
            numberOfbottles = input.nextInt();
        }       
        
        int box = (numberOfbottles / boxVol);
        System.out.println("Box Needed : " + box);
        double totPrice = (box * price_each_box);
        
        System.out.println("Total Cost : $" + totPrice);
        int leftOver = (numberOfbottles -(box * boxVol));
        System.out.println("Unboxed :" + leftOver);
        
    }  
}

Upvotes: 0

Views: 110

Answers (1)

Edgar Magallon
Edgar Magallon

Reputation: 559

The problem here is that you are reading and compare again with input.nextInt() and not with numberOfbottles, inside the while condition. What you should do is to use a do...while and compare it with your variable numberOfbottles:

public static void main(String[] args) 
{
    System.out.print("Welcome to Box Price Calculator");
    System.out.print(System.lineSeparator());
    System.out.print(System.lineSeparator());
    
    int boxVol = 20 ;
    double price_each_box = 2.99;
    
    java.util.Scanner input = new java.util.Scanner(System.in);
  
    int numberOfbottles;
  
    do
    {
        
        System.out.println("Bottles (Negative numbers are not allowed):");
        numberOfbottles = input.nextInt();
    
    }
    while (numberOfbottles < 0);
    
    int box = (numberOfbottles / boxVol);
    System.out.println("Box Needed : " + box);
    double totPrice = (box * price_each_box);
    
    System.out.println("Total Cost : $" + totPrice);
    int leftOver = (numberOfbottles -(box * boxVol));
    System.out.println("Unboxed :" + leftOver);   
}

Upvotes: 2

Related Questions