How do I process different delimiters in a RegEx expression with Java? - java

I am working on creating a program for my course, in which I am required to divide the string: This;is;the;first;line;;This;is;the;second;line!;;;;Done!;;.
In the requirements, I need to read a single semicolon as a space, and a double semicolon as a new line. How do I create a regular expression in the useDelimiter() method that allows me to parse through and differentiate between both ; and ;;? Thank you!
Assignment Excerpt:
Instead of hard-coding the string, this time you will read it from the console. Study the useDelimiter() method and use it to set the delimiter for the scanner input. This time allow either colons or semicolons as the delimiters. One might prefer to use the String Tokenizer here, but don’t -- use the Scanner’s useDelimiter() method to set the delimiter in the Scanner and process each token as it comes.
import java.util.Scanner;
public class Hw3p2 {
public static void main(String[] args) {
// Initializes scanner class.
Scanner input = new Scanner(System.in);
// Prompts user for input.
System.out.println("Enter the string you wish to filter & parse: ");
// Reads user input.
String filterString = input.nextLine();
// Initiates new scanner reading the user inputted string.
Scanner a = new Scanner(filterString);
a.useDelimiter(";|;;");
System.out.printf("\n");
// Loop that parses through string while there are more tokens.
while(a.hasNext()) {
System.out.print(a.next());
}
}
}
The Expected output is to be:

You may use this code:
public class Hw3p2 {
public static void main(String[] args) {
// Initializes scanner class.
Scanner input = new Scanner(System.in).useDelimiter(";;");
// Prompts user for input.
System.out.print("Enter the string you wish to filter & parse: ");
// Reads user input.
while(input.hasNext()) {
String filterString = input.next();
//System.err.println("filterString: " + filterString);
// Initiates new scanner reading the user inputted string.
Scanner a = new Scanner(filterString).useDelimiter(";");
// Loop that parses through string while there are more tokens.
while(a.hasNext()) {
System.out.print(a.next() + " ");
}
System.out.println();
a.close();
}
input.close();
}
}
Output:
Enter the string you wish to filter & parse: This;is;the;first;line;;This;is;the;second;line!;;;;Done!;;
This is the first line
This is the second line!
Done!
Note use of outer scanner with delimiter ;; and an inner one with ;.

Related

Can I input all the command at once?

I implemented a java program with some methods. Next I created a main class which will call the related method by entering a word.
for example:
Enter {A|B|C|D|E} to call method. A=method one B = method two...etc
A<--this is the user input
Enter Number:<--the first Scanner input of method A
123<--Input 1
Enter words:<-- the second Scanner input of method A
ABC<--Input 2
123ABC<--The output method A
Enter {A|B|C|D|E} to call method. A=method one B = method two...etc
B<--this is the user input
Enter Number 1:<--the first Scanner input of method B
100<--Input 1
Enter Number 2:<-- the second Scanner input of method B
50<--Input 2
150<--The output method B
Code of Method A {
String output;
private static Scanner keyboard = new Scanner(System.in);
System.out.println("Enter Number:");
String no = keyboard.nextLine();
System.out.println("Enter Words:");
String words = keyboard.nextLine();
//do something...
System.out.println(output);
}
Code of Main class{
private static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args){
Main main = new Main();
main.run();
}
public void run() {
boolean running = true;
while (running) {
displayMenu();
String command = keyboard.nextLine();
String[] parts = command.split("^");
if ("A".equalsIgnoreCase(command)) {
//call method A
} else if ("B".equalsIgnoreCase(command)) {
//call method B
} else if....etc
System.out.println();
}
what I want is input
A123 , ABCB100,50 at once
then the system will print the output of method A (123ABC) and B (150) for me.
What I want is input A into "keyboard", input 123 into "no" and input ABC into "words" at once
How can I do it?
As long as your don't close your Scanner (or its underlying input stream), the yet-to-read tokens will remain accessible for later use : read two lines (or 4 tokens - the comma is one) and "B\n100,50" will remain.
If you're asking how to provide this kind of input, it depends on your invokation method. If executed from bash, I'd use the following :
echo """A
123 , ABC
B
100,50""" | java ...
If you're asking how to dynamically invoke a method from its name, check the reflection API. Oracle's tutorial is a good resource in my opinion, here's a link to its section on retrieving and invoking methods.
There are 2 ways to do that.
First:
Instead of giving input directly in the console, first write all the data input somewhere and just copy it and paste it in the console.
Second:
You can use hasNexLine() and send EOF through keyboard by pressing ctrl+d.
Code:
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
while(s.hasNextLine())
{
sb.append(s.nextLine());
}
System.out.println(sb.toString());
}
Provide all your input and press ctrl+d to stop taking input.

Why won't Java print last word here?

Why does this print the entire string "1fish2fish"...
import java.util.Scanner;
class Main {
public static void main(String[] args) {
String input = "1,fish,2,fish";
Scanner sc = new Scanner(input);
sc.useDelimiter(",");
System.out.print(sc.nextInt());
System.out.println(sc.next());
System.out.print(sc.nextInt());
System.out.println(sc.next());
}
}
But this only prints "1fish2" even though I enter "1,fish,2,fish"?
import java.util.Scanner;
class Main {
public static void main(String[] args) {
System.out.println("Enter your string: ");
Scanner sc = new Scanner(System.in);
sc.useDelimiter(",");
System.out.print(sc.nextInt());
System.out.println(sc.next());
System.out.print(sc.nextInt());
System.out.println(sc.next());
}
}
In the first case, the scanner doesn't need the last delimiter, as it knows that there are no more characters. So, it knows that the last token is 'fish' and there are no more characters to process.
In the case of a System.in scan, the fourth token is considered as completed only when the fourth ',' is entered in the system input.
Note that white spaces are considered as delimiters by default. But, once you specify an alternate delimiter using useDelimiter, then white space characters don't demarcate tokens any more.
In fact, your first trial can be modified to prove that white space characters are not delimiters any more...
public static void main(String[] args) {
String input = "1,fish,2,fish\n\n\n";
Scanner sc = new Scanner(input);
sc.useDelimiter(",");
System.out.print(sc.nextInt());
System.out.println(sc.next());
System.out.print(sc.nextInt());
System.out.println(sc.next());
System.out.println("Done");
sc.close();
}
The new line characters will be treated as part of the fourth token.
I checked the first snippet; it is correctly printing -
1fish
2fish
Link - http://code.geeksforgeeks.org/jK1Mlu
Please let us know if your expectation is different.
Scanner waits for you to enter another ',' so when you will enter ',' then after that it will immediately prints fish after 1fish2.
so Pass 1,fish,2,fish, instead of 1,fish,2,fish

Meaning of input.nextLine()

I am taking a course on Java and the "instructor" is introducing how to get the user's input. I don't understand what is the "input.nextLine()" for.
Here's the code:
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
// Create Scanner object
Scanner input = new Scanner(System.in);
// Output the prompt
System.out.println("Type in something: ");
// Wait for the user to enter a line of text
String line = input.nextLine();
// Tell them what they entered
System.out.println("You just typed " + "'" + line + "'.");
}
}
It is for reading the next line from the input stream.
Scanner input = new Scanner(System.in);
// create a new reference and refer to the input stream.
String line = input.nextLine();
// read the next line from the stream (entered from the keyboard) and store it in a String variable named line
The java.util.Scanner.nextLine() method 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.
It returns the next line, waiting if necessary for the line to become available (i.e. the user types out something and presses enter).

How to take a scanner object and make it a String

I need help doing the following:
receiving input using Scanner class (I got this)
taking input from scanner and making it a String
use replaceAll to remove numbers 0-9 from user input.
The below code is what I have so far but it is only returning user input and not removing numbers:
public static void main(String[] args) {
Scanner firstname = new Scanner(System.in);
System.out.println("Please enter your first name:");
String firstname1 = firstname.next();
firstname1.replaceAll("[^0-9]","");
System.out.println(firstname1);
Updated Code. Thank you Hovercraft. I am now investigating how to retrieve all alpha characters as with the code below, I am only getting back the letters prior to the numeric values entered by the user:
import java.util.Scanner;
public class Assignment2_A {
public static void main(String[] args) {
Scanner firstname = new Scanner(System.in);
System.out.println("Please enter your first name:");
String firstname1 = firstname.next();
firstname1 = firstname1.replaceAll("[^A-Z]","");
System.out.println(firstname1);
String input = yourScannerObject.nextLine ();
where "yourScannerObject" is the name you give your scanner.
What method did you use to scan? is it {scanner object name}.next() ?
if so you have got a string and all that you have to do is create some string, and save the input to it, e.g.:
String str="";
str = {scanner object name}.next();
before using anything in java, I would advise you to read the API :
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html#next()
receiving input using Scanner class (I got this)
taking input from scanner and making it a String
use replaceAll to remove numbers 0-9 from user input.
Here's an example:
String in;
Scanner scan = new Scanner("4r1e235153a6d 6321414t435hi4s 4524str43i5n5g");
System.out.println(in = (scan.nextLine().replaceAll("[0-9]", ""))); // use .next() for space or tab
Output:
read this string
The problem in your code is the regex "[^A-Z]" is set to remove all non-alphabet capital characters. This means you remove all lower case as well. You could say "[^a-zA-Z]", but then you're also removing special characters.

How do I make Java register a string input with spaces?

Here is my code:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String question;
question = in.next();
if (question.equalsIgnoreCase("howdoyoulikeschool?") )
/* it seems strings do not allow for spaces */
System.out.println("CLOSED!!");
else
System.out.println("Que?");
When I try to write "how do you like school?" the answer is always "Que?" but it works fine as "howdoyoulikeschool?"
Should I define the input as something other than String?
in.next() will return space-delimited strings. Use in.nextLine() if you want to read the whole line. After reading the string, use question = question.replaceAll("\\s","") to remove spaces.
Since it's a long time and people keep suggesting to use Scanner#nextLine(), there's another chance that Scanner can take spaces included in input.
Class Scanner
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
You can use Scanner#useDelimiter() to change the delimiter of Scanner to another pattern such as a line feed or something else.
Scanner in = new Scanner(System.in);
in.useDelimiter("\n"); // use LF as the delimiter
String question;
System.out.println("Please input question:");
question = in.next();
// TODO do something with your input such as removing spaces...
if (question.equalsIgnoreCase("howdoyoulikeschool?") )
/* it seems strings do not allow for spaces */
System.out.println("CLOSED!!");
else
System.out.println("Que?");
I found a very weird thing in Java today, so it goes like -
If you are inputting more than 1 thing from the user, say
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
So, it might look like if we run this program, it will ask for these 3 inputs and say our input values are 10, 2.5, "Welcome to java"
The program should print these 3 values as it is, as we have used nextLine() so it shouldn't ignore the text after spaces that we have entered in our variable s
But, the output that you will get is -
10
2.5
And that's it, it doesn't even prompt for the String input.
Now I was reading about it and to be very honest there are still some gaps in my understanding, all I could figure out was after taking the int input and then the double input when we press enter, it considers that as the prompt and ignores the nextLine().
So changing my code to something like this -
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
sc.nextLine();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
does the job perfectly, so it is related to something like "\n" being stored in the keyboard buffer in the previous example which we can bypass using this.
Please if anybody knows help me with an explanation for this.
Instead of
Scanner in = new Scanner(System.in);
String question;
question = in.next();
Type in
Scanner in = new Scanner(System.in);
String question;
question = in.nextLine();
This should be able to take spaces as input.
This is a sample implementation of taking input in java, I added some fault tolerance on just the salary field to show how it's done. If you notice, you also have to close the input stream .. Enjoy :-)
/* AUTHOR: MIKEQ
* DATE: 04/29/2016
* DESCRIPTION: Take input with Java using Scanner Class, Wow, stunningly fun. :-)
* Added example of error check on salary input.
* TESTED: Eclipse Java EE IDE for Web Developers. Version: Mars.2 Release (4.5.2)
*/
import java.util.Scanner;
public class userInputVersion1 {
public static void main(String[] args) {
System.out.println("** Taking in User input **");
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name : ");
String s = input.nextLine(); // getting a String value (full line)
//String s = input.next(); // getting a String value (issues with spaces in line)
System.out.println("Please enter your age : ");
int i = input.nextInt(); // getting an integer
// version with Fault Tolerance:
System.out.println("Please enter your salary : ");
while (!input.hasNextDouble())
{
System.out.println("Invalid input\n Type the double-type number:");
input.next();
}
double d = input.nextDouble(); // need to check the data type?
System.out.printf("\nName %s" +
"\nAge: %d" +
"\nSalary: %f\n", s, i, d);
// close the scanner
System.out.println("Closing Scanner...");
input.close();
System.out.println("Scanner Closed.");
}
}

Categories

Resources