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().
Related
Let's say I had a scanner "in" that was assigned a one line CSV file, and I wanted to assign the values to an array, would I be able to do something like
String[] array = in.nextLine().split(",");
Yes, as noted in the comments. But you can also do this either reading from a string or from a file.
set the delimiter to match on 0 or more spaces, followed by a , followed by 0 or more spaces.
Scanner scanner = new Scanner("This, is , a ,test");
scanner.useDelimiter("\\s*,\\s*");
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
prints
This
is
a
test
I'm trying to store two variables from user input, one a char that's at the very beginning of input, the second a string that in the input follows the char. For my set of data sets there will always be a char at front and a string following after, separated by a whitespace, for example:
n It's a sunny day
n Nobody
Here is my code:
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
char charToSearch;
String inputString;
Scanner scnr = new Scanner(System.in);
charToSearch = scnr.next().charAt(0);
inputString = scnr.nextLine();
System.out.println(charToSearch);
System.out.println(inputString);
}
}
For the input 'z Today is Monday', I'm getting the result
z
Today is monday
I expected:
z
Today is Monday
As you can see there's a whitespace in front of the actual input. I want the string to contain no whitespace in front.
I assumed that the issue is something with the buffer (something I frankly do not understand well enough), so I tried to 'clear' the buffer and consume the whitespace by using scnr.next(), like this:
charToSearch = scnr.next().charAt(0);
scnr.next();
inputString = scnr.nextLine();
But that only leads to the string getting cut off, like this:
z
is Monday
I am using online IDE, if that is relevant here.
You can use the trim() function on the string. Simply use inputString.trim() function to clear the whitespace around the string.
You can call Scanner#skip to go past the whitespace.
scnr.skip("\\s+");
You could also use String#replaceAll to remove leading whitespace.
inputString = scnr.nextLine().replaceAll("^\\s+", "");
I would simplify it and read the entire line and then parse it with your logic. Like,
Scanner scnr = new Scanner(System.in);
String line = scnr.nextLine();
char charToSearch = line.charAt(0);
String inputString = line.substring(2);
System.out.println(charToSearch);
System.out.println(inputString);
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.
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,
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);