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);
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().
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
This question already has answers here:
Split string on spaces in Java, except if between quotes (i.e. treat \"hello world\" as one token) [duplicate]
(1 answer)
Java Regex for matching quoted string with escaped quotes
(1 answer)
Closed 8 years ago.
For example, input will be like:
AddItem rt456 4 12 BOOK “File Structures” “Addison-Wesley” “Michael Folk”
and I want to read all by using scanner and put it in a array.
like:
info[0] = rt456
info[1] = 4
..
..
info[4] = File Structures
info[5] = Addison-Wesley
So how can I get the string between quotes?
EDIT: a part of my code->
public static void main(String[] args) {
String command;
String[] line = new String[6];
Scanner read = new Scanner(System.in);
Library library = new Library();
command = read.next();
if(command.matches("AddItem"))
{
line[0] = read.next(); // Serial Number
line[1] = read.next(); // Shelf Number
line[2] = read.next(); // Shelf Index
command = read.next(); // Type of the item. "Book" - "CD" - "Magazine"
if(command.matches("BOOK"))
{
line[3] = read.next(); // Name
line[4] = read.next(); // Publisher
line[5] = read.next(); // Author
Book yeni = new Book(line[0],Integer.parseInt(line[1]),Integer.parseInt(line[2]),line[3],line[4],line[5]);
}
}
}
so I use read.next to read String without quotes.
SOLVED BY USING REGEX AS
read.next("([^\"]\\S*|\".+?\")\\s*");
You can use StreamTokenizer for this in a pinch. If operating on a String, wrap it with a StringReader. If operating on a file just pass your Reader to it.
// Replace “ and ” with " to make parsing easier; do this only if you truly are
// using pretty quotes (as you are in your post).
inputString = inputString.replaceAll("[“”]", "\"");
StreamTokenizer tokenizer = new StreamTokenizer(new StringReader(inputString));
tokenizer.resetSyntax();
tokenizer.whitespaceChars(0, 32);
tokenizer.wordChars(33, 255);
tokenizer.quoteChar('\"');
while (tokenizer.nextToken() != StreamTokenizer.TT_EOF) {
// tokenizer.sval will contain the token
System.out.println(tokenizer.sval);
}
You will have to use an appropriate configuration for non-ASCII text, the above is just an example.
If you want to pull numbers out separately, then the default StreamTokenizer configuration is fine, although it uses double and provides no int numeric tokens. Annoyingly, it is not possible to simply disable number parsing without resetting the syntax from scratch.
If you don't want to mess with all this, you could also consider changing the input format to something more convenient, as in Steve Sarcinella's good suggestion, if it is appropriate.
As a reference, take a look at this: Scanner Docs
How you read from the scanner is determined by how you will present the data to your user.
If they are typing it all on one line:
Scanner scanner = new Scanner(System.in);
String result = "";
System.out.println("Enter Data:");
result = scanner.nextLine();
Otherwise if you split it up into input fields you could do:
Scanner scanner = new Scanner(System.in);
System.out.println("Enter Identifier:");
info[0] = scanner.nextLine();
System.out.println("Enter Num:");
info[1] = scanner.nextLine();
...
If you want to validate anything before assigning the data to a variable, try using scanner.next(""); where the quotes contain a regex pattern to match
EDIT:
Check here for regex info.
As an example, say I have a string
String foo = "The cat in the hat";
regex (Regular Expressions) can be used to manipulate this string in a very quick and efficient manner. If I take that string and do foo = foo.replace("\\s+", "");, this will replace any whitespace with nothing, therefore eliminating whitespace.
Breaking down the argument \\s+, we have \s which means match any character that is whitespace.
The extra \ before \s is a an escape character that allows the \s to be read properly.
The + means match the previous expression 0 or more times. (Match all).
So foo, after running replace, would be "TheCatInTheHat"
Same this regex logic can apply to scanner.next(String regex);
Hopefully this helps a bit more, I'm not the best at explanation :)
An alternative using a messy regular expression:
public static void main(String[] args) throws Exception {
Pattern p = Pattern.compile("^(\\w*)[\\s]+(\\w*)[\\s]+(\\w*)[\\s]+(\\w*)[\\s]+(\\w*)[\\s]+[“](.*)[”][\\s]+[“](.*)[”][\\s]+[“](.*)[”]");
Matcher m = p.matcher("AddItem rt456 4 12 BOOK “File Structures” “Addison-Wesley” “Michael Folk”");
if (m.find()) {
for (int i=1;i<=m.groupCount();i++) {
System.out.println(m.group(i));
}
}
}
That prints:
AddItem
rt456
4
12
BOOK
File Structures
Addison-Wesley
Michael Folk
I assumed quotes are as you typed them in the question “” and not "", so they dont need to be escaped.
You can try this. I have prepared the demo for your requirement
public static void main(String args[]) {
String str = "\"ABC DEF\"";
System.out.println(str);
String str1 = str.replaceAll("\"", "");
System.out.println(str1);
}
After reading just replace the double quotes with empty string
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);