How can I specify a numeric pattern with dashes in Java - 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}");

Related

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!!");
}
}

How can I get my scanner to read the next line in the file?

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()));
}

java scanner.hasnext regex not working as expected

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

How to have my code run until I enter a number

I'm sorry if this is a silly question but I am fairly new to coding and so for my assignment I was given this code:
package webservice;
import webservice.Weather;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
System.out.print ("Enter the zip code : ");
java.lang.String zipCode = scan.nextLine();
try{
webservice.Weather service = new webservice.Weather();
webservice.WeatherSoap port = service.getWeatherSoap();
webservice.WeatherReturn result = port.getCityWeatherByZIP(zipCode);
System.out.print(result.getCity()+ " ");
System.out.println (result.getState());
System.out.println("Zip code " + zipCode);
System.out.println ("Current Temperature is " + result.getTemperature());
}
catch (Exception ex){
System.out.println("Error");
}
}//end main
}//end class
The code runs perfectly fine but I have to have it loop until i enter "0" for the zip code.
I'm fairly new to coding and I tried to review my previous works to try to incorporate a loop but I was never successful. Which loop would be the most efficient to have the code loop until the user enters "0" as the zip code?
Simply try this:
Scanner scan = new Scanner (System.in);
int zipCode;
while(scan.nextInt()!=0){
System.out.print ("Enter the zip code : ");
zipCode = scan.nextInt();
}
Use a while loop to verify your condition and use .nextInt() to get an int from the scanner.
Also there's a typo:
If you use :
import webservice.Weather;
You don't have to do this:
webservice.Weather service = new webservice.Weather();
It's simply:
Weather service = new Weather();
Take a look at Using Package Members for further information.
How about while loop?
String zipCode;
while(!"0".equals(zipCode = scan.nextLine())) {
//to do rest
}
Sample code:
import java.util.Scanner;
class Ideone
{
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
String zipCode;
while(!"0".equals(zipCode = sc.nextLine())) {
System.out.printf("zip code: %s\n", zipCode);
}
System.out.printf("last zip code: %s\n", zipCode);
}
}
I/P:
123
456
789
0
O/P:
zip code: 123
zip code: 456
zip code: 789
last zip code: 0
while loop would do your trick.
This is because while loop checks the condition first and then iterates over if the condition is found to be true. And in your case we need to check if the user has entered the correct value or not. If he has entered 0 we do not need to proceed further.

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