Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading