Skip to content
Advertisement

How to count the number of elements in one input

I hope you can help me with my task. I have tried to research different sites for this, but can’t find the specific one.

import java.util.Scanner;

public class Main{

    public static void main(String []args){
        Scanner input = new Scanner (System.in);
        System.out.print("Input: ");
        String arr = input.nextLine();
        //System.out.println(arr.length);
    }
}

Let us say that I’ve input 3, 2, 1, 5, 6 then the output should be 5. Another example is I have inputted 1, 2, 3, 4, 5, 6 then the output should be 6. It should count how many integers in the text are there in just one input.

Advertisement

Answer

After you getting the input line you can split it by , so you will get an array of elements and the length of it is the number of elements you want

public static void main(String []args){
    Scanner input = new Scanner (System.in);
    System.out.print("Input: ");
    String arr = input.nextLine();
    int numberOfElement = arr.split(",").length;
}

The problem with your code is that you used arr.length() and this is the number of char in the input string not the number of elements for examples

"1, 2, 3, 4, 5".length() -> 13 char
"1, 2, 3, 4, 5".split(",").length -> 5 element
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement