【问题标题】:reading int from console从控制台读取 int
【发布时间】:2010-12-28 15:29:52
【问题描述】:

如何在 java 中将 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。这可能吗?

【问题讨论】:

    标签: java arrays string int


    【解决方案1】:

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

    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
    

    另请注意,nextInt() 函数可以抛出 3 个指定的异常 here。不要忘记处理它们。

    【讨论】:

      【解决方案2】:

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

      无论如何,你为什么不使用扫描仪?如果您使用扫描仪,对您来说会容易得多。 :)

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

      【讨论】:

        【解决方案3】:
        int x = Integer.parseInt(String s);
        

        【讨论】:

        • 如果String 不包含可解析的int,请不要忘记捕获NumberFormatException
        猜你喜欢
        • 2012-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-04
        • 1970-01-01
        相关资源
        最近更新 更多