Determine if input string matches clock time using regular expressions in Java - java

I'm trying to determine if an input string is in a valid 24-hour date format (ie. hh:mm:ss). I'm using a few different logics and have been mostly successful with my test cases. My code currently fails for all the inputs I've tried (including the ones below).
The expression is supposed to work in the following way:
Inputting 11:24:10 should output Valid form
inputting 00:13:42 should output Valid form
Inputting 24:52:25 should output Invalid form
Inputting 05:62:55 should output Invalid form
Here's my code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.print("String to check: ");
String input = new Scanner(System.in).nextLine();
if (input.matches("((0|1)[0-9])|(2[0-3]):[0-5][0-9]:[0-5][0-9]")) {
System.out.println("Valid form");
} else {
System.out.println("Invalid form");
}
}
}
I've only recently started learning Java and I apologize if this question has been asked before (I googled!). Thanks for your help!

It should be
(((0|1)[0-9])|(2[0-3])):[0-5][0-9]:[0-5][0-9]
According to your regex
((0|1)[0-9])|(2[0-3]):[0-5][0-9]:[0-5][0-9]
It will match ((0|1)[0-9]) or (2[0-3]):[0-5][0-9]:[0-5][0-9]
You can also use non capturing group if you just want to match it as
(?:(?:(?:0|1)[0-9])|(?:2[0-3])):[0-5][0-9]:[0-5][0-9]
Your regex can be simplified further as by modifying hours part
[01][0-9]
IDEONE DEMO
EDIT
Little bit modification
(?:[01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]
REGEX DEMO

The issue is that your current regex will match (0|1)[0-9]) or (2[0-3]):[0-5][0-9]:[0-5][0-9]. You want your || operator to work on the (0|1)[0-9]) and (2[0-3]). So what you want is this:
((0|1)[0-9])|(2[0-3]):[0-5][0-9]:[0-5][0-9]
You also have a resource leak because you do not close your Scanner. It is best to store the new Scanner in a variable so that you can close it later. Here is the full code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.print("String to check: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
if (input.matches("(((0|1)[0-9])|(2[0-3])):[0-5][0-9]:[0-5][0-9]")) {
System.out.println("Valid form");
} else {
System.out.println("Invalid form");
}
sc.close();
}
}

Related

only one word of a sentence prints using replace method

As my class project I have written some codes that receives a sentence and if it has a special character by checking it's ASCII code it replaces it with another one. But unfortunately every time it replaces and shows only first word and deletes rest of the sentence. Please help me and if there's a better way for this it's appreciated.
here's my code:
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] arg) {
Scanner scanner = new Scanner(System.in);
String s = scanner.next();
if (s.contains("\u0626")) {
String result = s.replaceAll("\u0626", "\u0628");
System.out.println(result);
}
}
}

How to make java scanner accept more than one string input?

Hello i'm currently a beginner in Java. The code below is a while loop that will keep executing until the user inputs something other than "yes". Is there a way to make the scanner accept more than one answer? E.g. yes,y,sure,test1,test2 etc.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String ans = "yes";
while (ans.equals("yes"))
{
System.out.print("Test ");
ans = in.nextLine();
}
}
}
Use the or operator in your expression
while (ans.equals("yes") || ans.equals("sure") || ans.equals("test1"))
{
System.out.print("Test ");
ans = in.nextLine();
}
But if you are going to include many more options, it's better to provide a method that takes the input as argument, evaluates and returns True if the input is accepted.
Don't compare the user input against a value as loop condition?!
Respectively: change that loop condition to something like
while(! ans.trim().isEmpty()) {
In other words: keep looping while the user enters anything (so the loop stops when the user just hits enter).
You are looking for a method to check whether a given string is included in a List of string values. There are different ways to achieve this, one would be the use of the ArrayList contains() method to check whether your userinput in appears in a List of i.e. 'positive' answers you've defined.
Using ArrayList, your code could look like this:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
ArrayList<String> positiveAnswers = new ArrayList<String>();
positiveAnswers.add("yes");
positiveAnswers.add("sure");
positiveAnswers.add("y");
Scanner in = new Scanner(System.in);
String ans = "yes";
while (positiveAnswers.contains(ans))
{
System.out.print("Test ");
ans = in.nextLine();
}
}
}

How can I validate a phone number input of several variations?

My program currently validates the phone number only when it is ten consecutive numbers and characters and it closes when the word "exit" is typed. However, I was wondering how I could validate the numbers if they were also written as both, for example, (123)456-7890 and 123-456-7890
import java.util.Scanner;
public class Q2
{
public static void main(String[] args){
Scanner kb=new Scanner(System.in);
while (true){
System.out.print("Enter your phone number: ");
String number=kb.next();
if(number.equals("exit")){
System.exit(0);
}
boolean valid=true;
for(int i=0;i<number.length();i++){
if(number.length()!=10) valid=false;
}
if (valid) System.out.println("It is valid");
else System.out.println("It is invalid");
}
}
}
You do that by doing real validation.
Meaning: "validation" describes the process of checking your input against a set of rules. If the input conforms to all those rules, it is valid; otherwise it is not.
So, yes, checking the length was a first simple rule; but "length is 10" ... just turns out to not be a good rule. For example, "123456A90" has length 10; but is invalid.
What you can do instead (just giving you some ideas):
use regular expressions (or plain string parsing) in order to determine if your input string matches a certain pattern, like (nnn-nnnn-nnnn)
simple replace all "unwanted" characters, such as ( ) - with ""; and then you check if the resulting string has length 10.
So, the answer is: have a close look at your input and determine the properties that valid phone numbers have in common. And then you start writing code to check those.
Why you simply don't use regex like this its more powerful :
public static void main(String[] args) {
System.out.println("123-456-7890 is valid? " + valider("123-456-7890"));
System.out.println("(123)456-7890 is valid? " + valider("(123)456-7890"));
}
private static boolean valider(String phoneNumber) {
if (phoneNumber.matches("\\d{3}[-\\.\\s]\\d{3}[-\\.\\s]\\d{4}")) {
return true;
} else return phoneNumber.matches("\\(\\d{3}\\)\\d{3}-\\d{4}");
}

How do I set the statement if to read letters instead of numbers?

"if" statement only allows to put numbers in it.
Is there a way to make it read letters?
I'm only in my fifth lesson of Java (I study in a uni and the teacher is very slow but I want to learn things fast)
for example.
import java.util.Scanner;
public class Java {
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
int answer1;
System.out.println("Do you like Java?");
answer1 = scan.nextInt();
if (answer1 == yes)
System.out.println("Cool ~");
else
System.out.println("Ehh...");
}
}
I want to put "yes" instead of the number 5.
So if the user types "yes" it will print "correct".
P.S. I didn't find a clear answer to that in the search engine.
It's not a duplicated thread as I'm trying to find a clear answer to that.
I need a detailed explanation about it.
I'm still a beginner, using those "high tech java words" won't help me.
You need to modify your program so that your scanner to reads a String instead of an int. You can do that as:
import java.util.Scanner;
public class Java {
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
String answer1;
System.out.println("Do you like Java?");
answer1 = scan.next();
if (answer1.equals("yes"))
System.out.println("Cool ~");
else
System.out.println("Ehh...");
}
}
I used next() for this since we only want one word (token), but be aware that there are other options for reading Strings.
Notice also that I've changed the test in the condition because it's now a String. See this answer for more on comparing Strings.
You need to modify your program so that your scanner to reads a String instead of an int. You can do that as:
import java.util.Scanner; public class Java {
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
String answer1;
System.out.println("Do you like Java?");
answer1 = scan.next();
if (answer1.equals("yes"))
System.out.println("Cool ~");
else
System.out.println("Ehh...");
} }
I used next() for this since we only want one word (token), but be aware that there are other options for reading Strings.
Notice also that I've changed the test in the condition because it's
now a String. See this answer for more on comparing Strings.
Ok, what if you want the program to read both words and numbers:
Here's my program (more in depth, when you see the full thing), but this is one of 5 parts (that look a like) where I'm having the program...
public static void Gdr1() {
try {
System.out.print("[Code: Gdr1] Grade 1: %");
Scanner gdr1 = new Scanner(System.in);
Z = gdr1.next();
Z = Double.toString(Grd1);
Grd1 = Double.parseDouble(Z);
if ((Grd1<100)&&(Grd1>=5)) {
Gdr2();
} else if ((Grd1>=100)&&(Grd1<125)) {
System.out.println(" System> Great Job "+Stu+"!");
Gdr2();
} else if (Grd1<5) {
System.out.println("I'm sorry, the lowest grade I am allowed to compute is 5...");
Gdr1();
} else if (Z.equalsIgnoreCase("restart")) {
restart01();
} else {
System.out.println("("+Z+") cannot be resolved in my system...");
Gdr1();
}
} catch (Exception e) {}
}
Now everything works in the program, besides for when the End-User's input = "restart", I know some of the code in the program seems complicated, but it does work (most of it), can anyone help me try to figure this out, its for my portfolio at my school due latest by 1/25/2017 # 11:59 pm.
The things like Z (constant String), ""+Stu+"" (variable input), and [Code: Gdr1] are there for a purpose...

Problem in looping when using method in Java

I'm doing a simple program regarding methods.
But I have one problem. Everything is already working except when looping.
When I choose to loop again. The program skips on inputting the name. And proceeds directly to the year and section.
Here's the code:
public static void main(String[] args) {
do{
System.out.println("Input info:");
name=stringGetter("Name: ");
yearandsec=stringGetter("Year and section: ");
sex_code=charGetter("Sex code: " + "\n" + "[M]" + "\n" + "[F]:");
scode=intGetter("Scholarship code: ");
ccode=intGetter("Course code: ");
units=intGetter("Units: ");
fee_per_unit=doubleGetter("Fee per unit: ");
misc=doubleGetter("Miscellaneous: ");
display();
switches(scode, units, fee_per_unit, misc);
System.out.println("Another?");
dec=rew.nextInt();
}while(dec==1);
}
Here's the method getting the value for name together with the year and section:
public static String stringGetter(String ny){
String sget;
System.out.println(ny);
sget=rew.nextLine();
return sget;
}
I'm really annoyed with this problem, and I don't have any idea on how to fix this. Please help. thanks
Here is a simpler and more complete program that reproduces the error:
public static Scanner rew = new Scanner(System.in);
public static void main(String[] args) {
int dec;
do {
System.out.println("Input info:");
String name=stringGetter("Name: ");
String yearandsec=stringGetter("Year and section: ");
dec=rew.nextInt();
} while(dec==1);
}
public static String stringGetter(String ny){
System.out.println(ny);
return rew.nextLine();
}
The problem is that after calling nextInt() the call to nextLine() reads up to the new line after the int (giving a blank line), not up to the next new line.
If you change dec to a String and change dec=rew.nextInt(); to dec=rew.nextLine(); then it will work fine. Here is a complete example that you can copy and paste into a blank file to see that it works correctly:
import java.util.*;
public class Program
{
public static Scanner rew = new Scanner(System.in);
public static void main(String[] args) {
String dec;
do {
System.out.println("Input info:");
String name = stringGetter("Name: ");
String yearandsec = stringGetter("Year and section: ");
dec = stringGetter("Enter 1 to continue: ");
} while(dec.equals("1"));
}
public static String stringGetter(String ny){
System.out.println(ny);
return rew.nextLine();
}
}
You may also want to consider adding proper parsing and validation to your program. Currently your program will behave in an undesirable way if the user enters invalid data.
The line:
dec = rew.nextInt();
Is reading an int value from the input stream and is not processing the newline character, then when you come back to point where you get the name at which point a new line is still in the Reader's buffer and gets consumed by the stringGetter returning an empty value for name.
Change the line to do something like:
do {
//....
s = stringGetter("Another (y/n)? ");
} while ("y".equals(s));
Well you haven't told us what "rew" is, nor what rew.nextInt() does. Is it possible that rew.nextInt() is waiting for the user to hit return, but only actually consuming one character of the input - so that the next call to rew.nextLine() (for the name) just immediately takes the rest of that line? I suspect that's what's happening because you're using System.in - usually reading from System.in only gives any input when you hit return.
(It's possible that this is also only a problem on Windows - I wonder whether it consumes the "\r" from System.in as the delimiter, leaving "\n" still in the buffer. Not sure.)
To test this, try typing in "1 Jon" when you're being asked whether or not to continue - I think it will then use "Jon" as the next name.
Essentially, I think using Scanner.nextInt() is going to have issues when the next call is to Scanner.nextString(). You might be better off using a BufferedReader and calling readLine() repeatedly, then parsing the data yourself.

Categories

Resources