chatty
chatty

Reputation: 5031

reading int from console

How can I convert a String array into an int array in java? I am reading a stream of integer characters into a String array from the console, with

BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
for(c=0;c<str.length;c++) 
    str[c] = br.readLine();

where str[] is String typed. I want to compare the str[] contents ... which can't be performed on chars (the error) And hence I want to read int from the console. Is this possible?

Upvotes: 5

Views: 28338

Answers (3)

Rushil Paul
Rushil Paul

Reputation: 2048

Using a scanner is much faster and hence more efficient. Also, it doesn't require you to get into the hassle of using buffered streams for input. Here's its usage:

java.util.Scanner sc = new java.util.Scanner(System.in);  // "System.in" is a stream, a String or File object could also be passed as a parameter, to take input from

int n;    // take n as input or initialize it statically
int ar[] = new int[n];
for(int a=0;a<ar.length;a++)
  ar[a] = sc.nextInt();
// ar[] now contains an array of n integers

Also note that, nextInt() function can throw 3 exceptions as specified here. Don't forget to handle them.

Upvotes: 7

Prasoon Saurav
Prasoon Saurav

Reputation: 92854

Integer.parseInt(String); is something that you want.


Try this:

int[] array = new int[size];
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        for (int j = 0; j < array.length ; j++) {
                int k = Integer.parseInt(br.readLine());
                array[j] = k;
        }
     }

    catch (Exception e) {
            e.printStackTrace();
     }

Anyways,why don't you use Scanner? It'd be much easier for you if you use Scanner. :)

int[] array = new int[size];
    try {
        Scanner in = new Scanner(System.in); //Import java.util.Scanner for it
        for (int j = 0; j < array.length ; j++) {
                int k = in.nextInt();
                array[j] = k;
        }
     }
     catch (Exception e) {
            e.printStackTrace();
     }

Upvotes: 12

carillonator
carillonator

Reputation: 4743

int x = Integer.parseInt(String s);

Upvotes: 7

Related Questions