Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read arrays from user in java? [closed]

Tags:

java

What is the java equivalent of the following C code.

for(i = 0;i<n;i++)
scanf("%d",&a[i])

where i is a previously defined integer and a is an array

like image 645
station Avatar asked Mar 11 '26 11:03

station


1 Answers

The scanner class is used, System.in is the standard input, but it can get other input streams:

Scanner scan = new Scanner(System.in);
for(i = 0;i<n;i++) {
    a[i] = scan.nextInt();
}

Anyway, this might cause you some problems if the user press enter between two numbers, so another approach will be:

Scanner scan = new Scanner(System.in);
for(i = 0;i<n;i++) {
    String token = scan.next();
    a[i] = Integer.parseInt(token);
}
like image 139
MByD Avatar answered Mar 14 '26 01:03

MByD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!