Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 481
chatty Avatar asked Dec 21 '09 05:12

chatty


2 Answers

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();
     }

like image 78
Prasoon Saurav Avatar answered Sep 30 '22 15:09

Prasoon Saurav


int x = Integer.parseInt(String s);
like image 42
carillonator Avatar answered Sep 30 '22 16:09

carillonator