The Java console input line turn into an integer array of integers

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/sinat_32336967/article/details/98050303

Ideas:
The read data line coming in the form of a string.
First determines whether the input string is empty, empty, then do nothing.
Next, the specified character string was cut into an array of strings, here in accordance with the space division Geqie, since the input is distinguished by a space.
Finally, attempts to each string string array using Integer.parseInt (String s) to instantiate a good analytical method integer array them.
If there is an error, then return directly, without any action.
If there is no error, the contents of the final output array of integers.

package org.jinyuxin.a20190731;

import java.util.Scanner;

public class StringLineToIntArr {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("请输入一行数字,以空格分开...");
    String line = sc.nextLine();
    parseLineToIntArr(line);
  }

  public static void parseLineToIntArr(String s) {
    //字符串为空,则不作操作
    if (s.isEmpty()) {
      return;
    }
    
    //将字符串按空格切分,转成字符串数组
    String[] strArr = s.split(" ");
    int strArrLen = strArr.length;

    //将字符串数组转成整型数组
    int[] intArr = new int[strArrLen];
    
    //循环遍历字符串数组中的每一个字符串,尝试解析这个字符串到整型数组里。出错的话,就退出
    for (int i = 0; i < strArrLen; i++) {
      //
      try {
        intArr[i] = Integer.parseInt(strArr[i]);
      } catch (NumberFormatException e) {
        e.printStackTrace();
        return;
      }
    }
    //输出转换之后的整型数组
    for (int x : intArr) {
      System.out.println(x);
    }
  }
}

Here Insert Picture Description

Guess you like

Origin blog.csdn.net/sinat_32336967/article/details/98050303