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);
Related
I am trying to break a string b = "x+yi" into a two integers x and y.
This is my original answer.
Here I removed trailing 'i' character with substring method:
int Integerpart = (int)(new Integer(b.split("\\+")[0]));
int Imaginary = (int)(new Integer((b.split("\\+")[1]).
substring(0, b.split("\\+")[1].length() - 1)));
But I found that the code below just works same:
int x = (int)(new Integer(a.split("\\+|i")[0]));
int y = (int)(new Integer(a.split("\\+|i")[1]));
Is there something special with '|'? I looked up documentation and many other questions but I couldn't find the answer.
The split() method takes a regular expression that controls the split. Try
"[+i]". The braces mark a group of characters, in this case "+" and "i".
However, that won't accomplish what you are trying to do. You will end up with something "b = x", "y", "". Regular expressions also offer search and capture capabilities. Look at String.matches(String regex).
You can use the given link for understanding of How Delimiters Works.
How do I use a delimiter in Java Scanner?
Another alternative Way
You can use useDelimiter(String pattern) method of Scanner class. The use of useDelimiter(String pattern) method of Scanner class. Basically we have used the String semicolon(;) to tokenize the String declared on the constructor of Scanner object.
There are three possible token on the String “Anne Mills/Female/18″ which is name,gender and age. The scanner class is used to split the String and output the tokens in the console.
import java.util.Scanner;
/*
* This is a java example source code that shows how to use useDelimiter(String pattern)
* method of Scanner class. We use the string ; as delimiter
* to use in tokenizing a String input declared in Scanner constructor
*/
public class ScannerUseDelimiterDemo {
public static void main(String[] args) {
// Initialize Scanner object
Scanner scan = new Scanner("Anna Mills/Female/18");
// initialize the string delimiter
scan.useDelimiter("/");
// Printing the delimiter used
System.out.println("The delimiter use is "+scan.delimiter());
// Printing the tokenized Strings
while(scan.hasNext()){
System.out.println(scan.next());
}
// closing the scanner stream
scan.close();
}
}
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().
What I'm trying to do here is have a user input a sentence or some type of string, then have the scanner search through the string to determine if there is an "e" or "E" in there. If the scanner finds either one of those it will replace them with "xyz." If they are not present then it should return "All is good!" The code I have thus far is:
public class Example {
String userInput;
Scanner in = new Scanner(System.in);
System.out.println("Please write a sentence.");
userInput = in.nextLine();
System.out.println(userInput.replace("e","xyz"));
System.out.println(userInput.replace("E","xyz"));
in.close();
}
As I think you can tell this really just prints the same line twice, once removing a lower case e and the other removing a capital E. I was looking for a way to combine the two replacements and then have it replace and print if it finds an e or just print "All is good!" if there are no "e"s.
This isn't related to Scanner at all really. Trivial approach:
String replaced = userInput.replace("e","xyz").replace("E","xyz");
String out = replaced.equals(userInput) ? "All is good!" : replaced;
System.out.println(out);
Or use replaceAll:
Pattern eE = Pattern.compile("[eE]");
String replaced = eE.matcher(userInput).replaceAll("xyz");
You're going to want to look into Pattern and its associate Matcher. This can give you precisely what you want.
While String#replaceAll gives you what you want, it's not entirely semantic; you can certainly replace all of the "e"s with "xyz" and then compare them to see if there was no change, but using Matcher gives you a bit more obvious control over the logic.
We first need to compile a regex, then build a matcher from the compiled regex. If we find a match, we can then replace the strings; otherwise, we can print out our value.
String userInput;
Scanner in = new Scanner(System.in);
System.out.println("Please write a sentence.");
userInput = in.nextLine();
Pattern pattern = Pattern.compile("[eE]");
Matcher matcher = pattern.matcher(userInput);
if(matcher.find()) {
System.out.println(matcher.replaceAll("xyz"));
} else {
System.out.println("All is good!");
}
System.out.println(userInput.replaceAll("[eE]","xyz"));
Also, don't close the System.in stream. It's not desirable to close that out in case some other part of your application wants to make use of it, or if you want to make use of it later.
Java strings are immutable, so you can't just call replace on userInput and expect it to be modified in place. You need to save the result of the function call.
I am trying to read a CSV file value by value using Scanner.useDelimiter(";").
However Scanner.nextLine() still returns the whole line instead of a single Value.
The CSV-file looks like this:
0.00034;0.1;0.3;0.6;1,00E-13
My code:
Scanner iStream = new Scanner(new InputStreamReader(new FileInputStream(file.cvs);
iStream.useDelimiter(";");
String[] test = new String[5];
for (int i = 0; i < 5; i++) {
test[i] = iStream.nextLine();
}
Result:
"0.00034;0.1;0.3;0.6;1,00E-13"
Expected Result:
"0.00034", "0.1", "0.3", "0.6", "1,00E-13"
Is this possible, or should I use String.split()?
Am I missing something?
Apart from the fact that this problem is ready-made for a parsing library such as OpenCSV, nextLine doesnt account for delimiter patterns. Use next instead
test[i] = iStream.next();
From the Java Scanner documentation:
public 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 literally answers your question. However, I am not sure about next's behaviour at the start and end becuase it has to be "preceded and followed" by the delimiter. Maybe someone can fill in on this?
You could add extra characters to your delimiter, like \netc.
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.