从控制台读取int

如何在String中将String数组转换为int数组? 我正在从控制台读取一个整数字符流到一个String数组中

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

其中str[]是字符串类型。 我想比较str[]内容…不能在字符上执行(错误)因此我想从控制台读取int 。 这可能吗?

Integer.parseInt(String); 是你想要的东西。


尝试这个:

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

无论如何,你为什么不使用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(); } 

 int x = Integer.parseInt(String s); 

使用扫描仪要快得多,因此效率更高。 此外,它不需要您使用缓冲流进行输入的麻烦。 这是它的用法:

 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 

另请注意, nextInt()函数可以抛出此处指定的3个exception。 别忘了处理它们。