Click here to Skip to main content
15,512,244 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I'm doing a project for school and I need to make a password verifier (I.e, longer than 8 chars, not using invalid chars). The code will be finished when I figure out how to fix the dead code issue:
Java
import java.util.Scanner;
class Main {
  static boolean valid = false;
  static void password(String pass) {
    String[] ivp = {"!","@","#","$", "%", "^", "^", "&", "*", "(", ")", "~", "`","\"", "'", "/", "<",">",",", ".", "/", "\\", ";", ":", "{", "}", "[", "]","?", "+", "=", "_", "-"};
      for (int j = 0; j < ivp.length; j++) {
          if (pass.length() < 8) {
      System.out.println("Password must have at least eight characters.");
      valid = false;
    }
    if (pass.contains(ivp[j])) {
      System.out.println("Password must only contain letters and digits.");
      valid = false;
    }
    else {
    System.out.println("Password accepted!");
    valid = true;
    }
    if (valid); {
      break;
    }
    }
  }

  public static void main(String[] args) {
    String sn = "";
    Scanner scn = new Scanner(System.in);
    while(!valid) {
    System.out.print("Enter a string: ");
    sn = scn.nextLine();
   password(sn);
    }
  }
}


What I have tried:

putting a semicolon after the partese the if statements.
Posted
Updated 8-Apr-21 11:29am
v4
Comments
Patrice T 8-Apr-21 15:19pm    
Give exact error message.

1 solution

First thing you need to do is move the length test outside of the loop.

If only letters and numbers are valid it would be easier to just test to see if each of the characters in the pass string is alphabetic or numeric using the isLetterOrDigit function.

Java
import java.util.Scanner;
class Main 
{
	static boolean valid;
	static void password(String pass) {
		boolean valid = true;
		
		if (pass.length() < 8) {
			System.out.println("Password must have at least eight characters.");
			valid = false;
		}
		else {
			for (int j = 0; j < pass.length(); j++)	{
				if (!Character.isLetterOrDigit(pass.charAt(j)))	{
					System.out.println("Password must only contain letters and digits.");
					valid= false;
					break;
				}
			}
			
			if (valid) {
				System.out.println("Password accepted!");
			}
		}
	}

	public static void main(String[] args)
	{
		String sn = "";
		Scanner scn = new Scanner(System.in);
		while(!valid) {
			System.out.print("Enter a string: ");
			sn = scn.nextLine();
			password(sn);
		}
		
		scn.close();
	}
}
 
Share this answer
 
v2
Comments
c0d3r1/2 8-Apr-21 18:44pm    
Thank you. You are truly a godsend. IDK why my code did not work. Thankfully someone gets it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900