1
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    in.useDelimiter(", "); // using delimiter ", "

    int i = 1;
    while(in.hasNextInt()){
        i = in.nextInt();
        System.out.println(i);
    }
}

I am trying to get the input from console, but this code is not printing last integer How can I solve this problem. I don't want to use split and save the result in an array.

2 Answers 2

2

You will need to use a regex pattern.

in.useDelimiter(",?\\s");

OR, if it is not necessarily seperated by both spaces and commas (e.g. 1, 4,5465, 5):

in.useDelimiter("[,\\s]+"); // this is more permissive
Sign up to request clarification or add additional context in comments.

2 Comments

You tried a wrong pattern, it will not use "," as delimiter i.e try 1, 4,5465, 5 as input, you'll get 1,4,5,4,6,5,5 as output
@negia Yeah, I realized that just now, I removed the * (damn! it didn't go unnoticed :)).
0

With Scanner.useDelimiter, the string after your last input integer should match the delimiter pattern, for example with your pattern if you give "1, 3, 5, 6, " you will get 1 3 5 6 as output but if you give "1, 3, 5, 6" you will not get the last integer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.