Reputation: 147
I am trying to get this program to restart if the user input doesn't match the correct format. However I am unsure of how to do this. I have attached the code below:
package weeek4;
import javax.swing.JOptionPane;
public class rollNumber {
public static void main(String[] args) {
String input = JOptionPane.showInputDialog(null,"Enter your Roll Number in this format **-***-*****");
if (input.matches("\\d{2}-\\d{3}-\\d{5}")) {
JOptionPane.showMessageDialog(null,"Thank you");
}
else {
JOptionPane.showMessageDialog(null,"Invalid Number");
}
}
}
Upvotes: 0
Views: 767
Reputation: 9472
It is quite easy . Just use a loop
(A statement that repeats a block of code until a certain condition is met) and a flag variable(in this case , k
checks for the condition in the while
loop)
package weeek4;
import javax.swing.JOptionPane;
public class rollNumber
{
public static void main(String[] args)
{
String input = JOptionPane.showInputDialog(null,"Enter your Roll Number in this format **-***-*****");
int k = 0;
while (k!=1)
{
if (input.matches("\\d{2}-\\d{3}-\\d{5}")) {
JOptionPane.showMessageDialog(null,"Thank you");
k=1;
}
else
JOptionPane.showMessageDialog(null,"Invalid Number");
}
}
}
Hope I helped :)
Upvotes: 1