Java – why does my scanner still need a blank char

Input: 1 2 3

Objective: each number will be filled in the same array Space will be excluded

Scanner in = new Scanner(system.in);
String  n = in.nextLine();
System.out.println(n);

int[] nums = new int[n.length()];
for (int i = 0; i < n.length(); i++) {
     System.out.println(n.charAt(i));
     if (!String.valueOf(n.charAt(i)).equalsIgnoreCase(" ")) {
          nums[i] = Character.getNumericValue(n.charAt(i));
     }
}

I don't know why it also includes space ""

Solution

The way you do this, the number of elements in the num array will be the same as the number of characters in "n" Where char is a space, you will get a value of 0

String[] numStrings = n.split("\\D+");
    int[] nums = new int[numStrings.length];
    int i = 0;
    for (String num : numStrings) {
        nums[i] = Integer.parseInt(num);
        i++;
    }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>