I'm currently doing an assignment for my Java programming class.
The question in the book asks for the user to create a program that uses the JOptionPane boxes to ask the user for a password. The password has to be between 6 and 10 characters, and have at least one digit, and one letter. Once this requirement is met, ask the user to verify their password. If their second input doesn't match the first, ask the original question again. Once both inputs match, display a message saying "success!".
I've gotten mine to the point where it checks for the number of characters, but I can't for the life of me, figure out how to check for digits and letters also. I've tried nested for loops that search for digits and letters, but I can't figure out a way to make it bypass the length requirement when it doesn't have a number or letter. This is my current code.
import javax.swing.JOptionPane;
class Password{
public static void main(String[] args){
String input1 = "";
String input2 = "";
int inputLength;
do{
do{
input1 = JOptionPane.showInputDialog(null, "Enter your password\nIt must be 6 to 10 characters and\nhave at least one digit and one letter");
inputLength = input1.length();
}while(inputLength < 6 || inputLength > 10);
input2 = JOptionPane.showInputDialog(null, "Verify Password");
}while(!(input1.equals(input2)));
JOptionPane.showMessageDialog(null, "Success!");
}
}
You can deal with regular expression.
(?=.*\d) mean at last one digit in the word
(?=.*[a-zA-Z]) mean at least one letter
{6,10} mean between 6 and 10 characters
So the correct regex is ((?=.\d)(?=.[a-zA-Z]).{6,10})
Now look at the `.matches(String regex) method of String :)
If you can't use regex :
Get the CharArray (input1.toCharArray()) and iterate.
For each char, check if it's a number or a character
Keep 2 boolean (for exemple num and alpha) and set them to true when you see a number of a character
Then, look at you flag, and then test this
num && alpha && inputLenght > 6 && inputLenght < 10
Edit:
You can use Character.isLetter() and Character.isDigit(), i think you have enough informations now !
Figured it out! I ended up adding two while loops to check for digits and letters inside of the inner do loop. I set the while loops to make the boolean expressions false if the correct thing is found (I know, it seems backwards). But it makes it so the do loop will not run again if the correct characters are found. Thank you to everyone that posted, it really helped clear things up!
Here's the completed code:
import javax.swing.JOptionPane;
class Password{
public static void main(String[] args){
String input1 = "";
String input2 = "";
int inputLength;
boolean isDigit = true;
boolean isLetter = true;
char c = ' ';
char d = ' ';
int x = 0;
do{
do{
input1 = JOptionPane.showInputDialog(null, "Enter your password\nIt must be 6 to 10 characters and\nhave at least one digit and one letter");
inputLength = input1.length();
while(x < input1.length()){
c = input1.charAt(x);
if(Character.isDigit(c)){
isDigit = false;
break;
}
x++;
}
x = 0;
while(x < input1.length()){
d = input1.charAt(x);
if(Character.isLetter(d)){
isLetter = false;
break;
}
x++;
}
}while(inputLength < 6 || inputLength > 10 || isDigit || isLetter);
input2 = JOptionPane.showInputDialog(null, "Verify Password");
}while(!(input1.equals(input2)));
JOptionPane.showMessageDialog(null, "Success!");
}
}
Related
I am a student and kind of new to Java. For my homework I have to:
Ask the user to input a number (at least 7) using a do while loop.
Using a for loop I am required to ask the user to input that number of words.
Then I have to check if one of the words fulfills the given conditions:
The word must:
Start with an uppercase letter
End with a number
Contain the word "cse".
I am asked to create a method inside some code homework that does a specific task, the method should check all the required conditions, the name of the method should be countTest and it accepts the String as a parameter.
I will show you my code but I don't know how to create this specific method.
Output format
System.out.println("There as a total number of words " + count + " and
the ones that fulfill the condition are: " + condition);
The problem is, I dont know how to create the method or constructor or whatever it is called that calls all of the 3 methods inside it, and then connect that particular method to the main method!
I hope you guys can understand I am new to this, thank you in advance!
public class D6_6 {
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
System.out.println("Type a number that is at least 7");
int number = sc.nextInt();
int count = 0;
int condition = 0;
do{
if(number<7){
System.out.println("You should type a number that is at least 7 or higher");
number = sc.nextInt();
}
}
while(number<7);
sc.nextLine();
String str;
for(int i =0; i<number; i++){
System.out.println("Type a word");
str = sc.nextLine();
count++;
}
}
public boolean countTest(String str) {
}```
To check if the word start with an uppercase:
You can do that by first selecting the character you want to check by str.charAt(0). This will return a char that is the first letter of the input str.
To check if this char is an uppercase letter, you can easily use char.isUppercase(). This will return a boolean. You have to replace char by the name of the variable were you put the char of str.charAt(0) in.
To check if the last character is a number:
You can do that again by first selecting the last character by str.charAt(str.length()-1), were string.length-1 is the number of the last character.
To check if this character is a number, you can use the ascii table. Every character has it's own number. So if you want to check if your character is between 0 and 9, you can use char >= 48 || char <= 57 (look up in the ascii table). Again, char is the name of the variable were you put the char of str.charAt(str.length()-1) in.
To check if the word contains "cse":
There is a very easy method for that: str.contains("cse") will return a boolean that is true when "cse" is in the word and false when the word does not contain "cse".
I hope it is clear for you now!
I think I did it, thank you guys very much, I appreciate it!
public class D6_6 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Type a number that is at least 7");
int number = sc.nextInt();
int count = 0;
int condition = 0;
do {
if (number < 7) {
System.out.println("You should type a number that is at least 7 or higher");
number = sc.nextInt();
}
}
while (number < 7);
sc.nextLine();
String str;
for (int i = 0; i < number; i++) {
System.out.println("Type a word");
str = sc.nextLine();
count++;
if((countTest(str))){
condition++;
}
}
if(count == 0){
System.out.println("No words typed");
} else {
System.out.println("Total number of words typed: " + count + ", which fulfill the condition: "+ condition);
}
}
public static boolean countTest(String str) {
return Character.isUpperCase(str.charAt(0)) && str.charAt(str.length() - 1) >= 48 || str.charAt(str.length() - 1) <= 57 || str.contains("cse");
}
}```
Piglatin translator. at the end I am trying to get the location of the first vowel. Index is set to be the location of every vowel, but with pig latin you only need the location of the first vowel. When I run the program I don't always get the location of the first vowel. it seems to give me the second number and not the first.
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Assignment_4_Piglatin {
public static void main(String[] args) {
Scanner userWord = new Scanner(System.in);
System.out.println("K. Caleb Swallow");
System.out.println("Welcome to the Pig Latin Translator!");
boolean run = true;
while (run) {
System.out.println("Please enter a word(or press Q to quit):");
String firstLetter = "something";
String firstVowel = "test";
String word = userWord.next();
String vowels = "aeiou";
if (word.equals("Q")) {
System.exit(0);
}
firstLetter = Character.toString(word.charAt(0));
if (firstLetter.equals("a") || firstLetter.equals("e") || firstLetter.equals("i") || firstLetter.equals("o") || firstLetter.equals("u")) {
System.out.println(word + "way");
} else {
for (int index = 0; index < word.length(); index++) {
if (vowels.contains(String.valueOf(word.charAt(index)))) {
System.out.print(index);
String firstNumber = Integer.toString(index);
firstVowel = Character.toString(firstNumber.charAt(0));
}
}
}
System.out.println(firstVowel);
The example seems to have some redundant code in if..else condition. If you want to print the first vowels then you can do it with a simple for loop, e.g.:
String word = userWord.next().toLowerCase();
String vowels = "aeiou";
for(int i=0 ; i<word.length() ; i++){
if(vowels.contains(String.valueOf(word.charAt(i)))){
System.out.println(word.charAt(i));
break;
}
}
Please note that you need to do toLowerCase on the actual word in order for contains to work.
There are a few problems I can see off the bat, but the one that is likely causing this error is in these lines:
String firstNumber = Integer.toString(index);
firstVowel = Character.toString(firstNumber.charAt(0));
Think about what this is doing. First, you are making a String out of the index value, then you are saying that the first vowel is at the 0th index of that string.
Think of this example: hello
The program will run and assign "4" to firstNumber and firstVowel which isn't what you want.
However, if you only have one vowel, your program will "work".
What happens if you have over ten vowels? I know this isn't a realistic example, but say it happens. Your program will assign the index of the last vowel to firstNumber (say it's 15), then it will assign the first character of that to firstVowel (1). This doesn't make much sense at all, does it, especially if you don't have a vowel in index 1.
The main problem you are encountering for words less than 10 letters in length is that you are not just outputting the second number, you are outputting the last one. One way I like to deal with this is to go through the code and put in print statements where I'm not sure what a certain value is. For example, I'd put another print statement in your loop which tells you what letter you're looking at, like so:
System.out.println("LETTER: "+ String.valueOf(word.charAt(index)));
This will help you avoid confusion. The proper way to do this problem would be to use a break statement, such as in Darshan's answer. Alternatively, you could use the properties of the for loop:
firstVowel = "";
for (int index = 0; index < word.length() && firstVowel == ""; index++) {
CODE
}
Note that the second part of the for loop is a conditional statement. You already know that this can be used to cycle through the word's characters, but you can insert any logical statement there that you want. For this example, I set the default value of firstVowel to "" (setting it to null is a faux-pas, but that's another story). Then, each time the loop runs, it checks to see if the value of firstVowel has been changed, which will of course happen on the first time a vowel is run through the loop.
So in short, you need to modify the two lines at the beginning of my post and you need to find a way to break your loop when you find the first vowel. One solution has been given here, and another in Darshan Mehta's post.
public static void main(String[] args) {
Scanner userWord = new Scanner(System.in);
System.out.println("K. Caleb Swallow");
System.out.println("Welcome to the Pig Latin Translator!");
boolean run = true;
while (run) {
System.out.println("Please enter a word(or press Q to quit):");
String firstLetter = "something";
String firstVowel = "test";
String word = userWord.next();
ArrayList<Character> vowels = new ArrayList<>();
vowels.add('a');
vowels.add('e');
vowels.add('i');
vowels.add('o');
vowels.add('u');
if (word.equals("Q")) {
System.exit(0);
}
firstLetter = Character.toString(word.charAt(0));
if (firstLetter.equals("a") || firstLetter.equals("e") || firstLetter.equals("i") || firstLetter.equals("o") || firstLetter.equals("u")) {
System.out.println(word + "way");
} else {
for (int index = 0; index < word.length(); index++) {
char indchar = word.charAt(index);
if (vowels.contains(word.charAt(index))) {
System.out.println(index);
firstVowel = Character.toString(word.charAt(index));
System.out.println(firstVowel);
index = word.length();
}
}
}
}
}
This is how I would do it. I changed the vowels String to an ArrayList so you can easily check if the char in the String word with the index is a vowel and the code works absolutely fine. It returns you the index where the first vowel is and what vowel it is.
I'm trying to create program that will ask the user to enter serial numbers in a specific format and the program will verify if the codes are valid or not.
The format should be 2 numbers, followed by a dash, 4 numbers, a dot, then 4 numbers and 2 letters (note: letters accepted are only a,b,c).
Example of valid format:
31-0001.2341ac
00-9999.0001cb
If the length of the string is longer/shorter than the format (14 characters total length) it should display invalid. Same thing, if other characters were used it will also say invalid.
This is the code that I have done so far. Im not sure how I can achieve the exact specified format. Hopefully someone can help..
import java.util.Scanner;
public class SerialCheck{
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("How many serial numbers would you like to check: ");
int length = sc.nextInt();
int valid = 0;
String[] sSerials = new String[length];
for (int nCtr = 0; nCtr < length; nCtr++){
System.out.print ("Enter Serial " + (nCtr+1) + ": ");
sSerials[nCtr] = sc.next();
}
System.out.println();
System.out.println("The following were added: ");
for(int nCtr = 0; nCtr < length; nCtr++){
System.out.println(sSerials[nCtr]);
}
System.out.println();
for(int nCtr = 0; nCtr < length; nCtr++){
for (int x = 0; x < sSerials[nCtr].length(); x++){
char c = sSerials[nCtr].charAt(x);
if((sSerials[nCtr].charAt(x)!='a') ||
(sSerials[nCtr].charAt(x)!='b') ||
(sSerials[nCtr].charAt(x)!='c') ||
(sSerials[nCtr].charAt(x)!='-') ||
(sSerials[nCtr].charAt(x)!='.')){
valid--;
}
else{
valid++;
}
}
if (valid < 0 && sSerials[nCtr].length() != 14){
System.out.println("The address is invalid.");
}
else{
System.out.println("The address is valid.");
}
}
}
}
I frequently post answers saying "don't use regular expressions". But in this case: use regular expressions. They are the right tool for this job.
boolean isValid = sSerials[nCtr].matches(
"[0-9]{2}" // Match 2 digits
+ "-" // Then a dash
+ "[0-9]{4}" // Then 4 digits
+ "\\." // Then a dot (which must be escaped)
+ "[0-9]{4}" // Then 4 digits
+ "[abc]{2}" // Then 2 a, b or c.
This regex is split up simply to explain the parts of it. You can write the string literal on one line:
boolean isValid =
sSerials[nCtr].matches("[0-9]{2}-[0-9]{4}\\.[0-9]{4}[abc]{2}");
You can use some websites or utility like regexr.com which helps building you regular expression for required string(Seqial number for your product).
Then use java.util.regex package for identifying them,
The linkjava.util.regex given will expose you all the functions using which you can filter perticular type of string.
import java.util.Scanner;
import java.util.Stack;
public class Stack_1 {
public static void main(String[] args) {
String val;
Scanner input = new Scanner(System.in);
System.out.println("Enter Text: ");
val = input.nextLine();
push(val);
}
public static void push(String str) {
Stack<Character> stk = new Stack<Character>();
for (int i = 0; i < str.length(); i++) {
stk.push(str.charAt(i));
}
System.out.println(stk);
String reverseString = "";
String original = "";
int length = original.length();
for (int i = length - 1; i >= 0; i--)
reverseString = reverseString + original.toUpperCase().charAt(i);
if (original.toUpperCase().equals(stk))
System.out.println("The string is a palindrome.");
else if (reverseString.toUpperCase().equals(stk))
System.out.println("The string is not a palindrome.");
}
}
Can anyone help me out. I didn't know where I went wrong. The question was to create a stack (Character), and display the text where it is a palindrome or not. The user had to enter input.
P.S This was one of my lab test.
If I followed the code correctly, the problem appears to be that the OP is comparing a String object (either original or reverseString) to Stack<Character> object.
So, the probable failure is the incorrect attempted comparison of a String object to a Stack object.
I think there is a 2nd failure in the if/else if logic given that an example input of "cool" is not a palindrome, but no output is produced in such a case.
EDIT: while the OP code does attempt to adjust for the case of the entered data (not given in the question as to whether that is a requirement or not), it does not account for spaces or other punctuation. According to the entry on Wikipedia about Palindromes, punctuation is also usually ignored. Again, whether being concerned about spaces, periods, dashes, etc. was part of the exercise is not defined in the question. The question is a bit under specified in terms of full requirements.
I would think a solution using a stack would take a String, push it by character to a Stack (probably correcting for case and stripping out all punctuation at that time), and then do a comparison by popping from the Stack. I think the OP code is missing part of the requirement in using a Stack.
Example code to have only characters on the Stack. There are other approaches, of course:
// push by character onto the stack; use only
// characters, and convert to lower case
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if ( (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ) {
stk.push(Character.toLowerCase(c));
}
}
Example to remove all non characters from a check String:
// convert out comparison String to lower case and remove
// all non letters
String chk = str.toLowerCase().replaceAll("[^a-z]", "");
Example loop to use the Stack to check against the String:
// assume we have a palindrome
boolean palindrome = true;
// counter across the String
int i = 0;
// loop while there is more on the stack and we haven't
// failed our test
while (! stk.isEmpty() && palindrome) {
Character c = stk.pop();
palindrome = (c == chk.charAt(i++));
}
Sample Test Data:
cool is a palindrome: false
mom is a palindrome: true
Never odd or even is a palindrome: true
A man, a plan, a canal - Panama! is a palindrome: true
I have been asked to write an application that prompts the user for a String that contains at least five letters and at least five digits. Continuously reprompt the user until a valid String is entered. Display a message indicating whether the user was successful or did not enter enough digits, letters, or both.
I am a beginner programmer and I need help figuring out how too make this application work correctly. My issue is I am unable to figure out how to make my program interpret the letters and numbers from user input. Here is what I have so far:
public static void main(String[] args) {
// Declare variables.
String message;
int numLetters = 0;
int numDigits = 0;
boolean letters = false;
boolean digits = false;
// Input.
Scanner input = new Scanner(System.in);
System.out.println("Type a message with 5 letters and 5 digits: ");
message = input.nextLine();
// Loop through string.
The dark art of regular expressions can crush this problem with just one method call:
public static boolean check(String input) {
return input.matches("(?i)(?=(.*?[a-z]){5})(?=(.*?\\d){5}).*");
}
Breakdown:
the matches() method accepts a regex that must match the whole string to return true
the basic matching regex is .*, which matches everything
(?i) means "ignore case"
[a-z] is a character class as means "any lowercase letter"
.*?[a-z] means "0-n chars (but the smallest number possible) then a letter"
(.*?[a-z]){5} means "5 copies of the above"
(?=(.*?[a-z]){5}) is a "look ahead", which asserts, but does not consume the input (so you can fire another one) and means "there must be at least 5 letters in the input"
(?=(.*?\\d){5}) is similar, but asserts there are at least 5 numbers
Create a method to check if it has 5 letters and 5 digits:
public boolean check(String input){
int numDigits = 0;
int numLetters = 0;
for(int i=0; i<input.length();i++){
if(Character.isLetter(input.charAt(i))) numLetters++;
if(Character.isDigit(input.charAt(i))) numDigits++;
}
return (numDigits >= 5) && (numLetters >= 5);
}
Then you can add this method to a while loop:
while(!check(message)){
// get the input again and assign it to message
}
HA!!!! I GOT IT... For all you kids out there that need an answer to REFERENCE, check this out! Since everyone likes to dance around giving a good answer here is copy and paste code that will work. (Please dont hand it in as your own, but check out how this PITA code works!
//Date: 5/31/2015
//Subject: Mod 4, pg 389, Question 3
//Purpose:User is to input 5 digits and 5 letters. It will re prompt user until at least 5 digits and 5 letters are typed in.
import java.util.Scanner;
public class FiveLettersAndFiveDigits
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int numDigits = 0;
int numLetters = 0;
String message;
System.out.println("Please enter a 5 letter word and 5 digits.");
message = keyboard.nextLine();
while(numLetters < 5 &&numDigits <5)
{
for(int i=0; i < message.length();i++)
if(Character.isLetter(message.charAt(i))) ++numDigits;
for(int j=0; j < message.length();j++)
if(Character.isDigit(message.charAt(j))) ++numLetters;
if(numLetters >= 5 && numDigits >= 5)
{
System.out.println("You have " +numDigits+ " numbers and " +numLetters+ " letters, great job.");
}
else
{
System.out.println("You have typed in "+numDigits+" letters and "+numLetters+" numbers. Please try again.");
System.out.println("Please enter a 5 letter word and 5 digits.");
message = keyboard.nextLine();
continue;
}
}
System.out.println("This problem was no fun, hahaha. Took me like 3 hours!");
}
}
And that is that folks! Thank your lucky stars you had a reference online that was straight forward! hahaha Nothing sucks more than looking for some kind of direction and all you get is half #$$3D hints. Feel free to check out how this works.