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
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With