Why is my scanner still occupying a char space
Input: 1 2 3
Purpose: Each of this number will be filled with the same array. The 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 still includes space " "
.
source to share
As you did, the number of elements in the nums array will be the same as the number of characters in "n". And in places the char is space, you get the value 0. You can try it like this:
String[] numStrings = n.split("\\D+");
int[] nums = new int[numStrings.length];
int i = 0;
for (String num : numStrings) {
nums[i] = Integer.parseInt(num);
i++;
}
source to share
The problem with this code is that you are incrementing the i
event when char
you are looking at is a space where you will have empty spaces in your arraynums
You can easily fix this with:
String n = in.nextLine().replaceAll("\\D", "");
I'll remove everything non-digit characters
from what you type and after that you don't have to check:
int[] nums = new int[n.length()];
for (int i = 0; i < n.length(); i++){
nums[i] = Character.getNumericValue(n.charAt(i));
}
Or in smaller lines using Java8 features (you can even put 1 ^^):
String n = in.nextLine().replaceAll("\\D", "");
int[] nums = Arrays.stream(n.split("")).mapToInt(Integer::parseInt).toArray();
After erasing all non-numeric strings, the second string will split each into an array, then dash into int
, and then convert toarray
source to share
I changed .equalsIgnoreCase
to .equals
and used a pointer to insert into the array.
Scanner in = new Scanner(System.in);
String n = in.nextLine();
System.out.println(n);
int pointer = 0;
int[] nums = new int[n.length()];
for (int i = 0; i < n.length(); i++) {
if (!String.valueOf(n.charAt(i)).equals(" ")) {
nums[pointer] = Character.getNumericValue(n.charAt(i));
pointer++;
}
}
source to share