Home > database >  Converting String returned from Scanner nextLine() to String array
Converting String returned from Scanner nextLine() to String array

Time:10-13

My requirement is that I need to convert a string input taken from a Scanner's nextLine() method, to a string array:

My code:

Scanner sc= new Scanner(System.in); 
String myString = sc.nextLine(); 

The above code works fine, when I give input in the console as : new String[]{"A:22","D:3","C:4","A:-22"}

but my challenge is to read scanner input and assign it to String array like this:

String[] consoleInput=sc.nextLine();

I have an incompatible type error, which is normal as String cannot be converted to String array. Is there a way to convert sc.nextLine() to String array in the above line?

CodePudding user response:

If you literally type n, e, w, , S, etcetera (you type in new String[] {"A:22", "D:3"} and you want a method on scanner such that you get a string with that data), that is incredibly complicated and involves linking a java compiler in. If you're asking this kind of question, likely well beyond your current skill level.

What you can do, however, is simply ask the user to enter something like:

A:22 D:3 C:4 A:-22

Simply .nextLine().split(" ") and voila: First read a line, then split that line into a string array by looking for spaces as separators.

CodePudding user response:

Scanner sc = new Scanner(System.in); 
String myString = sc.nextLine(); 

String[] arr = myString.replaceAll("[ \"{}]", "").split(",");

Explanation: The regex in replaceAll replaces the characters ", {, '}, and ` (space character) with an empty string. Then you simply split the string along all the commas, and you get a String array containing all the tokens the user entered.

Note: the regex removes all spaces as well, so if your tokens have spaces in them, then they will get removed. However, from what I gathered from your question, there won't be any spaces in the elements of the array.

  • Related