Hello I am using the following java code to split user input into individual words -
String command = scanner.next();
command = command.toLowerCase();
String[] words = command.split(" ");
however when i try to print " words[1] " for an input with two or more words it throws a ArrayIndexOutOfBoundsException. It would seem that words[1] would simply be the second word in the sentence but the array does not contain it.
Instead of scanner.next(), try
String command = scanner.nextLine();
This will make sure you read all the words.
From the Scanner API:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
While the javadoc for Scanner#next() states:
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.
So in your case scanner.next() will return a word with no whitespace, as whitespace is how your scanner likely knows when to stop scanning.
You might want to use Scanner#nextLine() or something of the sort instead.
Try this one, and make sure you have read all input words
Scanner scanner = Scanner(System.in);
String command = scanner.nextLine();
command = command.toLowerCase();
String[] words = command.split(" ");
Now you can print
words[1]
if you have valid index value,
Related
I'm trying to take an input using Scanner class in Java.
My code is:
Scanner scan = new Scanner( System.in);
String newline = scan.next();
My input is something like:
india gate;25;3
and I'm trying to replace the whole string above with a new string:
new delhi;23;2
using
.replace(str1, str2)
The problem is it's only replacing the first word in the string and the output is something like:
india delhi;25;3
How can I take it as a whole string using Scanner?
Use ; as delimiter like this
while (scanner.hasNextLine()) {
lineScanner = new Scanner(scanner.nextLine());
lineScanner.useDelimiter(";");
String article = lineScanner.next();
// and so on...
}
use .replaceAll("india gate;25;3", "new delhi;23;2");
output
new delhi;23;2
You should read up on how the Scanner class works. Basically by default, it uses whitespace as the delimiter for next(). This means that when you call next(), it reads until it finds whitespace, then it returns what it read. So when you call next() on "india gate;25;3", it reads "india" and then hits a space. So it returns you "india". If you want to read until a newline instead (which it looks like you do), you want to use nextLine().
I'm trying to replace multiple substrings in a string, for example I have the following string wordlist
one two three
Where I want to replace \t tab characters with \r\n new line characters.
I define the separator variable as \n and replacement variable as \r\n.
Then I use wordlist = wordlist.replaceAll(separator, replacement); to replace all the characters, but when I display the wordlist again, it gives me the following result
onerntwornthree
I also tried splitting the wordlist by the substring separator into an array and then joining it again word by word into a new string separated by the replacement, but then it just gave me a result as
one\r\ntwo\r\nthree
Does anybody know how to solve this problem? In case you need it, here's the whole code:
System.out.print("Separator to replace: ");
separator = scanner.next( );
System.out.print("Replacement for separator: ");
replacement = scanner.next( );
wordlist = wordlist.replaceAll(separator, replacement);
Your input character for tab seems to be incorrect.
This code gives
String wordlist="one two three";
wordlist = wordlist.replaceAll("\t", "\r\n");
System.out.println(wordlist);
This output-
one
two
three
What you want to do is probably to split the string and the write the different lines one at a time to a PrintStream. That way you can use println.
Java is a platform independent language, and new lines are platform dependent. Making use of PrintStream.println will make sure your code is portable.
Why do you set the separator to \n?, it should be \t I assume?
The following code works fine for jdoodle:
String s = "one\ttwo\tthree";
s = s.replaceAll("\t","\r\n");
System.out.println(s);
EDIT
The reason why this doesn't work is because you query the user for the separator and when he enters \t, this is a string with the first character \ and the second t and not an escape character.
You should use StringEscapeUtils.unescapeJava first.
Thus:
Scanner sc = new Scanner(System.in);
String separator = sc.nextLine();
separator = StringEscapeUtils.unescapeJava(separator);
String s = "one\ttwo\tthree";
s = s.replaceAll(separator,"\r\n");
System.out.println(s);
If org.apache.commons.lang.StringEscapeUtils is not available, you can do this explicitly:
Scanner sc = new Scanner(System.in);
String separator = sc.nextLine();
separator = separator.replaceAll("\\t","\t");
String s = "one\ttwo\tthree";
s = s.replaceAll(separator,"\r\n");
System.out.println(s);
demo
I want to use regex to remove all characters that are not in range from input string. Here is my code:
System.out.print("Input: ");
Scanner scan = new Scanner(System.in);
String input = scan.next();
scan.close();
String formattedInput = input.replaceAll("[^a-zA-Z]", "");
System.out.println(formattedInput);
Here how it works:
input: test,test test
testtest
Why it removed 3rd occurence of test? I wanted him to remove only "," and " " in that particular case.
It's because you used a scanner and calling scan.next only picked up test,test.
A nice way to debug these kinds of things would be to do a System.out.println(input) just before your statement that calls replaceAll.
Firstly, I'm very beginner, but I like to think I mildly understand things.
I'm trying to write a method that will store the user's input into a string. It works just fine, except if the user puts in a space. Then the string stops storing.
public static String READSTRING() {
Scanner phrase = new Scanner(System.in);
String text = phrase.next();
return text;
}
I think the problem is that phrase.next() stops scanning once it detects a space, but I would like to store that space in the string and continue storing the phrase. Does this require some sort of loop to keep storing it?
Use .nextLine() instead of .next().
.nextLine() will take your input until a newline character has been found (when you press enter, a newline character is added). This essentially allows you to get one line of input.
From the Javadoc, this is what we have:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
Either you can use phrase.nextLine() as suggested by others, or you can use Scanner#useDelimiter("\\n").
Try phrase.nextLine();. If I recall correctly, Scanner automatically uses spaces as delimiters.
Try
pharse.NextLine();
and you got do an array for limited words
String Stringname = {"word","word2"};
Random f = new Random(6);
Stringname = f.nextInt();
and you can convert an integer to string
int intvalue = 6697;
String Stringname = integer.ToString(intvalue);
I am trying to use a scanner to read a text file pulled with JFileChooser. The wordCount is working correctly, so I know it is reading. However, I cannot get it to search for instances of the user inputted word.
public static void main(String[] args) throws FileNotFoundException {
String input = JOptionPane.showInputDialog("Enter a word");
JFileChooser fileChooser = new JFileChooser();
fileChooser.showOpenDialog(null);
File fileSelection = fileChooser.getSelectedFile();
int wordCount = 0;
int inputCount = 0;
Scanner s = new Scanner (fileSelection);
while (s.hasNext()) {
String word = s.next();
if (word.equals(input)) {
inputCount++;
}
wordCount++;
}
You'll have to look for
, ; . ! ? etc.
for each word. The next() method grabs an entire string until it hits an empty space.
It will consider "hi, how are you?" as the following "hi,", "how", "are", "you?".
You can use the method indexOf(String) to find these characters. You can also use replaceAll(String regex, String replacement) to replace characters. You can individuality remove each character or you can use a Regex, but those are usually more complex to understand.
//this will remove a certain character with a blank space
word = word.replaceAll(".","");
word = word.replaceAll(",","");
word = word.replaceAll("!","");
//etc.
Read more about this method:
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#replaceAll%28java.lang.String,%20java.lang.String%29
Here's a Regex example:
//NOTE: This example will not work for you. It's just a simple example for seeing a Regex.
//Removes whitespace between a word character and . or ,
String pattern = "(\\w)(\\s+)([\\.,])";
word = word.replaceAll(pattern, "$1$3");
Source:
http://www.vogella.com/articles/JavaRegularExpressions/article.html
Here is a good Regex example that may help you:
Regex for special characters in java
Parse and remove special characters in java regex
Remove all non-"word characters" from a String in Java, leaving accented characters?
if the user inputed text is different in case then you should try using equalsIgnoreCase()
in addition to blackpanthers answer you should also use trim() to account for whitespaces.as
"abc" not equal to "abc "
You should take a look at matches().
equals will not help you, since next() doesn't return the file word by word,
but rather whitespace (not comma, semicolon, etc.) separated token by token (as others mentioned).
Here the java docString#matches(java.lang.String)
...and a little example.
input = ".*" + input + ".*";
...
boolean foundWord = word.matches(input)
. is the regex wildcard and stands for any sign. .* stands for 0 or more undefined signs. So you get a match, if input is somewhere in word.