• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

reading user input of numbers into an array

 
Lesa
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone please tell me how to read a series of numbers in from the keyboard and put them into an array of integers for manipulation?
------------------
 
Eric Edwards
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Lesa:
Can anyone please tell me how to read a series of numbers in from the keyboard and put them into an array of integers for manipulation?

I did this in a hurry, but it works. It reads in ten numbers
and puts each number in an array. At the end it prints out the array. You can adjust it any way you want.
import java.io.*;
import java.text.*;
public class ReadNum
{ public static void main(String[] args)
{
int[] num = new int[10];// set up array of 10
for (int i = 0; i < 10; i++) // read in 10 numbers
{
System.out.println
("Enter a number."); // get a number
int x; // number you entered
try
{ InputStreamReader isr
= new InputStreamReader(System.in);
BufferedReader br
= new BufferedReader(isr);
String s = br.readLine();
x = Integer.parseInt(s);
num[i] = x; // put the number in the array
}
catch(IOException e)
{ x = 0;
}
}
for (int i = 0; i < 10; i++)
{
System.out.println(num[i]); // print out the array
}
}
}

[This message has been edited by Eric Edwards (edited February 27, 2000).]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic