The password validation sends out the wrong output? - java

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");
}

Related

How do I add a loop to this password checker

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");
}
}
}

how to find upside down of a 2digit number

I am trying to write program to find upside down of all double digit number. Actually I have written this code and it works pretty well too. Any other alternatives to find upside down of an integer. Say 18=81 and 96=69....
List < Integer > al = new ArrayList < Integer > ();
al.add(10);al.add(11);al.add(16);al.add(18);al.add(19);al.add(60);al.add(61);
al.add(66);al.add(69);al.add(80);al.add(81);al.add(86);al.add(88);al.add(91);
al.add(96);al.add(98);al.add(99);
Scanner s = new Scanner(System.in);
Integer n = s.nextInt();
if (((String)"" + n).length() == 2) {
if (al.contains(n))
System.out.println("yes");
else
System.out.println("no");
}
This is a simple, general algorithm analysing an integer w.r.t. digits with vertical symmetry. (It depends on a certain style of writing digits; note that "continental" '1' is not symmetrical.)
private static int[] other = new int[]{0, 1, -1, -1, -1, -1, 9, -1, 8, 6};
public static int invert( int n ){
int units = n % 10;
n /= 10;
int inv = other[units];
if( n == 0 ) return inv;
return inv < 0 ? -1 : invert( n )*10 + inv;
}
If a negative value is returned, the number is not symmetrical.
public static void main(String[] args) throws Exception {
for( int i = 100; i <= 199; ++i ){
int invi = invert( i );
if( invi > 0 ){
System.out.println( i + ": " + invi );
}
}
}
This is a better way of doing it.
It not only prints yes or no, but also the up side down number
public static void main(String[] args) {
List<String> al = new ArrayList<String>();
al.add("0");
al.add("1");
al.add("6");
al.add("8");
al.add("9");
Scanner s = new Scanner(System.in);
Integer n = s.nextInt();
String num = n + "";
if (num.length() == 2) {
if(al.contains(num.charAt(0) + "") && al.contains(num.charAt(1) + "")) {
System.out.println("Yes");
String upSideDownNumber = "";
if(num.charAt(1) == 6) {
upSideDownNumber += 9;
} else if(num.charAt(1) == 9) {
upSideDownNumber += 6;
} else {
upSideDownNumber += num.charAt(1);
}
if(num.charAt(0) == 6) {
upSideDownNumber += 9;
} else if(num.charAt(0) == 9) {
upSideDownNumber += 6;
} else {
upSideDownNumber += num.charAt(0);
}
System.out.println("The up side down number is " + upSideDownNumber);
} else {
System.out.println("No");
}
} else {
System.out.println("No");
}
}
Since only 0,1,6,8,9 look like digits when inverted. You can so below:
public static void main(String[] args) throws IOException {
Set<Integer> upsideDownProperDigits = new TreeSet<>(Arrays.asList(0,1,8,9,6));
Scanner s = new Scanner(System.in);
Integer n = s.nextInt();
boolean found = true;
while( n != 0){
int digit = n % 10;
if(!upsideDownProperDigits.contains(digit)){
found = false;
break;
}
n = n/10;
}
if(found){
System.out.println("yes");
}
else{
System.out.println("no");
}
}

Roman number to decimal in Java

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

not getting correct numbers in for loop

Hy there. Below you can see sagment of my code. So lets go to the problem.
int i is not returning correct values and i cannot figure it out why.
LIST: [AGRFT, AGRFT, ARNES, ASCII, ASEAN, Aaron, Abdul, Abdul]
So for example. User inputs AS***, the program should return i is at 2. However i am getting i is at 0.
If i remember right it should go like this:
User_input= AS***
User_input.lenght() should be 5
first it should be user_input.charAt(0)=='*' NO
second it should be user_input.charAt(1)=='*' NO
third it should be user_input.charAt(2)=='*' YES
BREAK
i is at 2.
SO what am i missing?
I am getting 0.
Oh and also at
for(i=0; i < user_input.length();i++){
i am getting warning that i++ is Dead code?
if (dolzina == 5) {
for(i=0; i < user_input.length();i++){
if (user_input.charAt(i)=='*');
break;
}
System.out.println("i is at "+ i);
this is my full code for refrence. What it does it reads from txt file add wor
public class proba {
public static void main(String[] args) {
String izbira;
int dolzina=0;
int i=0;
Scanner in = new Scanner(System.in);
String user_input;
Scanner input = new Scanner(System.in);
String regex;
List<String> list5 = new ArrayList<String>();
int beseda;
String prefix = null;
try {
File file = new File("sort.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String vrstica;
while ((vrstica = bufferedReader.readLine()) != null) {
if (vrstica.length() == 5) {
list5.add(vrstica);
}
}
System.out.println(list5);
do{
do {
System.out.println("Enter lenght of word:");
if (in.hasNextInt()) {
dolzina = in.nextInt();
} else if (in.hasNextLine()) {
System.out.printf("Wrong entry!%n ",
in.nextLine());
}
} while (dolzina <= 0);
Collections.sort(list5);
System.out.println("Enter a word for unknown character enter * :");
user_input = input.nextLine();
System.out.println("Sorted list: [length: " + list5.size() + "]");
if (dolzina == 5) {
for(i=0; i < user_input.length();i++){
if (user_input.charAt(i)=='*');
break;
}
System.out.println("i je"+ i);
prefix=user_input.substring(0,i);
System.out.println(prefix);
int start=binarySearchfirst(list5,prefix);
int end=binarySearchlast(list5,prefix);
System.out.println(start);
System.out.println(end);
for (int b=start;b<=end;b++)
{
user_input = user_input.replace("*", ".");
String s = (String) list5.get(b);
if (s.matches(user_input))
System.out.println(s);
}
}
dolzina=-1;
System.out.println("Ponovni vnos (da/ne):");
Scanner inn= new Scanner (System.in);
izbira = inn.next();
}while (izbira.equalsIgnoreCase("da"));
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}}
public static int binarySearchfirst(List<String> integerList, String prefix) {
int low = 0;
int high = integerList.size() - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (integerList.get(mid).startsWith(prefix)) {
if (mid == 0 || !integerList.get(mid - 1).startsWith(prefix)) {
return mid;
} else {
high = mid - 1;
}
} else if (prefix.compareTo(integerList.get(mid)) > 0) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return low;
}
public static int binarySearchlast(List<String> integerList, String prefix) {
int low = 0;
int high = integerList.size()-1;
while (low <= high) {
int mid = (low+high)/2;
if (integerList.get(mid).startsWith(prefix)) {
if (mid == integerList.size()-1 || !integerList.get(mid+1).startsWith(prefix)) {
return mid;
}
else {
low = mid+1;
}
}
else if (prefix.compareTo(integerList.get(mid)) > 0) {
low = mid+1;
}
else {
high = mid-1;
}
}
return high;
}
}
You have an extra semi-colon after your if statement:
for(i=0; i < user_input.length();i++)
{ if (user_input.charAt(i)=='*');
break;
}
So the break is executed the first time through the loop no matter what. This is also why i++ is being reported as dead code...it's never being executed.

How to find Largest Prime Number, Smallest Factor except 1, Sum of Numbers

Herro, Um I'm not sure if this is how you use this site but uh lets get to it... So I need help on this project and I have to do this -
Input [][] Output
A - F -> Multiply by 3, Divide by 4
G - J -> Divide by 3 + 25
K - N -> Find Greatest Factor * 2
O - Q -> Find largest prime inclusive * 3
R - W -> Find Smallest Factor Except 1
X - Z -> Sum Numbers
So I was wondering if my first couple is correct, and need help on the empty space. So the Letter represents the number of the as in "Z" is the last letter so its 26, and "A" is the first so its 1. So if an responses... Thanks ! package Fun;
import java.util.Scanner;
public class Fun {
public static void main(String[] args) {
// TODO Auto-generated method stub
run();
}
public static void run()
{
input();
evaluateAlphabet();
evaluate();
}
public static void input()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a Letter, please");
x = sc.next();
}
public static String x = " ";
public static int temp = 0;
public static int answer = 0;
public static void evaluateAlphabet()
{
if(x.equals("A"))
{
temp = 1;
}
else if (x.equals("B"))
{
temp = 2;
}
else if (x.equals("C"))
{
temp = 3;
}
else if (x.equals("D"))
{
temp = 4;
}
else if (x.equals("E"))
{
temp = 5;
}
else if (x.equals("F"))
{
temp = 6;
}
else if (x.equals("G"))
{
temp = 7;
}
else if (x.equals("H"))
{
temp = 8;
}
else if (x.equals("I"))
{
temp = 9;
}
else if (x.equals("J"))
{
temp = 10;
}
else if (x.equals("K"))
{
temp = 11;
}
else if (x.equals("L"))
{
temp = 12;
}
else if (x.equals("M"))
{
temp = 13;
}
else if (x.equals("N"))
{
temp = 14;
}
else if (x.equals("O"))
{
temp = 15;
}
else if (x.equals("P"))
{
temp = 16;
}
else if (x.equals("Q"))
{
temp = 17;
}
else if (x.equals("R"))
{
temp = 18;
}
else if (x.equals("S"))
{
temp = 19;
}
else if (x.equals("T"))
{
temp = 20;
}
else if (x.equals("U"))
{
temp = 21;
}
else if (x.equals("V"))
{
temp = 22;
}
else if (x.equals("W"))
{
temp = 23;
}
else if (x.equals("X"))
{
temp = 24;
}
else if (x.equals("Y"))
{
temp = 25;
}
else if (x.equals("Z"))
{
temp = 26;
}
else if (x.equals("Qwerty"))
{
temp = 27;
}
}
public static void evaluate()
{
if(temp>=1 && temp<= 6)
{
answer = (temp * 3)/4;
System.out.println("Answer is " + answer);
}
else if(temp >= 7 && temp<= 10)
{
answer = (temp/3) + 25;
System.out.println("Answer is " + answer);
}
else if(temp >= 11 && temp<= 14)
{
}
else if(temp>=15 && temp<= 17)
{
for(int i = temp; i>0; i--)
{
for(int j = 2; j <=i/2 + 1; j++)
{
if(i%j==0)
{
break;
}
if(j==i/2 + 1)
{
answer = i * 3;
}
}
}
System.out.println("Answer is " + answer);
}
else if(temp>=18 && temp<= 23)
{
answer = temp;
}
else if(temp>= 24 && temp<=26)
answer = (answer * 12)%26;
System.out.println("Answer is " + answer);
}
}
-Corruption
Here is a better approach for char to int conversion:
Assuming the string has at least 1 character(check for its length), you can get the temp by doing:
temp = x.getCharAt(0) - 'A' + 1;
or, safety first:
temp = 0;
if (x.matches("^[A-Z]{1}$") {
temp = x.getCharAt(0) - 'A' + 1;
}
What's happening here? Every character has an ASCII code, an integer. So, when you have 2 chars and you try to get the distance between them, the result is an int. 'A' - 'A' = 0(that's why i added a + 1), 'B' - 'A' = 1 and so on.
For the if condition, I am using a RegExp. ^ means start of the input, [A-Z]{1} means one of A-Z, $ means the end of the input. So, if it's an A-Z, temp will get a value, anything else won't make it in the if and your temp will remain 0 so you can easily test if you've got an A-Z or not.
That's all for code review, I won't give you solutions, you must work harder, use Google. You won't enjoy and learn if I give you everything ready for a copy paste.

Categories

Resources