I tried to use a Split Function to separate the input String by Space character into a String Array but nothing happened.
I used this code:
String a;
String[] b = new String[4];
a=input.next(); // input : 1 2 3 4
b=a.split(" "); // or b=a.split("\\s+");
/* output : b[0]=1 , b[1]=Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
*/
But when I defined a value like this:
String a="1 2 3 4";
Everything is done successfully.
What should I do?
Assuming input is a Scanner...
The next() method will return the next token, and by default, Scanner separates input by whitespace. You don't need to split the input when Scanner is tokenizing the input for you already.
A Scanner breaks its input into tokens using a delimiter pattern,
which by default matches whitespace. The resulting tokens may then be
converted into values of different types using the various next
methods.
Alternatively, you could use input.nextLine() to get the entire line, then you can split the line yourself.
Related
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?
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.
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.
Modified the regex pattern in replaceAll() method :
String[] strArr = s.nextLine().replaceAll("[ \"{}\\]\\[(new|String)]", "").split(",");
Output on printing the String Array strArr:
A:22
D:3
C:4
A:-22
I know pipe is a special character and I need to use:
Scanner input = new Scanner(System.in);
String line = input.next();
String[] columns = line.split("\\|");
to use the pipe as a delimiter. But it doesn't work as desired when I parse from the command line.
e.g.
When I parse from a file, this just works. However, when the input has a white space, whenever I parse the input from command line, it gives me out of bounds error, because it splits the word into two array element.
input
a|5|Hello|3
output:
columns[0] = "a";
columns[1] = "5";
columns[2] = "Hello";
columns[3] = "3";
bug:
input:
a|5|Hello World|3;
output:
columns[0] = "a";
columns[1] = "5";
columns[2] = "Hello";
columns[3] = "World";
columns[4] = "3";
I want columns[3] as "Hello World". How can I fix this?
I think you should get the data from user by using nextLine() instead of only next().
In my case its working fine just click here and check the source code ..
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input. nextLine() reads input including space between the words (that is, it reads till the end of line n).
A Scanner breaks its input into tokens using a delimiter pattern,
which by default matches whitespace. Source
To overcome, you should use nextline() method instead.
String line = input.nextline();
I am having difficulty splitting a string of user input into two words. The string is in the format "word1, word2", and I am trying to create two separate strings of word1 and word2. Here is my attempt:
System.out.println("Enter the two words separated by a comma, or 'quit':");
Scanner sc = new Scanner(System.in);
String input = sc.next();
while(!input.equals("quit")){
input.replaceAll("\\s+","");
System.out.println(input); //testing
int index1 = input.indexOf(",");
String wordOne = input.substring(0, index1);
String wordTwo = input.substring(index1+1, input.length() );
if(wordOne.length()!=wordTwo.length()){
System.out.println("Sorry, word lengths must match.");
}
System.out.println("Enter the two words separated by a comma, or 'quit':");
input = sc.next();
}
This is the output:
Enter the two words separated by a comma, or 'quit':
leads, golds
leads,
Sorry, word lengths must match.
Enter the two words separated by a comma, or 'quit':
golds
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1911)
at Solver.main(Solver.java:22) //this points to the line "String wordOne = input.substring(0, index1);"
Could someone please tell me where I am going wrong?
Why don't you try:
input.split(",");
This will give you an String array. From JavaDocs.
public String[] split(String regex)
Splits this string around matches of the given regular expression.
This method works as if by invoking the two-argument split method with
the given expression and a limit argument of zero. Trailing empty
strings are therefore not included in the resulting array.
Update: Since, you are using sc.next() which will take a single word unless it sees a space at which it will terminate the input. You should instead use sc.nextLine() to keep the complete input as user inputs.
next()
public java.lang.String next()
Finds and returns the next complete
token from this scanner. A complete token is preceded and followed by
input that matches the delimiter pattern. This method may block while
waiting for input to scan, even if a previous invocation of hasNext
returned true.
nextLine()
public java.lang.String nextLine()
Advances this scanner past the
current line and returns the input that was skipped. This method
returns the rest of the current line, excluding any line separator at
the end. The position is set to the beginning of the next line. Since
this method continues to search through the input looking for a line
separator, it may buffer all of the input searching for the line to
skip if no line separators are present.
The problem is that you are using sc.next() instead of sc.nextLine(). I can see that in your input you are entering "leads, gold" where leads, is followed by a space. In this case sc.next() will return just "leads," and not "leads, gold"
So I want to get the length of the input in java, but the (String.length()) doesn't produce a satisfying result.
So when I type this code:
String c = "hi hello";
System.out.print(c.length());
I get 8 which is correct
but when I type this code:
Scanner s = new Scanner(System.in);
String c = s.next();
System.out.print(c.length());
For "hi hello" is the input, I get 2 not 8. I tried again with different inputs and I found that string.length() have a problem with spaces in inputs. for example, if the input was "123456 78" the output would be 6 not 9. Can you tell me how to get the full length of the input? Thanks in advance
Replace s.next() to s.nextLine() and you will get the desired result.
next() finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.
nextLine() returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
-> "123456 78"
s.next().length() -> "123456".length() -> 6
s.nextLine().length() -> "123456 78".length() -> 9
Use nextLine() rather than next() as next() can read the input only till the space.
nextLine() reads input including space between the words (that is, it reads till the end of line \n)
Scanner s = new Scanner(System.in);
String c = s.nextLine();
System.out.print(c.length());
The java.util.Scanner.next() method finds and returns the next
complete token from this scanner. A complete token is preceded and
followed by input that matches the delimiter pattern.
The delimiter here is " ".
You get 2 as length because it says the length of "hi" is 2. If you
want the length of complete string use nextLine() it counts upto "\n"
I am trying to split the input sentence based on space between the words. It is not working as expected.
public static void main(String[] args) {
Scanner scaninput=new Scanner(System.in);
String inputSentence = scaninput.next();
String[] result=inputSentence.split("-");
// for(String iter:result) {
// System.out.println("iter:"+iter);
// }
System.out.println("result.length: "+result.length);
for (int count=0;count<result.length;count++) {
System.out.println("==");
System.out.println(result[count]);
}
}
It gives the output below when I use "-" in split:
fsfdsfsd-second-third
result.length: 3
==
fsfdsfsd
==
second
==
third
When I replace "-" with space " ", it gives the below output.
first second third
result.length: 1
==
first
Any suggestions as to what is the problem here? I have already referred to the stackoverflow post How to split a String by space, but it does not work.
Using split("\\s+") gives this output:
first second third
result.length: 1
==
first
Change
scanner.next()
To
scanner.nextLine()
From the javadoc
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
Calling next() returns the next word.
Calling nextLine() returns the next line.
The next() method of Scanner already splits the string on spaces, that is, it returns the next token, the string until the next string. So, if you add an appropriate println, you will see that inputSentence is equal to the first word, not the entire string.
Replace scanInput.next() with scanInput.nextLine().
The problem is that scaninput.next() will only read until the first whitespace character, so it's only pulling in the word first. So the split afterward accomplishes nothing.
Instead of using Scanner, I suggest using java.io.BufferedReader, which will let you read an entire line at once.
One more alternative is to go with buffered Reader class that works well.
String inputSentence;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
inputSentence=br.readLine();
String[] result=inputSentence.split("\\s+");
rintln("result.length: "+result.length);
for(int count=0;count<result.length;count++)
{
System.out.println("==");
System.out.println(result[count]);
}
}