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.
Related
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 am printing out the contents of a txt file while skipping over any numbers that are in the file.
The file I am using looks like this:
one two 3 three four
five six 7 eight
I have tried using input2.next() or input2.nextline() after System.out.print(token), but I either get an error or it doesn't read the next line accurately.
import java.util.*;
import java.io.*;
public class ScannerClass {
public static void main(String[] args) throws FileNotFoundException {
System.out.print("Enter file name and extension: ");
Scanner input = new Scanner(System.in);
File file = new File(input.next());
Scanner input2 = new Scanner(file);
String token;
//this will print out the first line in my txt file, I am having trouble
//reading the next line in the file!
while ((token = input2.findInLine("[\\p{Alpha}\\p{javaWhitespace}]+")) != null) {
System.out.print(token);
}
}
}
The output is:
one two three four
What I would like to see is the whole txt file less any numbers such as:
one two three four
five six eight
One main problem with your reg exp is that it matches only one part of the line first before the digit and then after the digit while the findInLine somehow advances the line counter.
So here is a different solution using your reg exp pattern but I have separated the reading from the file from the matching logic
Pattern p = java.util.regex.Pattern.compile("[\\p{Alpha}\\p{javaWhitespace}]+");
while (input2.hasNextLine()) {
String line = input2.nextLine();
Matcher m = p.matcher(line);
while (m.find()) {
System.out.print(m.group()); //Prints each found group
}
System.out.println();
}
You can add this RegEx;
import java.util.*;
import java.io.*;
public class ScannerClass {
public static void main(String[] args) throws FileNotFoundException {
System.out.print("Enter file name and extension: ");
Scanner reader = new Scanner(System.in);
reader = new Scanner(new File(reader.next()));
Pattern p = Pattern.compile("[a-zA-Z_]+");
Matcher m = null;
while (reader.hasNext()){
String nextLine = reader.nextLine();
m = p.matcher(nextLine);
while(m.find()) {
System.out.printf("%s ",m.group());
}
System.out.println();
}
}
}
May not be the most optimum but it'll work. Each loop iteration will split the current line into an array of strings delimited by a number (\\d+), then each array element (the alphabet words and whitespace in this case) will be streamed and joined into a single string.
while (input2.hasNextLine()) {
String[] nonNumbers = input2.nextLine().split("\\d+");
System.out.println(Arrays.stream(nonNumbers).collect(Collectors.joining()));
}
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
I have a txt file containing words and their abbreviations that looks like this
one,1
two,2
you,u
probably,prob
...
I have read the txt file into a string splitting it and replacing the commas with spaces like so..
public String shortenWord( String inWord ) {
word = inWord;
String text = "";
try {
Scanner sc = new Scanner(new File("abbreviations.txt"));
while (sc.hasNextLine()) {
text = text + sc.next().replace(",", " ") + " ";
}
// System.out.println(text);
//System.out.println(word);
if (text.contains(word)) {
System.out.println(word);
}
else {
System.out.println("nope");
}
}
catch ( FileNotFoundException e ) {
System.out.println( e );
}
return text;
}
The user must input a word that they want abbreviated and it will return the abbreviated version of the word.
class testit{
public static void main(String[] args){
Shortener sh = new Shortener();
sh.shortenWord("you");
}
}
I have it returning the word they entered if it is found but i want it to return the word next to it in the file which would be the abbreviated version.
eg. printed string 'text' looks like ..
one 1 two 2 three 3 you u probably prob hello lo
I want them to be able to enter 'you' the program find 'you' and then prints 'u' which is the next string over separated by a space
Removing the comma achieves nothing, so don't do it.
I would first split:
String[] text = sc.next().split(",");
Then compare with the first part of the split:
if (text[0].equals(word))
and if true, return the second part of the split:
return text[1];
Part of the logic looks like below:
Map<String,String> myShortHand = new HashMap<String, String>();
Scanner sc = new Scanner(new File("abbreviations.txt"));
while (sc.hasNextLine()) {
String text[] = sc.next().split(",");
myShortHand.put(text[0],text[1]);
}
Now get the details from map like
myShortHand.get("one");
I want to give a sentence from standard input and my sentence might have a space between it. I want to split the string. How to take input from standard input device?
I can do it with hard coded string.
String speech = "Four score and seven years ago";
String[] result = speech.split(" ");
You can take input from user with nextLine() method of Scanner class
import java.util.Scanner;
public class SplitString
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in/*Taking input from standard input*/);
System.out.print("Enter any string=");
String userInput = scan.nextLine();//Taking input from user
String splittedString[] = userInput.split(" ");//Splitting string with space
}
}
Store the input in a StringBuilder, line by line.
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
String line;
line = reader.readLine();
Then you can split your result.
String[] result = line.split("\\s");