I am trying to run while loop for each input user enter but don't know how to stop if user is not entering input. I need help in stopping while loop if user doesn't enter input.
Code:
import java.util.*;
class petrol{
public static void main(String[] args){
int vehicle_counter=0,petrol_counter=0;
System.out.println("Enter quantity of petrol to be filled in vehicles seperated by space:");
Scanner s1 = new Scanner(System.in);
ArrayList<Integer> array = new ArrayList<Integer>();
while(true){
if(petrol_counter<=200 && array.size()<50){
int input = s1.nextInt();
petrol_counter=petrol_counter+input;
vehicle_counter++;
array.add(input);
}
else{
System.out.println("Quantity Excedded then 200 Litres or no of Vehicles excedded then 50.");
break;
}
}
System.out.println("Hii");
}
}
e.g: If I enter 2 3 4 2 and press enter loop should stop.
Problem with possible solution :
If I use while(s1.nextInt().equals(true))
I get an error.
How do I use break?
BufferedReader
is better way. But if you still want to stick toScanner
, then this is not a preferable solution but just to give you another line of thought, probably you can usewhile(s1.hasNextInt())
instead ofwhile(true)
. Now if you want to stop inputting values, then before pressing enter type any non integer characters like punctuation. – Aniruddha Sardars1.hasNextInt()
works. i added a cooment to add period(.) at the end. – Jay Patel