Simple JAVA: Password Verifier problem - java

I have a simple problem that says:
A password for xyz corporation is supposed to be 6 characters long and made up of a combination of letters and digits. Write a program fragment to read in a string and print out a message as to whether or not the string entered would be considered a valid password.
I need help on completing this code. I have this pseudocode that I can't workout into Java code:
print "enter new password"
input newPassword
digitCounter =0
letterCounter = 0
for I = 0 to newPassword.length() by 1
c = newPassword.charAt(i)
if c is a digit
increment digitCounter
else if c is a letter
increment letterCounter
endif
endFor
if newPassword.length() >= 6 and digitCounter > 0 and letterCounter > 0
print "the password is valid"
else
print " password rejected, must be at least 6 characters long and be a mix of letters and digits "
endif
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
So far all I have is this for the Java code:
import java.util.Scanner;
public class Password
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String thePassword;
int len, i, letterCounter = 0, digitCounter = 0;
char c;
Len = thePassword.length();
System.out.print("Enter the password: ");
thePassword = in.nextLine();
for (i = 0,i = len, )
{
c = in.charAt(1);
if ()
}
}
}

Take a look at Character.isDigit() and Character.isLetter() for checking the characters:
If you want to use String.charAt() to get the characters of your string, you could do a for loop like so:
for (int i = 0;i < s.length();i++) {
char c = s.charAt(i);
//Check things about c
}
Although Java 1.5 instroduced a For-Each loop which will loop automatically over arrays like so:
for (char c : s.toCharArray()) {
//Check things about c
}

impot javax.swing.JOptionPane;
class PasswordDemo{
public static void main(String[] agrs){
String pass = "abcdef";
String right = "Success!";
String wrong = "Failed to login";
String input = JOptionPane.showInputDialog("Enter the password to login: ");
do{
JOptionPane.showMessageDialog(null,wrong);
input = JOptionPane.showInputDialog("Enter the password to login: ");
}while(!input.equals(pass));
//when login successfully
JOptionPane.showMessageDialog(null,right);
}
}

I'd check that the Regex \d (any digit), and the Regex [a-z] (any letter) both matches the string. And then check for length.

A couple quick tips:
your pseudo code algorithm is not correct. It will correctly validate that strings must indeed be at least 6 characters in length, but won't invalidate passwords with weird characters in them (e.g. ~%). Based on the problem statement, it seems implicit that the sentence "made up of a combination of letters and digits" means made up only of those. For this part, as others have mentionned, you can use built-in methods of the String or Character classes such as String.charAt(), Character.isDigit() and Character.isLetter().
make it a habit to declare stuff at the latest possible time (i.e just before it's used). In your example, you have String thePassword, then 2 other lines, then you assign something to thePassword. Instead, write it directly as String thePassword = in.nextLine(). This will help make the code less cluttered and easier to read. Same for your other declarations (char c, int len, etc.).
try to use the enhanced for loop if you can, in order to avoid having to figure out the length and determine where to stop (potential for errors). In your example, your loop could be something like for (char c : thePassword.toCharArray()). If you haven't talked about this loop in your class yet, you don't have to use, and you should know how the simple for loop works as well, but this is just a suggestion. In your code example, your loop does not make sense, so I'd advise you to read up on loops.

I'm going to pretend that you just read in from the command line arguments, if you need it to be able to accept multiple passwords you can generalize it. Here is how I would easily do it:
public class Password {
public static void main(String[] args) {
String thePassword = args[0];
int passLength = thePassword.length();
boolean hasLetters = false;
boolean hasDigits = false;
boolean hasSomethingElse = false;
for (int i=0; i < passLength; i++) {
char c = thePassword.charAt(i);
if(Character.isLetter(c)) hasLetters = true;
else if(Character.isDigit(c)) hasDigits = true;
else hasSomethingElse = true;
}
if (hasLetters && hasDigits && !hasSomethingElse && (passLength >= 6)) {
System.out.println("Password is correctly formatted");
} else {
System.out.println("Password is not correctly formatted");
}
}
}

Related

How can I modify my code to only accept a certain data type?

What can I do to modify this, is there any java function for that?
What needs to be done so that it only accepts characters and returns an error message for other data types?
import java.util.*;
public class problem5
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a letter from the alphabet: ");
char letter = in.next(".").charAt(0);
char vowels[] = {'A','E','I','O','U','a','e','i','o','u'};
int vowelcount = 0;
for (int i = 0; i < 10; i++)
{
if (vowels[i] == letter)
{
vowelcount++;
}
}
if (vowelcount > 0)
{
System.out.println("You entered a vowel.");
}
else
{
System.out.println("You entered a consonant.");
}
}
}
I need to reject input that has more than 1 char – Nico Dela Cruz
You just need to check the length of your input
String input = in.next(".");
if(input.length == 1){
char letter = input.charAt(0);
...
}
Add an else if you want to add an error message of some sort.
To check the input to only accept letter, you have Character.isLetter(char) to check every "letter" in UNICODE for you.
If you want to only accept a range of a-z and/or A-Z, you can do it yourself with an if condition or using regex.
Wrap your loop in a statement such as:
if (Character.isLetter(letter)){
and put and else clause at the end for your error
Edit:
OP has changed their question slightly, so you can either:
-Accept only the first character entered:
char letter = in.next().trim().charAt(0);
-Or as AxelH said above, only proceed if user enters one char:
if(input.length == 1){
char letter = input.charAt(0);

Show Characters shared between two strings

For a Java exercise I'm writing a program where the user enters two strings. The program then checks to see if the two strings share any similar characters and outputs them to the screen.
For example is Terrarium and Terraform are the two strings it should print t e r r a r. However when I run my program it always simply outputs all the characters in the first string. (In this case T e r r a f o r m.)
I suspect I'm creating a logical error based on a limited understanding of loops. But when I search for answers people seem to always use a similar method to my own.
Here is the code for your viewing:
import java.util.Scanner;
public class CountMatches
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println(" Please enter a String >> ");
String stringA = keyboard.nextLine();
System.out.println(" Please enter another String >> ");
String stringB = keyboard.nextLine();
for(int counter = 0; counter < stringA.length(); counter++ )
{
char compareA = stringA.charAt(counter);
char compareB = stringB.charAt(counter);
//System.out.println(compareA);
//System.out.println(compareB);
//System.out.println("");
if(compareA != compareB)
{
System.out.println("");
}
else if(compareA == compareB);
{
System.out.println(compareA);
System.out.println("");
}
}
}
}
else if(compareA == compareB);
Get rid of the semicolon on this line and it should work. I would also get rid of the first if statement just keep the second one.
You have two problems with this code.
First,
for(int counter = 0; counter < stringA.length(); counter++ )
If the two string are of different length, you could get an exception by going off the end of the other string. So, do this:
int len = stringA.length();
if (len > stringB.lengh()) len = stringB.length();
Next, the reason you code fails is because you have a ; at the end of your else. Your code should be:
if(compareA != compareB)
{
System.out.println("");
}
else // Don't need the == here
{
System.out.println(compareA);
System.out.println("");
}
Good luck with this.

Changing single chars to upper or lower case depending on user input in Java

I have tried to find guidance on this, but I keep getting solutions on an entire string, or a single character. I am in my 4th week of Java, and have hit a roadblock.
I have to ask a user to input three letters ("Enter three letters: abc"). Depending on which case they type, I have to write a program that swaps upper with lower and visa versa. For example, if the user types "aBc", my output will be "AbC".
This is what I have so far. If my code is horrible, I'm sorry. I'm learning as I go.
import java.util.Scanner;
public class LowerUpper {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter three letters: ");
String letters = input.nextLine();
for (int i = 0; i < letters.length(); i++) {
char letter1 = letters.charAt(0);
char letter2 = letters.charAt(1);
char letter3 = letters.charAt(2);
if (Character.isUpperCase(letters.charAt(0)) == true)
System.out.println(Character.toLowerCase(letter1));
else {
System.out.println(Character.toUpperCase(letter1));
}
if (Character.isUpperCase(letters.charAt(1)) == true)
System.out.println(Character.toLowerCase(letter2));
else {
System.out.println(Character.toUpperCase(letter2));
}
if (Character.isUpperCase(letters.charAt(2)) == true)
System.out.println(Character.toLowerCase(letter3));
else {
System.out.println(Character.toUpperCase(letter3));
}
}
}
}
When I typed "abc" for the input, the output was:
A
B
C
A
B
C
A
B
C
The format of the output is supposed to be "Result: ABC". I can work on that later. I'm just trying to figure out how to get this to execute correctly. My hunch is that I'm definitely going wrong on my if/else statements. I do not know how to print the changed chars all in a row (abc, AbC, ABC, etc). I thought I did it correctly at the beginning with the indexing of the string (0,1,2).
By the way, it's not showing my output correctly this forum. It is supposed to be one letter per line, not "ABCABCABC", if I made sense with that.
The reasoning for this is because it's inside of a for loop, which is essentially worthless, because you are never using the integer 'i'. If you remove the for loop, it should only execute once, thus for outputting "ABC", instead of "A B C A B C A B C". To print the chars in a row, you can simply append each character to a string, and then output that.
The biggest issue I see is that you've got a loop going over the length of the string but you're not using the loop index i to reference the individual characters. In short, you're trying too hard and overlooking the obvious.
Wouldn't this do the trick?
for (int i = 0; i < letters.length(); i++) {
char letter1 = letters.charAt(0);
if (Character.isUpperCase(letter1)) {
System.out.println(Character.toLowerCase(letter1));
} else {
System.out.println(Character.toUpperCase(letter1));
}
}
The reason why you get a redundant printing 'coz you loop the three variables which already contain all characters.
To solve your problem. just remove the for loop. 'coz you already
store each character to the three variables.
You code will look like this now:
import java.util.Scanner;
public class LowerUpper {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter three letters: ");
String letters = input.nextLine();
char letter1 = letters.charAt(0);
char letter2 = letters.charAt(1);
char letter3 = letters.charAt(2);
if (Character.isUpperCase(letters.charAt(0)) == true)
System.out.println(Character.toLowerCase(letter1));
else {
System.out.println(Character.toUpperCase(letter1));
}
if (Character.isUpperCase(letters.charAt(1)) == true)
System.out.println(Character.toLowerCase(letter2));
else {
System.out.println(Character.toUpperCase(letter2));
}
if (Character.isUpperCase(letters.charAt(2)) == true)
System.out.println(Character.toLowerCase(letter3));
else {
System.out.println(Character.toUpperCase(letter3));
}
}
}
Ok, here is my new code. It compiled with no errors and the output was just as it was supposed to be:
import java.util.Scanner;
public class LowerUpper {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter three letters: ");
String letters = input.nextLine();
char letter1 = letters.charAt(0);
char letter2 = letters.charAt(1);
char letter3 = letters.charAt(2);
if (Character.isUpperCase(letters.charAt(0)) == true)
System.out.print("Result: " + Character.toLowerCase(letter1));
else {
System.out.print("Result: " + Character.toUpperCase(letter1));
}
if (Character.isUpperCase(letters.charAt(1)) == true)
System.out.print(Character.toLowerCase(letter2));
else {
System.out.print(Character.toUpperCase(letter2));
}
if (Character.isUpperCase(letters.charAt(2)) == true)
System.out.print(Character.toLowerCase(letter3));
else {
System.out.print(Character.toUpperCase(letter3));
}
}
}
The problem is that you have a loop then do each letter individually. So get rid of the loop. It would look better if you re-wrote it with a loop but only had one if/else statement inside the loop based on i not 0,1&2.
Replace your for loop with:
System.out.println(letters.toUpperCase());

Trying to write a simple compiler in java (I am using notepad++)

My question is how would I write a simple compiler ,that is like the compilers used in fax machines, that would convert something like aaaavvvvvddddddddddd to 4a5vBd.
Also, I get to "Assume" that any string entered will not contain uppercase letters and no numbers, and that any string will contain less than 61 of any type of character so, I get to assume no one will put in 64 continues a's in my program.
This is as far as I gotten
import java.util.*;
public class Program4
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int n;
char cn;
String word;
String numChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
System.out.println("Hello, please enter a string");
word = scan.nextln();
if(n <= 61)
{
int n = ?;
cn = numChars.charAt(n);
}
}
}
I assume I need to use a loop, but I don't know what I should use to count the repeating letters and then tell how many letters of that type are in a row. Now I am only asking for advice and not so much for code, because I want to do it but, as a beginner my Java "Vocabulary" isn't very big right now.
Any advice/ tips would be greatly appreciated.
Sincerely,
Mr.Trips
Well I am back and it appears my code here likes to only print out 147. No matter what I type in I will always get 147. I have tried to hand trace all my variables, but when I do it I get exactly what I want, and I must have some error in my logic. Any thoughts?
import java.util.*;
public class Program4
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int n = 0;
int s = 0;
char a;
char b;
char c;
String word;
String numChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
System.out.println("Please enter a string");
word = scan.nextLine();
while (n < word.length())
{
a = word.charAt(n);
b = a;
n = n ++;
a = word.charAt(n);
if (a == b)
{
s = (s + 1) ;
}
else if (a != b);
{
c = numChars.charAt(s);
System.out.print(b + c);
s = 0;
c = 0;
break;
}
}
}
}
Thank you again!
Since you don't want code this is logically how to do it. You are right you should loop through the string for each char. Store the last char in a variable and keep a counter variable. Compare current char to last char if it is equal then increment the counter. As soon as it is not equal to the last char then add counter + last char to result string and reset counter variable. Each iteration update last char variable.

Using methods to check for palindromes

I have to use methods to test a sentence for palindromes and I have got most of it done but it will only do the first word in the string and won't move on to the next one. I believe its something got to do with the spaces, if anyone could help that'd be great. Also I haven't studied arrays so I'd appreciate if arrays were not used.
class palindromeTesting
{
public static void main(String[] args)
{
String userInput;
String goodWords;
String palindromes;
System.out.println("Please enter a sentance to be tested for palindrome: ");
userInput = EasyIn.getString();
userInput += " " ;
goodWords = charsCheck(userInput); //Calling a method to check if any word contains more than letters.
palindromes = palinCheck(goodWords); //Checking the good words to see if they're palindromes.
System.out.println("The valid palindromes are " + palindromes);
} //Main
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
public static String charsCheck(String userInput)
{
String validWords;
String firstWord;
Boolean goodWord;
int spacePos;
char letter;
spacePos = userInput.indexOf(" ");
validWords = "";
while(spacePos > 0)
{
firstWord = userInput.substring(0 , spacePos);
goodWord = true;
for(int index = 0 ; index < firstWord.length() && goodWord == true ; index++)
{
spacePos = userInput.indexOf(" ");
letter = Character.toUpperCase(firstWord.charAt(index));
if(letter < 'A' || letter > 'Z' )
{
goodWord = false;
}
} //for
if(goodWord == true)
{
firstWord = firstWord + " ";
validWords = validWords + firstWord;
}
userInput = userInput.substring(spacePos + 1);
spacePos = userInput.indexOf(" ");
} //While
return validWords;
} //charsCheck main
//-----------------------------------------------------------------------------------------------------------------------------------------------------------
public static String palinCheck(String goodWords)
{
String firstWord;
String validPalins = "";
String backward = "";
int spacePos;
spacePos = goodWords.indexOf(" ");
while(spacePos > 0)
{
firstWord = goodWords.substring(0 , spacePos);
for(int i = firstWord.length()-1; i >= 0; i--)
{
backward = backward + firstWord.charAt(i);
}
if(firstWord.equals(backward))
{
validPalins = validPalins + firstWord;
}
goodWords = goodWords.substring(spacePos + 1) ;
spacePos = goodWords.indexOf(" ") ;
}//While
return validPalins;
} //palinCheck main
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
} //Class
If you believe the issue are spaces, you could always remove all spaces (and any other unwanted characters) with the replaceAll() method (check out the API). Say you have word1 and word2 you'd like to compare to see if they are palindromes, then do the following:
String word1 = "du mb";
String word2 = "b,mu d";
word1 = word1.replaceAll(" ", "");//replace it with empty string
word1 = word1.replaceAll(",", "");//even if the comma doesn't exist, this method will be fine.
word2 = word2.replaceAll(" ", "");
word2 = word2.replaceAll(",", "");
Once you've gotten ridden of unnecessary characters or spaces, then you should do the check. Also, you could always use Regex expressions for this kind of task, but that may be a bit difficult to learn for a beginner.
Also, I recommend using for loops (can probably be done in one for loop, but nested loops will do) instead of while loop for this task. Check out this example.
Sidenote:
Also I haven't studied arrays so I'd appreciate if arrays were not
used.
Strings are essentially char arrays.
The problem you described is actually not what is happening; your code does indeed move on to the next word. For my test, I used the test input Hi my name is blolb.
The problem is in your palinCheck method. You are using the backward variable to reverse the word and check whether it and firstWord, are equal. However, you aren't resetting the backward variable back to a blank string in the loop. As a result, you're constantly adding to whatever was in there before from the previous loop. At the end of the method, if I examine the content of backward using my test string above, it actually looks like iHymemansiblolb.
To solve this, simply declare String backward inside the while loop, like so:
while(spacePos > 0) {
String backward = "";
// rest of loop
Quick side note:
During the run of the palinCheck method, you're changing the goodWords parameter each iteration when you do this:
goodWords = goodWords.substring(spacePos + 1) ;
While this is technically acceptable (it has no effect outside of the method), I wouldn't consider it good practice to modify the method parameter like this. I would make a new String variable at the top of the method, perhaps call it something like currentGoodWords or something like that, and then change your line to:
currentGoodWords = goodWords.substring(spacePos + 1) ;
Also, I assume this is homework, so if you are allowed to use it, I would definitely take a look at the StringBuilder#reverse() method that Elliot Frisch mentioned (I admit, I never knew about this method before now, so major +1s to Elliot).
I had this code written as a personal project quite a while ago on palindrome using the shortest amount of code. It basically strip every non-word character, put it to lower case just with 13 lines. Hope this help haha! Let's hope other guys would get lucky to find this too.
import java.util.Scanner;
public class Palindrome {
public static void main(String[]args){
if(isReverse()){System.out.println("This is a palindrome.");}
else{System.out.print("This is not a palindrome");}
}
public static boolean isReverse(){
Scanner keyboard = new Scanner(System.in);
System.out.print("Please type something: ");
String line = ((keyboard.nextLine()).toLowerCase()).replaceAll("\\W","");
return (line.equals(new StringBuffer(line).reverse().toString()));
}
}

Categories