1 Replies - 240 Views - Last Post: 06 October 2012 - 11:19 PM Rate Topic: -----

#1 GhostedWill  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 16
  • Joined: 07-September 11

Java syntax tips

Posted 06 October 2012 - 08:12 PM

Hey all, this topic is mostly about syntax. By this I mean the program that I wrote below does as intended but since im new to java im a bit skeptic if the way im writing the code is the proper way.. just need tips of what to avoid and such. Any tip would help.



package Runner;

import edu.mdc.cop2800.passvalidation.Password;
import java.util.Scanner;

public class Runner {

	
	private static Scanner scn;

	public static void main(String[] args) {
		scn = new Scanner(System.in);
		Password psw = new Password();
		
		System.out.println("Enter Password: ");
		psw.setPassword(scn.nextLine());
		psw.validate();
		
		if(psw.validate())
			System.out.println("Your Password meets all requirements.");
		else
			System.out.println("Check your password requirements! Maximum of 8 characters(letters & numbers(2 or more))");
	}

}



package edu.mdc.cop2800.passvalidation;

public class Password {
	
	private char[] password;
	private static final int MAXCHARS = 8;
	
	public Password (){
		password = null;
	}
	
	public Password(String  newPassword){
		setPassword(newPassword);
	}
	
	//setters
	public void setPassword(String newPassword){
		password = newPassword.toCharArray();
	}
	
	//getters
	public String getPassword(){
		return password.toString();
	}
	
	//methods
	public boolean passLength(){
		if(password.length > MAXCHARS)
			return false;
		return true;
	}
	public boolean validate(){
		int digitCheck = 0;
		int letterCheck = 0;
		if(passLength()){
			for(int i = 0; i < password.length; i++){
				if(Character.isWhitespace(password[i]))
					return false;
				if(Character.isLetter(password[i])){
					letterCheck++;
				}
				if(Character.isDigit(password[i])){
					digitCheck++;
				}	
			}
			if(digitCheck < 2)
				return false;
			else{
				if(letterCheck == (MAXCHARS-digitCheck))
					return true;
				return false;
			}
		}
		return false;
	}

}



Thanks in advance :bigsmile:

Is This A Good Question/Topic? 0
  • +

Replies To: Java syntax tips

#2 farrell2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 862
  • View blog
  • Posts: 2,650
  • Joined: 29-July 11

Re: Java syntax tips

Posted 06 October 2012 - 11:19 PM

Lookg nice, but one thing does stick out: You have some if statements in brackets, and some not. While you do not need brackets in an ie/else with a single statement, it is good to use them anyway, to help prevent the dangling else problem.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1