Reading int from console

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

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

where str[] is the string typed. I want to compare the contents of str[] ... which cannot be executed on characters (error) And therefore I want to read int from the console. Is it possible?

+4
source share
3 answers

Integer.parseInt(String); - Is this what you want.


Try the following:

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

Anyway, why aren't you using Scanner? It would be much easier if you used 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(); } 

+11
source
 int x = Integer.parseInt(String s); 
+6
source

Using a scanner is much faster and therefore more efficient. Furthermore, this does not require you to encounter the problem of using buffered streams for input. Here is its use:

 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 the nextInt() function may throw 3 exceptions, as indicated here . Do not forget to handle them.

+6
source

All Articles