How to take input stream


#1

I have written this code …Please suggest me the necessary changes
public class Main {
public static void main(String[] args) {
// YOUR CODE GOES HERE
// Please take input and print output to standard input/output (stdin/stdout)
// DO NOT USE ARGUMENTS FOR INPUTS
// E.g. ‘Scanner’ for input & ‘System.out’ for output
ArrayList arrl = new ArrayList();
Scanner sc = new Scanner(System.in);
while(sc.nextInt())
{
int n = sc.nextInt();
if(n<0)
break;
else
arrl.add(n);

}
Collections.reverse(arrl);
for(int i=0;i<arrl.size();i++)
{
    System.out.print(arrl.get(i)+" ");
}

}
}


#2

The problem is in line
while(sc.nextInt())
because scanner return some exception or integer value but not false so loop will continue infinitely.


#3

use while(true) and check condition inside loop

e.g.
while(true){
if(condition)
break;
else
//add
}


#4

You can also use do while loop

Scanner sc=new Scanner(System.in);
int n;
ArrayList ar=new ArrayList<>();
do{
n=sc.nextInt();
if(n>=0)
ar.add(n);
}while (n>=0);


#5

you have to mention the type of datatype you using for this Arraylist when you creating your ArrayList, like this: ArrayList for Integer datatype.


#6

import java.lang.;
import java.util.
;

public class Main {
public static void main(String[] args) {
List al= new ArrayList<>();
Scanner sc = new Scanner(System.in);
while(true){
int temp = sc.nextInt();
if(temp >= 0)
al.add(temp);
else
break;
}

    for(int i=al.size()-1;i>=0;i--){
        System.out.print(al.get(i)+" ");
    }
}

}