java scanner.hasnext regex not working as expected - java

I'm trying to use a scanner to validate input on a simple CLI tool. The string can only contain letters, numbers and a forward slash. The regex that I have used ^[a-zA-Z0-9/]+$ works when I test it on http://www.freeformatter.com/java-regex-tester.html
Here is my code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String path = "";
String domain = "";
System.out.print("domain (eg. example.com):");
while (!sc.hasNext("(?=^.{1,254}$)(^(?:(?!\\d+\\.)[a-zA-Z0-9_\\-]{1,63}\\.?)+(?:[a-zA-Z]{2,})$)")) {
System.out.println("invalid domain name.");
sc.next();
}
domain = sc.next();
System.out.print("path:");
while (!sc.hasNext("^[a-zA-Z0-9/]+$")) {
System.out.println("Invalid path. Try again:");
sc.next();
}
path = sc.next();
}
}
Here is the output from my program:
domain (eg. example.com):si.com
path:/one/two/three
Invalid path. Try again:
/
Invalid path. Try again:
/one/two
Invalid path. Try again:
aaa
Invalid path. Try again:
Edit: The code above doesn't produce a match on strings such as /one/two, /one or /.
What am I doing wrong?
Is my regex correct?
Why is it the tester that I linked to produces different results?

The regex that you are using has a NOT ^ in the beginning. Because of that the regex is rejecting the path. Please try the following code.
Scanner scanner = new Scanner(System.in);
System.out.print("path:");
while (!scanner.hasNext("[a-zA-Z0-9/]+")) {
System.out.println("Invalid path. Try again:");
scanner.next();
}
String path = scanner.next();
System.out.println("path:"+path);
It should work

Related

How can I specify a numeric pattern with dashes in Java

For this code, I'm trying to get the user to input a pattern of numbers like "####-##-###" including the dashes. I have this code but it's returning an error.
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.Scanner;
public class StudentNumber {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter your student number: ");
int su;
Pattern p = Pattern.compile("[\\d]{4,}+[-?]{1,1}+[\\d]{2,}+[-?]{1,1}+[\\d]{3,}");
su = s.nextInt();
String input = String.valueOf(su);
Matcher m = p.matcher(input);
if (m.matches()){
System.out.println("You have successfully logged in.\nWelcome to your new dashboard!");
} else {
System.out.println("Invalid format. Try Again.");
}
}
}
the error is
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:943)
at java.base/java.util.Scanner.next(Scanner.java:1598)
at java.base/java.util.Scanner.nextInt(Scanner.java:2263)
at java.base/java.util.Scanner.nextInt(Scanner.java:2217)
at com.mycompany.studentnumber.StudentNumber.main(StudentNumber.java:21)
The error you're getting is because you have the dashes in the string and you're calling nextInt. You need to read the input as a string (with e.g. nextLine) then apply the regex to that and convert the parts to integers as appropriate.
su = s.nextInt();
Since the input you expect contains dashes, i.e. -, it isn't an int, it's a string, so use method nextLine (rather than method nextInt).
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StudentNumber {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter your student number: ");
Pattern p = Pattern.compile("[\\d]{4,}+[-?]{1,1}+[\\d]{2,}+[-?]{1,1}+[\\d]{3,}");
String input = s.nextLine();
Matcher m = p.matcher(input);
if (m.matches()){
System.out.println("You have successfully logged in.\nWelcome to your new dashboard!");
} else{
System.out.println("Invalid format. Try Again.");
}
}
}
Here is output from a sample run:
Enter your student number: 123-456-789
Invalid format. Try Again.
Here is another sample run:
Enter your student number: 1234-56-789
You have successfully logged in.
Welcome to your new dashboard!
Since,you are using - in int input, input cant't take it as integer, instead of it use next() method of Scanner() class.
String input = in.next()
Also, if you are using
Pattern p = Pattern.compile("[\\d]{4,}+[-?]{1,1}+[\\d]{2,}+[-?]{1,1}+[\\d]{3,}");
It also validates 111111-11-11111. To avoid this use instead
Pattern p = Pattern.compile("[\\d]{4}+[-?]{1}+[\\d]{2}+[-?]{1}+[\\d]{3}");

I have an error saying, syntax error on tokens, delete these tokens and many more, you can see for yourself

It says on the line String correctname="Pisay"; syntax error delete this token
package StringExple;
import java.util.Scanner;
public class StringExple{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String correctname=”Pisay";
System.out.println(“Enter your username:”);
String username = sc.nextLine();
if(username.equals(correctname)){
System.out.println(“Authorized user!!”);
} else
System.out.println(“Unauthorized user!!”);
if(username.equalsIgnoreCase(correctname)) {
System.out.println(“Authorized user!!”);
} else
System.out.println(“Unauthorized user!!”);
}
}
Couple of syntax issue is there, after fixing working.
Say Double Quotes " in print statements are not proper.
It's simple syntax issue if you concentrate then you should be able to fix them by own.
As you are doing 2 tests for both equals() and equalsIgnoreCase(), you may verify using equalsIgnoreCase() only because it will include equals() check also.
package sep2020;
import java.util.Scanner;
public class StringExple {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String correctname = "Pisay"; // String input
System.out.println("Enter your username:");
String username = sc.nextLine();
if (username.equalsIgnoreCase(correctname)) {
System.out.println("Authorized user!!");
} else
System.out.println("Unauthorized user!!");
}
}
Output:
Enter your username:
test
Unauthorized user!!
Enter your username:
Pisay
Authorized user!!
The adjusted code is below - the only issue is using ” opposed to ".
Also please format you code for future questions.
import java.util.Scanner;
class StringExple{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String name = "Pisay"; // String input
System.out.println("Enter your username:");
String username = sc.nextLine();
if(username.equals(correctname)){
System.out.println("Authorized user!!");
}else System.out.println("Unauthorized user!!");
if(username.equalsIgnoreCase(correctname)) System.out.println("Authorized user!!");
else System.out.println("Unauthorized user!!");
}
}

Scanner issue! Code is skipping the first user input and printing twice instead of once ONLY on the first iteration

https://courses.cs.washington.edu/courses/cse142/15sp/homework/6/spec.pdf
EDIT* Input Files are here:(sorry i'm new to stack overflow, hopefully this works)
I've also tried console.next() but it gives different errors than console.nextLine() in the rePlaceholder method. **
tarzan.txt - https://pastebin.com/XDxnXYsM
output for tarzan should look like this: https://courses.cs.washington.edu/courses/cse142/17au/homework/madlibs/expected_output_1.txt
simple.txt https://pastebin.com/Djc2R0Vz
clothes.txt https://pastebin.com/SQB8Q7Y8
this code should print to an output file you name.
Hello, I have a question about scanners because I don't understand why the code
is skipping the user input on the first iteration but works fine on the rest.
I'm writing a code to create a madlib program and the link will provide the explanation to the program but pretty much you have these placeholders in a text file and when you see one, you prompt for user input to replace it with your own words. However, my program always go through TWO placeholders first and only ask the user input for one, completely skipping the first placeholder. What is wrong with my code??? Also, how do you fix this? Everything else is running perfectly fine, only that the first line is consuming two placeholders so I'm always off by one.
Welcome to the game of Mad Libs.
I will ask you to provide various words
and phrases to fill in a story.
The result will be written to an output file.
(C)reate mad-lib, (V)iew mad-lib, (Q)uit? c
Input file name: tarzan.txt
Output file name: test.txt
Please type an adjective: Please type a plural noun: DD DDDD <--- why is it like this
Please type a noun: DDDD
Please type an adjective: DD
Please type a place:
========================================================================
package MadLibs;
import java.util.*;
import java.io.*;
public class MadLibs2 {
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
intro();
boolean isTrue = true;
while(isTrue) {
System.out.print("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
String choice = console.next();
if (choice.equalsIgnoreCase("c")) {
create(console);
}
else if (choice.equalsIgnoreCase("v")) {
view(console);
}
else if (choice.equalsIgnoreCase("q")) {
System.exit(0);
}
}
}
public static void view(Scanner console) throws FileNotFoundException {
System.out.print("Input file name: ");
String viewFile = console.next();
File existingMadLib = new File(viewFile);
Scanner printText = new Scanner(existingMadLib);
while(printText.hasNextLine()) {
System.out.println(printText.nextLine());
}
}
public static void create(Scanner console) throws FileNotFoundException {
System.out.print("Input file name: ");
String inputFile = console.next();
File newMadLib = new File(inputFile);
while(!newMadLib.exists()) {
System.out.print("File not found. Try again: ");
inputFile = console.next();
newMadLib = new File(inputFile);
}
System.out.print("Output file name: ");
String outputFile = console.next();
System.out.println();
PrintStream output = new PrintStream(new File(outputFile));
Scanner input = new Scanner(newMadLib);
while(input.hasNextLine()) {
String line = input.nextLine();
outputLines(line, output, console);
}
}
public static void outputLines(String line, PrintStream output, Scanner console) throws FileNotFoundException{
String s = "";
Scanner lineScan = new Scanner(line);
while(lineScan.hasNext()){
s = lineScan.next();
if(s.startsWith("<") || s.endsWith(">")) {
s = rePlaceholder(console, lineScan, s);
}
output.print(s + " ");
}
output.println();
}
public static String rePlaceholder(Scanner console, Scanner input, String token) {
String placeholder = token;
placeholder = placeholder.replace("<", "").replace(">", "").replace("-", " ");
if (placeholder.startsWith("a") || placeholder.startsWith("e") || placeholder.startsWith("i")
|| placeholder.startsWith("o") || placeholder.startsWith("u")) {
System.out.print("Please type an " + placeholder + ": ");
} else {
System.out.print("Please type a " + placeholder + ": ");
}
String change = console.nextLine();
return change;
}
public static void intro() {
System.out.println("Welcome to the game of Mad Libs.");
System.out.println("I will ask you to provide various words");
System.out.println("and phrases to fill in a story.");
System.out.println("The result will be written to an output file.");
}
}
in your rePlaceholder, change this line:
String change = console.nextLine();
Into this
String change = console.next();
Your problem is that nextLine doesn't wait for your output, just reads what it has in the console, waiting for a new line.
This is from the documentation to be a bit more precise on the explanation:
Since this method continues to search through the input looking for a
line separator, it may buffer all of the input searching for the line
to skip if no line separators are present.
UPDATE
After reading the comment, the previous solution will not work for multiple words.
After reading the output file, you are using next().
You need to make another call to nextLine() to clean the buffer of any newlines.
System.out.print("Output file name: ");
String outputFile = console.next();
console.nextLine(); // dummy call
System.out.println();

If user presses enter (without anything else) how can I print out the line ("please give a valid command")?

I have a program in java where the user have to give command. However if he presses enter without anything else the program stops and he gets this:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at UserInterface.main(UserInterface.java:43)
How is it possible that I can detect with the program that no line is found, and I print out the following ("please give a valid command").
I have tried this:
Scanner keyboard = new Scanner(System.in);
String command = keyboard.nextLine();
if (command == "") {
System.out.println("please give a valid command");
}
1) You can use the method isEmpty() from the Scanner itself to find out if an input is "nothing".
Try this:
Scanner keyboard = new Scanner(System.in);
String command = keyboard.nextLine();
if (command.isEmpty())
{
System.out.println("Please give a valid command.");
}
2) You can't compare two Strings like you did either. If you want to compare them you need to use the equals(Object anObject) method.
Here is an example:
Scanner keyboard = new Scanner(System.in);
String command = keyboard.nextLine();
if (command.equals("A String"))
{
System.out.print("Success");
}
Surround the statement with try/catch
...
String command = "";
try {
keyboard.nextLine();
} catch (Exceptionn e) {}
...
This will catch the exception.
Try this:
if(command.equals("")){
System.out.println("please give a valid command");
}

find in line java object , how to scan all the input?

im doing a test about findInLine object but its not working and i dont know why.
this is the code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("enter string: ");
String a = null;
String pattern ="(,)";
if (input.findInLine(pattern) != null){
a = input.nextLine();
}
System.out.println(a);
enter string: (9,9) <---------- that is what i wrote
this is the output: 9)
what i need to do if i want that the variable a will get all the string that i wrote like this: a = (9,9) and not a = 9)
Whatever I understood. You want to input some string and if that string gets matches to your pattern you need that to be shown in console. This will give you correct output.
import java.util.Scanner;
public class InputScan {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String a;
System.out.print("enter string: ");
String pattern = "\\(\\d+,\\d+\\)"; // Its regex
// For white spaces as you commented use following regex
// String pattern = "\\([\\s+]?\\d+[\\s+]?,[\\s+]?\\d+[\\s+]?\\)";
if ((a = input.findInLine(pattern)) != null){
System.out.println(a);
}
}
}
Java Regex Tutorial
Scanner findInLine()
Input:
(9,9)
Output :
(9,9)
You need to escape your brackets in the regex. Now the regex matches the comma.
Moreover, you should realize that Scanner.findInLine() also advances on the input.
Try
String pattern = "\\([0-9]*,[0-9]*\\)";
String found = input.findInLine(pattern);
System.out.println(found);
to verify this.

Categories

Resources