+ 2

How to get the length of a scanner input?

If my input is scanner that ask for 3 inputs. Example input 5 4 1 I want to check that I have exactly three inputs before I run the code. How I can do that. I tried to put them in a string and check the length but it didn't work.

5th Dec 2020, 6:13 PM
Khaled ^^ خالد القريشي‎
Khaled ^^ خالد القريشي‎ - avatar
7 Respostas
+ 10
Aah AJ #Learn With Me 👨‍💻 my bad😅.Thank you for your suggestion 🤗
6th Dec 2020, 1:31 AM
♪A ruba♪💖
♪A ruba♪💖 - avatar
+ 9
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); String k=sc.nextLine(); int s=0; String[] l=k.split(" "); System.out.println(l.length); } } Here is the code it gives how many elements we entered .It splits the input based on space character and the number of elements we want will be length of that array Hope it helps :-)
5th Dec 2020, 6:41 PM
♪A ruba♪💖
♪A ruba♪💖 - avatar
+ 3
♪®!_!b@♪💖 You don't need to write for loop because s and l.length will be always equal because for loop depends on the length of string array.
5th Dec 2020, 6:51 PM
A͢J
A͢J - avatar
+ 2
Thank you AJ #Learn With Me 👨‍💻 yes it works with or without the loop is the same
5th Dec 2020, 7:02 PM
Khaled ^^ خالد القريشي‎
Khaled ^^ خالد القريشي‎ - avatar
+ 1
Oh ♪®!_!b@♪💖 thank you, I thought about a loop. Okay I will try this
5th Dec 2020, 6:48 PM
Khaled ^^ خالد القريشي‎
Khaled ^^ خالد القريشي‎ - avatar
+ 1
Thank you♪®!_!b@♪💖 it worked
5th Dec 2020, 7:02 PM
Khaled ^^ خالد القريشي‎
Khaled ^^ خالد القريشي‎ - avatar