I have created a password checker program. All it does is ask for a password and then outputs if the password doesn't follow the rules I have made. I would like to get help to figure out to loop this right so you can check multiple passwords without restarting.
import java.util.Scanner;
public class password {
public static void main(String[] args) {
String end = "endofinput";
Scanner word = new Scanner(System.in);
System.out.print("Password:");
String password = word.nextLine();
// password
if(password.contains("password")){
System.out.println("Password may not contain the word password");
}
// lenght
if( password.length() < 8){
System.out.println("Needs to be longer");
}
//space/special check
if((password.contains(" ")||password.contains("#")|| password.contains("#")|| password.contains("!") || password.contains("~")|| password.contains("$") || password.contains("%") || password.contains("^")|| password.contains("*") || password.contains("(")|| password.contains(")") || password.contains("-")|| password.contains("+") || password.contains("/")|| password.contains(":") || password.contains("&")|| password.contains(".")|| password.contains(", ") || password.contains("<")|| password.contains(">")|| password.contains("?")|| password.contains("|"))){
System.out.println("No spaces or special Characters");
}
// Number
if(!(password.contains("1")|| password.contains("2")||password.contains("3")||password.contains("4")||password.contains("5")||password.contains("6")||
password.contains("7")||password.contains("8")||password.contains("9")||password.contains("0"))){
System.out.println("Need a Number");
}
// upper case
if (true) {
int count = 0;
for (int i = 65; i <= 90; i++) {
// type casting
char c = (char)i;
String e = Character.toString(c);
if (password.contains(e)) {
count = 1;
}
}
if (count == 0) {
System.out.println("Needs an uppercase letter");
}
}
//lower case
if (true) {
int count = 0;
for (int i = 90; i <= 122; i++) {
// type casting
char c = (char)i;
String str1 = Character.toString(c);
if (password.contains(str1)) {
count = 1;
}
}
if (count == 0) {
System.out.println("Needs Lower case");
}
}
}
}
Just add a while with a "True" of condition, and put an if with a condition you want, to quit the loop, for example ìf(password == "Exit"). like this.
while(true)
{
System.out.print("Password:");
String password = word.nextLine();
if(password == "exit")
{
System.out.println("Ending the program");
break; //this break will stop the loop
}
// password
if(password.contains("password")){
System.out.println("Password may not contain the word password");
}
// lenght
if( password.length() < 8){
System.out.println("Needs to be longer");
}
//space/special check
if((password.contains(" ")||password.contains("#")|| password.contains("#")|| password.contains("!") || password.contains("~")|| password.contains("$") || password.contains("%") || password.contains("^")|| password.contains("*") || password.contains("(")|| password.contains(")") || password.contains("-")|| password.contains("+") || password.contains("/")|| password.contains(":") || password.contains("&")|| password.contains(".")|| password.contains(", ") || password.contains("<")|| password.contains(">")|| password.contains("?")|| password.contains("|"))){
System.out.println("No spaces or special Characters");
}
if(!(password.contains("1")|| password.contains("2")||password.contains("3")||password.contains("4")||password.contains("5")||password.contains("6")||
password.contains("7")||password.contains("8")||password.contains("9")||password.contains("0"))){
System.out.println("Need a Number");
}
// upper case
if (true) {
int count = 0;
for (int i = 65; i <= 90; i++) {
// type casting
char c = (char)i;
String e = Character.toString(c);
if (password.contains(e)) {
count = 1;
}
}
if (count == 0) {
System.out.println("Needs an uppercase letter");
}
}
//lower case
if (true) {
int count = 0;
for (int i = 90; i <= 122; i++) {
// type casting
char c = (char)i;
String str1 = Character.toString(c);
if (password.contains(str1)) {
count = 1;
}
}
if (count == 0) {
System.out.println("Needs Lower case");
}
}
}
Related
I am making a program that takes a string from a user to create a password. However, this password needs to be at least 8 characters or more, and it can only include letters(uppercase and lowercase) and digits. I already did this, however, when I enter in the user input a blank space(ex: "pass word") or a special symbol such as "%" or "&", the method still returns the value true, making the password valid when it shouldn't return this, how do I correct this?
import java.util.Scanner;
public class Password
{
public static void main(String[] args)
{
System.out.println("Enter your password");
Scanner input = new Scanner(System.in);
String pass = input.nextLine();
System.out.println("Is the password valid? " + passwordCheck(pass));
}
public static boolean passwordCheck(String password)
{
boolean pass = false;
for(int i=0; i < password.length(); i++)
{
char c = password.charAt(i);
if(password.length() >= 8)
{
if(c >= 48 && c <= 57)
{
pass = true;
}
else if(c>= 97 && c<= 122)
{
pass = true;
}
else if(c>=65 && c<=90)
{
pass = true;
}
else if(c == 32)
{
pass = false;
}
}
}
return pass;
}
}
you need to break out of the loop once it encounters a space or any other special character.
import java.util.Scanner;
public class Password
{
public static void main(String[] args)
{
System.out.println("Enter your password");
Scanner input = new Scanner(System.in);
String pass = input.nextLine();
System.out.println("Is the password valid? " + passwordCheck(pass));
}
public static boolean passwordCheck(String password)
{
boolean pass = false;
for(int i=0; i < password.length(); i++)
{
char c = password.charAt(i);
if(password.length() >= 8)
{
// also you can directly mention the character instead of looking for its respective ASCII value
if(c >= '0' && c <= '9')
{
pass = true;
}
else if(c>= 'a' && c<= 'z')
{
pass = true;
}
else if(c>='A' && c<='Z')
{
pass = true;
}
else // loop will break if it encounters a space or any other
special character
{
pass = false;
break;
}
}
}
return pass;
}
}
I used Luhn algorithm but, for some reason all of the card numbers I try it always displays that the card number is valid even if its not.
This is my code so far I believe the issue is with the toString method but I have no idea on how to fix it. Please help!
public class CreditCard
{
private String number;
private String result;
private int sum = 0;
private int n = 0;
private boolean value = true;
private StringBuilder builder = new StringBuilder();
private String word = builder.toString();
public CreditCard(String number)
{
this.number = number;
}
public String toString()
{
for(int x = 0; x < number.length(); x++)
{
char c = number.charAt(x);
if(Character.isDigit(c)){
builder.append(c);
}
}
String result = builder.toString() + " was issued by " + getIssuer();
if(isValid())
result += " and is valid.";
else
result += " and is not valid.";
return result;
}
public String getIssuer()
{
if(builder.length() == 13 && builder.substring(0, 1).equals("4") )
result = "VISA";
else if(builder.length() == 14)
{
if(builder.substring(0, 2).equals("36") || builder.substring(0, 2).equals("38")
|| builder.substring(0, 3).equals("300") || builder.substring(0, 3).equals("301")
|| builder.substring(0, 3).equals("302") || builder.substring(0, 3).equals("303")
|| builder.substring(0, 3).equals("304") || builder.substring(0, 3).equals("305"))
result = "Diner's Club";
else
result = "Unknown";
}
else if(builder.length() == 15)
{
if(builder.substring(0, 2).equals("34") || builder.substring(0, 2).equals("37"))
result = "American Express";
else
result = "Unknown";
}
else if(builder.length() == 16)
{
if(builder.substring(0, 2).equals("51") || builder.substring(0, 2).equals("52")
|| builder.substring(0, 2).equals("53") || builder.substring(0, 2).equals("54")
|| builder.substring(0, 2).equals("55"))
{
result = "MasterCard";
}
else if(builder.substring(0, 4).equals("6011"))
{
result = "Discover";
}
else if(builder.substring(0, 1).equals("4"))
{
result = "VISA";
}
else
result = "Unknown";
}
else
result = "Unknown";
return result;
}
public boolean isValid()
{
if(word.length() % 2 == 0){
for(int i = 0; i < word.length(); i++)
{
char c = word.charAt(i);
int num = Character.getNumericValue(c);
if(i % 2 == 0)
{
n = num * 2;
if(n > 9)
{
n -=9;
}
sum +=n;
}
else
sum+= num;
}
}
else
{
for(int x = 0; x < word.length(); x++)
{
char c = word.charAt(x);
int num = Character.getNumericValue(c);
if(x % 2 != 0)
{
n = num * 2;
if(n > 9)
{
n -=9;
}
sum +=n;
}
else
sum += num;
}
}
if(sum % 10 == 0)
value = true;
else
value = false;
return value;
}
}
First of all you need to revise your method, I would put an arguments into getIssuer and isValid method. These method are public and they could be called from outside of the class and they return something, which is not correct.
If not possible, then they have to use number instance variable.
The code returns wrong results, because you are not setting the value of word variable, it is null.
The program that I've written is giving me the wrong output. It verifies whether the input password is 6 characters long with letters and numbers, if one of the requirement is not met, then it should say "Invalid Password." Otherwise, then it should output "Password Accepted." But when I enter more than 6 character long password, though the password is all letters, it still say password accepted.
import java.util.*;
public class passwd {
public static void main(String[] args)
{
String in_pass;
int i = 0, x = 0, l = 0, d = 0;
boolean valid_len;
Scanner in = new Scanner(System.in);
System.out.print("Enter Password: ");
in_pass = in.next();
int len = in_pass.length();
valid_len = (len >= 6) ? true : false;
char passwd_l;
char passwd_d;
if (valid_len == false)
{
System.out.println("Invalid Password");
}
else if (valid_len == true)
{
for (i = 0, x = 0; i < len; i++, x++)
{
passwd_l = in_pass.charAt(i);
if (Character.isLetter(passwd_l))
{
l += i;
}
passwd_d = in_pass.charAt(x);
if (Character.isDigit(passwd_d))
{
d += x;
}
}
}
if (i > 0 && x > 0)
{
System.out.println("Password Accepted");
}
}
}
Check out this one!
else if (valid_len == true){
for (i = 0; i < len; i++){
passwd_l = in_pass.charAt(i);
if (Character.isLetter(passwd_l))
{
l ++;
}
if (Character.isDigit(passwd_l))
{
d ++;
}
}
}
if (l > 0 && d > 0){
System.out.println("Password Accepted");
}
I've been having trouble with this assignment:
Given a string, replace the first occurrence of 'a' with "x", the second occurrence of 'a' with "xx" and the third occurrence of 'a' with "xxx". After the third occurrence, begin the replacement pattern over again with "x", "xx", "xxx"...etc.; however, if an 'a' is followed by more than 2 other 'a' characters in a row, then do not replace any more 'a' characters after that 'a'.
No use of the replace method is allowed.
aTo123X("ababba") → "xbxxbbxxx"
aTo123X("anaceeacdabnanbag") → "xnxxceexxxcdxbnxxnbxxxg"
aTo123X("aabaaaavfaajaaj") → "xxxbxxxaaavfaajaaj"
aTo123X("pakaaajaaaamnbaa") → "pxkxxxxxxjxxaaamnbaa"
aTo123X("aaaak") → "xaaak"
My code's output is with a's included, x's added but not the correct amount of x's.
public String aTo123X(String str) {
/*
Strategy:
get string length of the code, and create a for loop in order to find each individual part of the String chars.check for a values in string and take in pos of the a.
if one of the characters is a
replace with 1 x, however, there aren't more than 2 a's immediately following first a and as it keeps searching through the index, add more x's to the original string, but set x value back to 1 when x reaches 3.
if one of characters isn't a,
leave as is and continue string.
*/
String xVal = "";
String x = "x";
String output = "";
for (int i = 0; i < str.length(); i++){
if( str.charAt(i) == 'a'){
output += x;
str.substring(i+1, str.length());
}
output += str.charAt(i);
}
return output;
}
This is the code that does the same. I've commented the code to explain what it does
public class ReplaceChar {
public static void main(String... args){
String[] input =new String[]{"ababba","anaceeacdabnanbag","aabaaaavfaajaaj"};
StringBuilder result = new StringBuilder();
for (int i= 0; i < input.length;i++){
result.append(getReplacedA(input[i]));
result.append("\n");
}
System.out.println(result);
}
private static String getReplacedA(String withA){
// stringBuilder for result
StringBuilder replacedString = new StringBuilder();
// counting the number of time char 'a' occurred in String for replacement before row of 'aaa'
int charACount = 0;
// get the first index at which more than two 'aa' occurred in a row
int firstIndexOfAAA = withA.indexOf("aaa") + 1;
// if 'aaa' not occurred no need to add the rest substring
boolean addSubRequired = false;
// if the index is 0 continue till end
if (firstIndexOfAAA == 0)
firstIndexOfAAA = withA.length();
else
addSubRequired = true;
char[] charString = withA.toCharArray();
//Replace character String[] array
String[] replace = new String[]{"x","xx","xxx"};
for(int i = 0; i < firstIndexOfAAA; i++){
if (charString[i] == 'a'){
charACount++;
charACount = charACount > 3 ? 1 : charACount ;
// add the number x based on charCount
replacedString.append(replace[charACount - 1]);
}else{
replacedString.append(charString[i]);
}
}
// if the String 'aaa' has been found previously add the remaining subString
// after that index
if (addSubRequired)
replacedString.append(withA.substring(firstIndexOfAAA));
// return the result
return replacedString.toString();
}
}
Output:
xbxxbbxxx
xnxxceexxxcdxbnxxnbxxxg
xxxbxxxaaavfaajaaj
EDIT : Some Improvement You can make for some corner cases in the getReplacedA() function:
Check if char 'a' is there or not in the String if not just return the String No need to do anything further.
Use IgnoreCase to avoid the uppercase or lowercase possibility.
Firstly, string is immutable, so the below statement does nothing
str.substring(i+1, str.length());
I guess you wanted to do:
str = str.substring(i+1, str.length());
However, even after fix that, your program still doesn't work. I can't really comprehend your solution. 1) you are not detecting more than 3 a's in a row. 2) you are not appending "xx" or "xxx" at all
Here is my version, works for me so far:
public static void main(String[] args) {
System.out.println(aTo123X("ababba")); // "xbxxbbxxx"
System.out.println(aTo123X("anaceeacdabnanbag")); // "xnxxceexxxcdxbnxxnbxxxg"
System.out.println(aTo123X("aabaaaavfaajaaj")); // "xxxbxxxaaavfaajaaj"
}
public static String aTo123X(String str) {
String output = "";
int aOccurrence = 0;
String[] xs = {"x", "xx", "xxx"};
for (int i = 0; i < str.length(); ++i) {
if (str.charAt(i) == 'a') {
output += xs[aOccurrence % 3]; // append the x's depending on the number of a's we have seen, modulus 3 so that it forms a cycle of 3
if (i < str.length() - 3 && str.charAt(i + 1) == 'a' && str.charAt(i + 2) == 'a' && str.charAt(i + 3) == 'a') {//if an 'a' is followed by more than 2 other 'a' characters in a row
output += str.substring(i + 1);
break;
} else {
++aOccurrence; // increment the a's we have encountered so far
}
} else {
output += str.charAt(i); // append the character if it is not a
}
}
return output;
}
public class NewClass {
public static void main(String[] args) {
System.out.println(aTo123X("ababba")); // "xbxxbbxxx"
System.out.println(aTo123X("anaceeacdabnanbag")); // "xnxxceexxxcdxbnxxnbxxxg"
System.out.println(aTo123X("aabaaaavfaajaaj")); //xxxbxxxaaavfaajaaj
}
public static String aTo123X(String str) {
String output = "";
int aCount = 0;
int inRow = 0;
for (int i = 0; i < str.length();) {
if (str.charAt(i) == 'a') {
if (inRow <= 1) {
inRow++;
aCount++;
if (aCount == 1) {
output += "x";
} else if (aCount == 2) {
output += "xx";
} else {
output += "xxx";
aCount = 0;
}
boolean multiple = ((i + 1) < str.length()) && (str.charAt(i + 1) == 'a')
&& ((i + 2) < str.length()) && (str.charAt(i + 2) == 'a');
if (multiple) {
i++;
while (i < str.length()) {
output += str.charAt(i++);
}
return output;
}
} else {
output += str.charAt(i);
}
} else {
output += str.charAt(i);
inRow = 0;
}
i++;
}
return output;
}
}
I am pointing out problems in your code in form of comments in the code itself.
public String aTo123X(String str) {
//You are not using xVal variable in your code, hence it's obsolete
String xVal = "";
//You don't need x variable as you can simply use string concatenation
String x = "x";
String output = "";
for (int i = 0; i < str.length(); i++) {
/**
* Here, in "if" block you have not implmented any logic to replace the 2nd and
* 3rd occurence of 'a' with 'xx' and 'xxx' respectively. Also, substring() returns
* the sub-string of a string but you are not accepting that string anywhere, and
* you need not even use sub-string as "for" loop will cycle through all the
* characters in the string. If use sub-string method you code will only process
* alternative characters.
*/
if( str.charAt(i) == 'a') {
output += x;
str.substring(i+1, str.length());
}
/**
* Because of this statement a's are also returned, because this statement gets
* in both scenarios, whether the current character of string is a or not.
* But, this statement should get executed only when current character of the
* string is 'a'. So, in terms of coding this statement gets executed no matter
* "if" loop is executed or not, but it should get executed only when "if" loop
* is not executed. So, place this statement in else block.
*/
output += str.charAt(i);
}
return output;
}
I have implemented the logic for you. Here is Solution for your problem, just copy and run it. It passes all the specified test cases.
public String aTo123X(String str) {
String output = "";
int count = 1;
boolean flag = true;
for (int i = 0; i < str.length(); i++) {
if(str.charAt(i) == 'a' && flag == true) {
switch(count) {
case 1: output += "x";
count++;
break;
case 2: output += "xx";
count++;
break;
case 3: output += "xxx";
count = 1;
break;
}
if ((str.charAt(i+1) == 'a' && str.charAt(i+2) == 'a') == true) {
flag = false;
}
}
else {
output += str.charAt(i);
}
}
return output;
}
I use Map To store where to replace
public static void main(String[] args) {
System.out.println(aTo123X("ababba"));//xbxxbbxxx
System.out.println(aTo123X("anaceeacdabnanbag"));//xnxxceexxxcdxbnxxnbxxxg
System.out.println(aTo123X("aabaaaavfaajaaj"));//xxxbxxxaaavfaajaaj
}
public static String aTo123X(String str){
String res = "";
int nthReplace = 1; //Integer to store the nth occurence to replace
//Map to store [key == position of 'a' to replace]
//[value == x or xx or xxx]
Map<Integer, String> toReplacePos = new HashMap<>();
//The loop to know which 'a' to replace
for (int i = 0; i < str.length(); i++) {
if(str.charAt(i) == 'a'){
toReplacePos.put(i, nthReplace % 3 == 1 ? "x": (nthReplace % 3 == 2 ? "xx": "xxx"));
nthReplace++;
//Break if an 'a' is followed by more than 2 other 'a'
try {
if((str.charAt(i+1) == 'a')
&& (str.charAt(i+2) == 'a')
&& (str.charAt(i+3) == 'a')){
break;
}
} catch (StringIndexOutOfBoundsException e) {
}
}
}
//Do the replace
for (int i = 0; i < str.length(); i++) {
res += toReplacePos.containsKey(i) ? toReplacePos.get(i) : str.charAt(i);
}
return res;
}
I have edited my answer. This one is giving the correct solution:
public static void main (String[] args) throws InterruptedException, IOException, JSONException {
System.out.println(aTo123X("ababba")); //xbxxbbxxx
System.out.println(aTo123X("anaceeacdabnanbag")); //xnxxceexxxcdxbnxxnbxxxg
System.out.println(aTo123X("aabaaaavfaajaaj")); //xxxbxxxaaavfaajaaj
}
public static String aTo123X(String str) {
String x = "x";
String xx = "xx";
String xxx = "xxx";
int a = 1;
int brek = 0;
String output = "";
for (int i = 0; i < str.length(); i++) {
if(str.charAt(i) == 'a' && a == 1) {
output += x;
str.substring(i+1, str.length());
a = 2;
try {
if(str.charAt(i+1) == 'a' && str.charAt(i+2) == 'a')
brek += 1;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else if(str.charAt(i) == 'a' && a == 2) {
output += xx;
str.substring(i+1, str.length());
a = 3;
try {
if(str.charAt(i+1) == 'a' && str.charAt(i+2) == 'a')
brek += 1;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else if(str.charAt(i) == 'a' && a == 3) {
output += xxx;
str.substring(i+1, str.length());
a = 1;
try {
if(str.charAt(i+1) == 'a' && str.charAt(i+2) == 'a')
brek += 1;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
output += str.charAt(i);
brek = 0;
}
if(brek>0) {
output += str.substring(i+1);
break;
}
}
return output;
}
I have to make a program that converts Roman numbers to decimal. I am confused about how to write the conditions for the Roman numbers, such as IV (4), IX (9), XL (40) and CM(900). The code that I wrote works for all the other numbers.
public static void main(String[] args) {
System.out.print("Enter a roman numeral: ");
Scanner in = new Scanner(System.in);
String Roman = in.next();
int largo = Roman.length();
char Roman2[] = new char[largo];
int Roman3[] = new int[largo];
for (int i = 0; i < largo; i++) {
Roman2[i] = Roman.charAt(i);
}
for (int i = 0; i < largo; i++) {
if (Roman2[i] == 'I') {
Roman3[i] = 1;
} else if (Roman2[i] == 'V') {
Roman3[i] = 5;
} else if (Roman2[i] == 'X') {
Roman3[i] = 10;
} else if (Roman2[i] == 'L') {
Roman3[i] = 50;
} else if (Roman2[i] == 'C') {
Roman3[i] = 100;
} else if (Roman2[i] == 'M') {
Roman3[i] = 1000;
}
}
int total = 0;
for (int m = 0; m < Roman3.length; m++) {
total += Roman3[m];
}
System.out.println("The Roman is equal to " + total);
}
You can check the previous digit.
For example, I added the condition that detects IV :
if (Roman2[i]=='I'){
Roman3[i]=1;
} else if (Roman2[i]=='V'){
Roman3[i]=5;
if (i>0 && Roman2[i-1]=='I') { // check for IV
Roman3[i]=4;
Roman3[i-1]=0;
}
} else if (Roman2[i]=='X'){
Roman3[i]=10;
} else if (Roman2[i]=='L'){
Roman3[i]=50;
} else if (Roman2[i]=='C'){
Roman3[i]=100;
} else if (Roman2[i]=='M'){
Roman3[i]=1000;
}
Define enum like below:
public enum RomanSymbol {
I(1), V(5), X(10), L(50), C(100), D(500), M(1000);
private final int value;
private RomanSymbol(final int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
public int calculateIntEquivalent(final int lastArabicNumber, final int totalArabicResult) {
if (lastArabicNumber > this.value) {
return totalArabicResult - this.value;
} else {
return totalArabicResult + this.value;
}
}
}
And use it like RomanSymbol.I.getValue() which will return 1 and similarly for other.
So if you accept character from user, you can get the values as:
char symbol = 'I';//lets assume this is what user has entered.
RomanSymbol rSymbol = RomanSymbol.valueOf(String.valueOf(symbol));
int invalue = rSymbol.getValue();
And if you have string like IV, then you could calculate on something like for example:
int lastValue = rSymbol.calculateIntEquivalent(intValue, 0);
lastValue = rSymbol.calculateIntEquivalent(intValue, lastValue); //and so on