I have a problem that requires at least 2 uppercase letters, at least 3 lowercase letters and 1 digits.
Here is the exact problem:
Write an application that prompts the user for a password that contains at least two uppercase letters, at least three lowercase letters, and at least one digit. Continuously prompt the user until a valid password is entered. Display Valid password if the password is valid; if not, display the appropriate reason(s) the password is not valid as follows:
For example, if the user enters "Password" your program should output: Your password was invalid for the following reasons: uppercase letters digits
If a user enters "passWOrd12", your program should output: valid password
Here is my coding so far, I am having the problem of the program promting the user to enter in more passwords once they enter and incorrect one.
import java.util.*;
public class ValidatePassword {
public static void main(String[] args) {
String inputPassword;
Scanner input = new Scanner(System.in);
System.out.print("Password: ");
inputPassword = input.next();
System.out.println(PassCheck(inputPassword));
System.out.println("");
}
public static String PassCheck(String Password) {
String result = "Valid Password";
int length = 0;
int numCount = 0;
int capCount = 0;
for (int x = 0; x < Password.length(); x++) {
if ((Password.charAt(x) >= 47 && Password.charAt(x) <= 58)
|| (Password.charAt(x) >= 64 && Password.charAt(x) <= 91)
|| (Password.charAt(x) >= 97 && Password.charAt(x) <= 122)) {
} else {
result = "Password Contains Invalid Character!";
}
if ((Password.charAt(x) > 47 && Password.charAt(x) < 58)) {
numCount++;
}
if ((Password.charAt(x) > 64 && Password.charAt(x) < 91)) {
capCount++;
}
length = (x + 1);
}
if (numCount < 2) {
result = "digits";
}
if (capCount < 2) {
result = "uppercase letters";
}
if (numCount < 2 && capCount < 2) {
result = "uppercase letters digits";
}
if (length < 2) {
result = "Password is Too Short!";
}
return (result);
}
}
You need a while loop. This will ensure that your code will keep looping until it succeeds. When it succeeds, the boolean becomes true and it doesn't loop. Write whatever you want to happen next after the while loop.
public static void main(String[] args) {
String inputPassword;
Scanner input = new Scanner(System.in);
boolean success=false;
while(!success){
System.out.print("Password: ");
inputPassword = input.next();
System.out.println(PassCheck(inputPassword));
if(PassCheck(inputPassword).equals("Valid Password")) success = true;
System.out.println("");
}
}
you can do it by changing the return type of PassCheck method to a boolean result and use Character class to check for Uppercase Lowercase Digit characters and count occurence of each one at the end check for conditions and if it pass then the result is true else it is false and you can iterator your do-while according to result of PassCheck method
public class ValidatePassword {
public static void main(String[] args) {
String inputPassword;
Scanner input = new Scanner(System.in);
boolean isValidPassword = false;
do {
System.out.print("Password: ");
inputPassword = input.next();
isValidPassword = PassCheck(inputPassword);
System.out.println("");
}while(!isValidPassword);
}
public static boolean PassCheck(String Password) {
boolean isValid = false;
String result = "";
int numCount = 0;
int capCount = 0;
int lowCount = 0;
for (int x = 0; x < Password.length(); x++) {
if(Character.isDigit(Password.charAt(x))) {
numCount++;
}
if(Character.isUpperCase(Password.charAt(x))) {
capCount++;
}
if(Character.isLowerCase(Password.charAt(x))) {
lowCount++;
}
}
if(numCount >= 1 && capCount >= 2 && lowCount >= 3) {
result = "Password Valid";
isValid = true;
} else {
isValid = false;
result = "Password is Invalid: ";
if(Password.length() < 2) {
result += " Password is Too Short!";
}
if(numCount < 1) {
result += " no digit";
}
if(capCount < 2) {
result += " at lease 2 Uppercase";
}
if(lowCount < 3) {
result += " at lease 3 Lowercase";
}
}
System.out.println(result);
return isValid;
}
}
Below is the finished code that worked on the Cengage platform for me:
import java.util.*;
public class ValidatePassword {
public static void main(String[] args) {
String inputPassword;
Scanner input = new Scanner(System.in);
boolean success=false;
while(!success){
System.out.print("Password: ");
inputPassword = input.next();
System.out.println(PassCheck(inputPassword));
if(PassCheck(inputPassword).equals("Valid Password")) success = true;
System.out.println("");
}
}
public static String PassCheck(String Password) {
String result = "Valid Password";
int length = 0;
int numCount = 0;
int capCount = 0;
for (int x = 0; x < Password.length(); x++) {
if ((Password.charAt(x) >= 47 && Password.charAt(x) <= 58) || (Password.charAt(x) >= 64 && Password.charAt(x) <= 91) ||
(Password.charAt(x) >= 97 && Password.charAt(x) <= 122)) {
} else {
result = "Password Contains Invalid Character!";
}
if ((Password.charAt(x) > 47 && Password.charAt(x) < 58)) {
numCount++;
}
if ((Password.charAt(x) > 64 && Password.charAt(x) < 91)) {
capCount++;
}
length = (x + 1);
}
if (numCount < 2) {
result = "digits";
}
if (capCount < 2) {
result = "uppercase letters";
}
if (capCount < 2) {
result = "uppercase letters";
}
if (numCount < 2 && capCount < 2)
{
result = "uppercase letters digits";
}
if (length < 2) {
result = "Password is Too Short!";
}
return (result);
}
}
Related
I'm new to programming & I tried to make an algorithm to find the grade of the marks entered by the user for each subject. At the beginning of the program user inputs all the marks for each subject. After that computer should automatically print all the subjects in the following order subject - mark - grade.
I used the do-while loop for avoiding when the user inputs an out of range number. Also, I thought to use try-catch and do-while to avoid getting an invalid variable type from the user. I put the whole try-catch into another do-while loop. So, it has to be loop until the user inputs an integer value when an exception exists. But when I enter a wrong variable type like A while the program is running, the computer decides that all the remaining inputs are invalid variables without the user's entry and prints the "marks" as zero and null for all those "grades" >>Subject_4 - 0 - null. Otherwise, if I input a correct variable it should print like this >>Subject_1 - 56 - C. How can I fix this? Please help me.
public class findResults {
int getMark;
int setMark;
String setGrade;
int arrayIndex;
String [] subjects = {"Subject_1","Subject_2","Subject_3","Subject_4"};
int [] marks = new int [subjects.length];
String[] grades = new String [subjects.length];
public findResults(){
Scanner scan = new Scanner (System.in);
System.out.println("Enter your marks for each subjects!");
for (int t = 0;t<subjects.length;t++){
arrayIndex = t;
int x = 0;
do{
try {
do{
System.out.print(subjects[t]+" - ");
getMark = scan.nextInt();
setMark = ((getMark <= 100 && getMark >= 0)? getMark : (x=x-1));
x = x+1;
}while(x!=1);
} catch (Exception e) {
System.out.println("Please input valid number ..!");
}
}while(x!=x);
}
for (int i = 0; i<subjects.length;i++)
System.out.println(subjects[i]+" - "+marks[i]+" - "+ grades[i]);
}
public void setResult(){
if (setMark >= 75){
setGrade = "A";
marks[arrayIndex]= setMark;
grades[arrayIndex]= setGrade;
}
else if(setMark >=65){
setGrade = "A";
marks[arrayIndex]= setMark;
grades[arrayIndex]= setGrade;
}
else if(setMark >=65){
setGrade = "B";
marks[arrayIndex]= setMark;
grades[arrayIndex]= setGrade;
}
else if(setMark >=55){
setGrade = "C";
marks[arrayIndex]= setMark;
grades[arrayIndex]= setGrade;
}
else if(setMark >=35){
setGrade = "S";
marks[arrayIndex]= setMark;
grades[arrayIndex]= setGrade;
}
else if(setMark >0){
setGrade = "W";
marks[arrayIndex]= setMark;
grades[arrayIndex]= setGrade;
}else{
setGrade = "F";
marks[arrayIndex]= setMark;
grades[arrayIndex]= "Fail";
}
}
}
Consider the following.
private static String setGrade(int setMark) {
String setGrade;
if (setMark >= 75) {
setGrade = "A";
}
else if (setMark >= 65) {
setGrade = "B";
}
else if (setMark >= 55) {
setGrade = "C";
}
else if (setMark >= 35) {
setGrade = "S";
}
else if (setMark > 0) {
setGrade = "W";
}
else {
setGrade = "F";
}
return setGrade;
}
public static void main(String[] args) {
String[] subjects = {"Subject_1", "Subject_2", "Subject_3", "Subject_4"};
int[] marks = new int[subjects.length];
String[] grades = new String[subjects.length];
Scanner scan = new Scanner(System.in);
System.out.println("Enter your marks for each subject.");
for (int t = 0; t < subjects.length; t++) {
System.out.printf("%s - ", subjects[t]);
try {
String str = scan.nextLine();
marks[t] = Integer.parseInt(str);
if (marks[t] < 0 || marks[t] > 100) {
System.out.println("Between 0 and 100, please. Re-enter.");
t--;
continue;
}
else {
grades[t] = setGrade(marks[t]);
}
}
catch (NumberFormatException xNumberFormat) {
System.out.println("Invalid value. Re-enter.");
t--;
continue;
}
}
for (int i = 0; i < subjects.length; i++) {
System.out.println(subjects[i] + " - " + marks[i] + " - " + grades[i]);
}
}
Below is the output from a sample run.
Enter your marks for each subject.
Subject_1 - -2
Between 0 and 100, please. Re-enter.
Subject_1 - a
Invalid value. Re-enter.
Subject_1 - 10
Subject_2 - 90
Subject_3 - 4.3
Invalid value. Re-enter.
Subject_3 - 43
Subject_4 - 007
Subject_1 - 10 - W
Subject_2 - 90 - A
Subject_3 - 43 - S
Subject_4 - 7 - W
I've read that I would need to put "continue" after an "if" statement, but every I tried this with my if statement and it states that "continue cannot be used outside of a loop."
Set it in the loop. EX:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true){
System.out.print("Enter a password: The password must have at least eight characters, only letters and digits, and at least two digits. ");
String s = input.nextLine();
if (thepassword(s)) {
System.out.println("Valid Password");
break;
} else {
System.out.println("Invalid Password");
}
}
}
See more : Java Break and Continute
Use an outer infinite loop with a lable, then break the loop using break loop_lable. Check until a valid input is made.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a password: The password must have at least eight characters, only letters and digits, and at least two digits. ");
loop:for(;;)
{
String s = input.nextLine();
if (thepassword(s))
{
System.out.println("Valid Password");
break loop;
}
else
{
System.out.println("Invalid Password");
continue loop;
}
}
input.close();
}
public static boolean thepassword(String password) {
boolean thepassword = true;
if (password.length() < 8) {
thepassword = false;
} else {
int totaldigits = 0;
for (int n = 0; n < password.length(); n++) {
if (thedigit(password.charAt(n)) || theletter(password.charAt(n))) {
if (thedigit(password.charAt(n))) {
totaldigits++;
}
} else {
thepassword = false;
break;
}
}
if (totaldigits < 2) {
thepassword = false;
}
}
return thepassword;
}
public static boolean theletter(char c) {
return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'));
}
public static boolean thedigit(char c) {
return (c >= '0' && c <= '9');
}
}
I am kind of confused is my program correct or I am missing something!
I could get an output out of it.
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter you String: ");
String bin = sc.nextLine();
int length = bin.length();
int j = 0;
int sum = 0;
if (length != 0) {
for (int i = length - 1; i >= 0; i--) {
if (bin.charAt(i) == "0" || bin.charAt(i) == "1") {
String s = bin.charAt(j) + "";
sum = (int) (sum + (Integer.valueOf(s)) * (Math.pow(2, i)));
j++;
} else {
System.out.println("illegal input.");
}
}
System.out.println(sum);
} else {
System.out.println("illegal input.");
}
}
Remove the quotation marks on this line:
if (bin.charAt(i) == "0" || bin.charAt(i) == "1") {
should become
if (bin.charAt(i) == 0 || bin.charAt(i) == 1) {
Below code works fine:
import java.util.Scanner;
public class test {
public static void main (String args []) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter you String: ");
String bin = sc.nextLine();
int length = bin.length();
int j = 0;
int sum = 0;
if (length != 0) {
for (int i = length - 1; i >= 0; i--) {
if (bin.charAt(i) == '0' || bin.charAt(i) == '1') {
String s = bin.charAt(j) + "";
sum = (int) (sum + (Integer.valueOf(s)) * (Math.pow(2, i)));
j++;
} else {
System.out.println("illegal input.");
}
}
System.out.println(sum);
} else {
System.out.println("illegal input.");
}
}
}
Here are the instructions for what I am supposed to be doing.
Write a program that inputs a string that represents a binary number.
The string can contain only 0s and 1s and no other characters, not
even spaces.
Validate that the entered number meets these requirements. If it does
not, display an error message. If it is a valid binary number,
determine the number of 1s that it contains. If it has exactly two 1s,
display "Accepted". Otherwise, display "Rejected".
All input and output should be from the console. Here are some sample
inputs to test:
abc 10102011 10101FF 0000 1111 (note the space in this test case)
00000000 1111 01110000001 1000001
What I have so far is written here:
import java.util.Scanner;
import java.util.Set;
class ValidateBinary1
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String binary = input.nextLine();
boolean isCorrect = true;
boolean notCorrect = false;
for(int i = 0; i <= binary.length() - 1; i++)
{
if(binary.charAt(i) == '1')
{
isCorrect = true;
}
else if(binary.charAt(i) != '0' & binary.charAt(i) != '1')
{
isCorrect = false;
System.out.println("Wrong input! Please enter a valid binary number");
}
}
if(isCorrect)
System.out.println("Accepted");
else if(notCorrect)
System.out.println("Rejected");
}
}
What can I write to have the program output the "rejected" line?
Try this ( you are using bitwise operator & instead of logical operator &&) but I dont think using && either is correct; you have to use bitwise or ||. Also you are not check for the number of ones, the number of ones in the input string must be exactly 2 according to your problem description.
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String binary = input.nextLine();
boolean isCorrect = true;
short numberOfOnes = 0;
for(int i = 0; i <= binary.length() - 1; i++)
{
if(binary.charAt(i) == '1')
{
numberOfOnes++;
}
else if(! (binary.charAt(i) == '0' || binary.charAt(i) == '1'))
{
isCorrect = false;
System.out.println("Wrong input! Please enter a valid binary number");
break;
}
}
if(isCorrect && numberOfOnes == 2)
System.out.println("Accepted");
else
System.out.println("Rejected");
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String binary = input.nextLine();
boolean isCorrect = true;
boolean isCountCorrect = true;
for (int i = 0; i < binary.length(); i++) {
if (binary.charAt(i) == '1' || binary.charAt(i) == '0') {
continue;
} else {
isCorrect = false;
break;
}
}
if (isCorrect == true) {
int count = 0;
for (int i = 0; i < binary.length(); i++) {
if (binary.charAt(i) == '1') {
count++;
}
}
if (count > 2) {
isCountCorrect = false;
}
}
if (isCorrect = true && isCountCorrect == true) {
System.out.println("Approved");
} else
System.out.println("Rejected");
}
Here we go. I took one of the answers and used it to modify my code and came up with this:
import java.util.Scanner;
import java.util.Set;
class ValidateBinary1
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String binary = input.nextLine();
boolean isCorrect = true;
short numberOfOnes = 0;
for(int i = 0; i <= binary.length() - 1; i++)
{
if(binary.charAt(i) == '1')
{
numberOfOnes++;
}
else if(binary.charAt(i) != '0' && binary.charAt(i) != '1')
{
isCorrect = false;
System.out.println("Wrong input! Please enter a valid binary number");
}
}
if(isCorrect && numberOfOnes == 2)
System.out.println("Accepted");
else
System.out.println("Rejected");
}
}
This is exactly what I needed. Thanks!
Im trying to convert a user entered string that starts with a consonant to pig latin buy moving all the consonants to the end of the word till the word starts with a vowel, and then adding "ay" to the end of the word. I have a for loop that's supposed to do this, but for some reason, it outputs nothing. What am i doing wrong here? Im stumped.
Here's the code:
import java.util.Scanner;
public class two {
public static void main(String[] args) {
System.out.println("Please enter a word");
Scanner word = new Scanner(System.in);
String pigLatin = word.nextLine();
while (!pigLatin.equalsIgnoreCase("quit")) {
if (isVowel(pigLatin.charAt(0))) {
pigLatin = (pigLatin + "way");
System.out.println(pigLatin);
}
else {
for (int i = 0; i < pigLatin.length(); i++) {
char firstChar = pigLatin.charAt(0);
pigLatin = pigLatin.substring(1);
pigLatin = pigLatin + firstChar;
if (i >= pigLatin.length())
{
pigLatin = pigLatin + "ay";
System.out.println(pigLatin);
}
}
}
System.out.println("Please enter a word");
pigLatin = word.nextLine();
}
word.close();
}
private static boolean isVowel(char ch) {
char v = Character.toLowerCase(ch);
if (v == 'a' || v == 'e' || v == 'i' || v == 'o' || v == 'u') {
return true;
}
else {
return false;
}
}
}
You need a less than or equal <= on the i otherwise i is never greater than or equal to pigLatin.length().
for (int i = 0; i <= pigLatin.length(); i++) {
char firstChar = pigLatin.charAt(0);
pigLatin = pigLatin.substring(1);
pigLatin = pigLatin + firstChar;
if (i >= pigLatin.length())
{
System.out.println(pigLatin);
}
}
your for loop condition is
i < pigLatin.length()
and you said in if
if(i >= pigLatin.length()){....}
so this condition will never be true , for that reason there is no output,
see below code ,
import java.util.Scanner;
/**
*
* #author rahmat waisi
*/
public class PigLatin {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
while (true) {
// System.out.print("Please enter a word: , Enter [ quit ] for exit : ");
String pigLatin = scanner.nextLine();
if (pigLatin.equals("quit")) {
break;
}
if (isVowel(pigLatin.charAt(0))) {
pigLatin += "ay";
System.out.println(pigLatin);
} else {
String output = "";
int separation_index = findFirstVowel(pigLatin);
if (separation_index ==-1) {
System.out.println(pigLatin+"ay");
continue;
}
output+= pigLatin.substring(separation_index);
output+= pigLatin.substring(0, separation_index) + "ay";
System.out.println(output);
}
}
}
}
private static boolean isVowel(char ch) {
char v = Character.toLowerCase(ch);
return v == 'a' || v == 'e' || v == 'i' || v == 'o' || v == 'u';
}
private static int findFirstVowel(String str) {
for (int i = 0; i < str.length(); i++) {
if (isVowel(str.charAt(i))) {
return i;
}
}
return -1;
}
}
here is some input:
pig
banana
trash
happy
duck
glove
eat
omelet
are
ffff
quit
and their output is:
igpay
ananabay
ashtray
appyhay
uckday
oveglay
eatay
omeletay
areay
ffffay