import java.util.Scanner;
public class VerifySerialBayneHarris {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
String text;
String cha;
System.out.println("Enter a Serial number: ");
text=input.nextLine();
if(text.matches("[^-](?!.*--)[A-Za-z0-9-]+[^-]"));{
System.out.println("Serial number "+text+" verification \nValid");
System.out.println("Enter a wildchar character: ");
cha=input.nextLine();
text= text.replaceAll("[A-Za-z0-9]", cha);
}
if(text.matches("[^A-Za-z0-9-]+"));
System.out.println("Only uppercase , lowercase letters, dashes and numbers are allowed.It should have exactly 2 non-consecutive dashes in the middle. ");
}
}
This is what I have so far, but I keep getting both of the expressions running instead of one or the other. There must be something I'm missing. Thanks in advance.
Here is my guidelines:
prompts the user to enter a serial number according to the following rules:
Only uppercase and, lowercase letters, dashes and numbers are allowed.
It should have exactly 2 non-consecutive dashes in the middle.
Your program should verify that the serial number is valid and if so, prompt the user to enter a wildcard character. It should then display the concealed serial number by masking all of its characters except the dashes using the wild char character
[What code is supposed to look like]
[1]: https://i.stack.imgur.com/xoGke.jpg
Get rid of the semi-colon here...
if(text.matches("[^-](?!.*--)[A-Za-z0-9-]+[^-]"));{ << HERE
...and...
if(text.matches("[^A-Za-z0-9-]+")); << HERE
Your blocks are always executing because the if statement has an empty block due to this.
If you have minus in character class then it should be first:
[A-Za-z0-9-] shall be [-A-Za-z0-9]
But I would not include the - in the groups and write the pattern as: [A-Za-z0-9]+(-[A-Za-z0-9]+){2}
Or with POSIX: \p{Alnum}+(-\p{Alnum}+){2}
If you want to access the 3 segments: (\p{Alnum}+)-(\p{Alnum})-(\p{Alnum})
Related
Basically I want the user to enter a code in this format - XXXX000 and if the user enters 3 letters and 4 digits for example - it outputs an error.
What i did is that i wrote a command that input has to be maximum 7 characters but it doesn't specify what the characters need to be. Therefore if user enters 7 digits, it is still accepted which it should not.
System.out.print("Enter the animal's unique code - Format: (XXXX111)");
String codein = in.nextLine();
a.setCode(codein);
if (codein.length() != 7) {
System.out.println("Format was not met, please try again");
System.out.println("Enter the animal's unique code - Format: (XXXX111)");
codein = in.nextLine();
a.setCode(codein);
}
An error should appear if user does not enter in this format XXXX000
Assuming that X means A-Z and a-z and 0 means 0-9 in your pattern, you can use this pattern to valid the code:
[A-Za-z]{4}\d{3}
For more info on regexes, see here.
Use it like this:
if (codeine.matches("[A-Za-z]{4}\\d{3}")) {
// valid
} else {
// invalid
}
Imagine you are developing a software package for Amazon.com that requires users to enter their own passwords. Your software requires that users’ passwords meet the following requirements: The password should be at least 8 characters. The password should contain at least one uppercase and at least one lowercase letter. The password should contain at least one digit. The password may not contain a blank
Write a program that verifies that passwords are valid.
This is my code:
import java.io.*;
import java.util.Scanner;
public class assignment7{
public static boolean test(String password,Scanner input){
boolean valid=false;
while(input.hasNextLine()){
password=input.nextLine();
for(int i=0;i<password.length();i++){
char c=password.charAt(i);
if((password.length()>=8)&&
(Character.isUpperCase(c))&&
(Character.isLowerCase(c))&&
(Character.isDigit(c))&&
(Character.isWhitespace(c)))
valid=true;
}
}
return valid;
}
public static void main(String[]args)throws FileNotFoundException{
Scanner input=new Scanner(new File("password.txt"));
String password;
while(input.hasNextLine()){
password=input.nextLine();
System.out.println(password.trim());
boolean isvalid=test(password,input);
if(isvalid)
System.out.println("This is a valid password: "+password+"\n");
else
System.out.println("This is a invalid password: "+password+"\n");
}
System.out.println("This program prcoessed all data");
input.close();
}
}
Why does my code only read the first password and stop executing? Plus even my password is correct but it still print out invalid password?
My input file is:
asdF1k12
Mzj1kada45
jKl123oin
You have create a while loop to loop through the lines in two locations: in your main method and in your test method. The test method is consuming all input, leaving nothing more for the main loop.
You're already passing password to test correctly; just don't have a while loop within test.
You don't need to check the password length each loop; just test it once before the for loop on the characters.
A character cannot simultaneously be uppercase, lowercase, a digit, and (&&) whitespace. You'll need to test if it's uppercase, lowercase, or (||) a digit, which would make it not whitespace.
Right now you're setting valid to true if any of the characters meet the conditions. To make it so that valid is true if all of the characters meet the requirements, initialize valid to true and set it to false if the current character doesn't meet the requirement.
You may also decide not test empty lines at all depending on your exact requirements.
I am trying to get some integer inputs from user by using scanner.hasNextInt() method. It works just fine but I need to type a letter to let the program know that I'm done entering integers while I want the console to know that after I press the enter key after a single line.
For example, I type
(1
2
3
y
enter)
and the program works just fine but if I type
(1
2
3
enter
enter)
nothing happens, even if I keep pressing the enter key. This is the related part of my code, if you need to take a look at it.
public class Main {
static LinkedList linkedList =new LinkedList();
public static void main(String [] args){
System.out.println("enter integer numbers");
Scanner scanner=new Scanner(System.in);
while (scanner.hasNextInt()){
linkedList.append(scanner.nextInt());
}
print();
}
}
Three steps to understand it.
Scanner uses a delimiter to break the input into tokens, the default delimiter is \p{javaWhitespace}+. Try
Scanner scanner = new Scanner(System.in);
System.out.println(scanner.delimiter());
\p{javaWhitespace} is equivalent to java.lang.Character.isWhitespace(), so \p{javaWhitespace}+ will matches multiple characters which isWhitespace.
A line break produced by key enter is a white space. When you enter multiple enters, they will be recognized as a delimiter, not a token.
You can use s single white space, so it will take the second enter as token:
scanner.useDelimiter("\\p{javaWhitespace}");
I had a simple question. I've been exploring basic input validation in java (Only accept integers or doubles etc.. from user). The code below Works great for simple applications but it did spark my curiosity; whenever you input a letter then follow it with a space then another letter, it displays the "Try again. Input numbers only " message twice.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Input Number, BOi");
//Basic input validation. Only Accepts Integers.
while (!sc.hasNextInt()){
sc.next();//This Clears the Scanner for next input
System.out.println("Try again. Input numbers only.");
}
int userInput = sc.nextInt();
System.out.println("CONGRATS! YOU'VE ENTERED THE NUMBER: " +
userInput);
}
}
If I were to input
p p p
then the result would be
Try again. Input numbers only.
Try again. Input numbers only.
Try again. Input numbers only.
I would expect the result to just be Try again. Input numbers only. displayed once. Can anybody explain why this happens? I've heard the term "regex" thrown around but don't know if it's relevant. Thank you!
Its because next() does not consume the whole line. It only consumes the first word until space and the remaining words stays.
Thus when your loop will repeat as many words you have until it finds an int.
For example here you are giving P P P means 3 words hence thrice iteration
Thus you should use:
sc.nextLine() if you are expecting non integer and parse it
sc.nextInt(); and handle exception if someone inputs anything other
than int
Your problem is just a lack of knowledge of how Scanner really works.
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
So when you enter p p p, Scanner.nextInt() will split p p p into p then p and then p. Thats why you get 3 times the same message.
Use nextLine()Â method to get the whole line and not "skip" any whitespace.
this is my first time asking a question. If I'm breaking any rules let me know please :)
I want to verify that the user only types in only one character and store in a variable I have already declared initially. As well, loop back the question for user to type in again if they did not do what they are asked for
Here is a what I have done so far
import java.util.Scanner;
public class arraytesting {
public static void main(String[] args) {
Scanner myKeyboard = new Scanner(System.in);
int user_Choice;
int rowAndcolumns;
char[][] user_Array;
char user_Char;
do {
System.out.print("Enter your choice (1 to 9): ");
user_Choice = myKeyboard.nextInt();
if (user_Choice < 1 || user_Choice > 9)
System.out.println("Illegal choice, please try again.");
} while (user_Choice < 1 || user_Choice > 9);
switch (user_Choice) {
case 1:
do {
System.out.print("\nHow many rows and columns (min 4 & max 20)? ");
rowAndcolumns = myKeyboard.nextInt();
if (rowAndcolumns < 1 || rowAndcolumns > 9)
System.out.println("Illegal choice, please try again.");
} while (rowAndcolumns < 4 || rowAndcolumns > 20);
do {
System.out.print("Which character do you want to fill your square with? (only one character)");
user_Char = myKeyboard.next().charAt(0);
if () // error message for user if they did not type correctly, Idk what to put in the
System.out.println("Illegal choice, please try again.");// boolean for it to compare
System.out.print(user_Char);
} while (); // using do-while loop to loop back question, if they don't type in correctly, i
// would only like for user to type in only one character
break;
}
}
}
I know I can put both of them in one do-while loop, but I want to focus on getting the boolean to check for user input.
edit: I would only like the user to enter only one single character
ex. '#' or 'a'
whereas "##" or "i am typing something that is not one character" is wrong
inside the spaces of if and while are how I want it to be verified
There is no need to do any check for "only 1 character entered". That makes no sense. You can't predict the future, so you cannot know if a user will enter more characters after 1 character has been entered. You will either just take the first character entered and work with it and ignore any potential additional characters - or you have to wait for more than 1 character, essentially breaking the program for users who do the right thing (enter only one character), just to be able to give them an error message when they finally do the wrong thing (enter another character).
That being said, this code:
user_Char = myKeyboard.next().charAt(0);
will actually wait for several characters to be entered until some kind of delimiter (per default some whitespace character, e.g. newline) is entered. That's exactly what you do not want.
You want to get one character from input, and one only. You don't have to care about more characters being entered after that:
user_Char = myKeyboard.next(".").charAt(0);
This tells myKeyboard to return the next String that matches the regex ".", which is any character, and only 1 character.
If you want to validate the entered character, e.g. only alphanumeric characters allowed, you can update your if and while to something like this:
if (!Pattern.matches("[a-zA-Z0-9]", new String(user_Char)))
or even better, use the String returned by myKeyboard.next("."):
String user_String = myKeyboard.next(".");
user_Char = user_String.charAt(0);
if (!Pattern.matches("[a-zA-Z0-9]", user_String))
or you could directly tell myKeyboard to only allow valid characters and skip the entire do/if/while error handling:
user_Char = myKeyboard.next("[a-zA-Z0-9]").charAt(0);
Edit
One thing your code doesn't handle right now is invalid inputs, e.g. letters when you call nextInt. This will actually throw a java.util.InputMismatchException, and you might want to wrap your nextInt() and next(...) calls in try-catch blocks to handle these exceptions.
Please check the code below, based on the discussion with Max, I used the .length() method to check the lenght of the string that the user typed.
You can check the type of the character to avoid the runtime exception in the first if statement using some methods in Character class that you use to check if the input is digit/letter or not ?
Character.isDigit(char)
Character.isLetter(char)
Character.isLetterOrDigit(char)
I also changed some variable names, Java is following the camel case style and class name has to be capitalized. I also refactored some code to check the range of the numbers to git rid of repeating same code on and on, check the method betweenExclusive
package stackoverflow.q2;
import java.util.Scanner;
public class Question2 {
public static void main(String[] args) {
Scanner myKeyboard = new Scanner(System.in);
int userChoice;
int rowAndcolumns;
char[][] user_Array;
char userChar;
do {
System.out.print("Enter your choice (1 to 9): ");
userChoice = myKeyboard.nextInt();
if ( !betweenExclusive(userChoice, 1,9) )
System.out.println("Illegal choice, please try again.");
} while (!betweenExclusive(userChoice, 1,9));
switch (userChoice) {
case 1:
do {
System.out.print("\nHow many rows and columns (min 4 & max 20)? ");
rowAndcolumns = myKeyboard.nextInt();
if (!betweenExclusive(rowAndcolumns ,1 , 9))
System.out.println("Illegal choice, please try again.");
} while (!betweenExclusive(rowAndcolumns ,4 , 20));
String input;
while (true){
System.out.print("Which character do you want to fill your square with? (only one character)");
input = myKeyboard.next();
// error message for user if they did not type correctly, Idk what to put in the
// boolean for it to compare
if ( input.length()>1){
System.out.print("Illegal character, try again please !!! ");
}else{
userChar = input.charAt(0);
System.out.print(userChar);
break;
}
} // using do-while loop to loop back question, if they don't type in correctly, i
// would only like for user to type in only one character
break;
}
}
public static boolean betweenExclusive(int x, int min, int max)
{
return x>=min && x<=max;
}
}