0

I have this really simple code:

public class ArrayIO {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);    
        System.out.println("Enter a number from 50 to 150: ");
        int elements = sc.nextInt();

        while(elements<50 && elements>150) {
            System.out.println("Less than 50 or more than 150");
            elements = sc.nextInt();
        }
            sc.close();

            ArrayList<Integer> integers = new ArrayList<>();
            for(int i=1; i<=elements; i++) {
                integers.add(i);
            }

            integers.toArray();

            System.out.printf("Array size is %d\n", integers.size());

    }

}

but my program bypasses the while loop completely when it has more than one condition. It works just fine with only one condition. I feel like I'm doing some really stupid mistake, but I just can't quite get it for almost an hour already.

4
  • 6
    So... how can elements be less than 50 and greater than 150 at the same time? I think you mean "or", || (Two pipes) Commented May 16, 2017 at 18:52
  • 1
    based on System.out.println("Enter a number from 50 to 150: "); you may want : while( elements >= 50 && elements <= 150 ) Commented May 16, 2017 at 18:54
  • @ChristopherSchneider wow, it actually worked. Didn't think I made that stupid of a mistake, quite embarrassing, really. However, I believe I've tried it when I was using if-else statement instead of while loop and it didn't work. It works just fine now, though. Thanks! Commented May 16, 2017 at 18:56
  • 1
    @svasa No, since I want my array size to be >=50 and <=150, and this while loop cuts off every number lower than 50 and higher that 150 Commented May 16, 2017 at 19:07

1 Answer 1

7

Change && to || if you want OR:

while(elements<50 || elements>150) {
    System.out.println("Less than 50 or more than 150");
...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.