Java 从控制台读取 int

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1938389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 01:36:45  来源:igfitidea点击:

reading int from console

javaarraysstringint

提问by chatty

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

java中如何将String数组转换为int数组?我正在String从控制台将整数字符流读入数组,其中

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 intfrom the console. Is this possible?

在哪里str[]输入字符串。我想比较str[]内容......不能在字符上执行(错误)因此我想int从控制台读取。这可能吗?

采纳答案by Prasoon Saurav

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

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



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


回答by carillonator

int x = Integer.parseInt(String s);

回答by Rushil Paul

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.

还要注意的是,nextInt()作为指定的函数可以抛出异常3这里。不要忘记处理它们。