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 " "

.

+3


source to share


5 answers


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++;
    }

      

+1


source


One easy way to achieve this is to do something like this:



String  n = in.nextLine().replace(" ", "");
int nums[] = new int[n.length()];
int i=0;
for(char c : n.toCharArray()) {
    nums[i++] = Character.getNumericValue(c);
}

      

+3


source


You can split the input line using:

String  n = in.nextLine();
String[] splitLine = n.split(" ");
for (String s : splitLine){
   //you can save the num in an array
   int num = Integer.parseInt(s);
}

      

+1


source


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

+1


source


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++;

             }
        }

      

+1


source







All Articles