How to take input from user untill user enters a negative number in java. while loop for taking infinite inputs from user.
Taking N number of Inputs from User
Hello everyone here i am going to discuss how to take input from user or external input until a user enters negative number.
Problems:
- The first problem with this is we exactly don’t know how many inputs user is going to enter.
- So we are unable to decide what should be the size of array to store those numbers.
Solution
- We will take input untill user enters zero, so we will be using “While Loop” for checking the condition.
- Also as we are not sure about number of elements, we will use “ArrayList” instead of array. Because the size of array is fixed but arraylist size is not fixed it can grow dynamically.
- Initial capacity of array list is 10 elements, once it reaches maximum capacity the arraylist size will be increased automatically by current size * 3 /2 .
- As we are using while loop it terminates whenever user enters a negative number.
JAVA CODE
import java.util.*; class demo { public static void main(String[] args) { Scanner sc=new Scanner(System.in); ArrayList array1=new ArrayList(); System.out.println("enter array elements"); boolean flag=true; while(flag) { int a=sc.nextInt(); if(a>0) { array1.add(a); } else { flag=false; } } } }
Similar Posts
Xoriant off campus coding question and solution