nothing will output - java

no matter where I place the output statement, whether is it for 1 place of the array, all of the array, or even the count variable. I can't print out ANYTHING to the console. I have tried printing in the main, and in the functions. any ideas?
Edit1: I have discovered I can print inside a jswing window, but still no luck to the console, which is making error checking difficult.
Given the fact that I can still output correctly in a window, and people claim eclipse will print it out, I have deemed that the console for my ancient text editor is just incompetent, I appreciate the help
'
//=========================//
//colby moniz project 9-1 //
//Number sorter //
//=========================//
//===========================================//
//This program takes 10 integers and sorts //
//them into even, odd, and negative. //
//===========================================//
//=============//
//Import Files //
//=============//
import javax.swing.*; // DRAW DIALOG BOX CLASS
import java.awt.*; // IMPORT AWT TO CHANGE FONT AND COLORS
public class p91 {
public static void main(String[] args) {
//=================================//
//varbiles section //
//=================================//
sorter sort = new sorter(); //Creatests an instances of sorter, inside main.
int[] test = new int[10];
int inputNum;
//================================//
//Introduction windows //
//================================//
info( "This program will sort 10 intergers, \n into the catagories minimum, maximum and negitive",
"Introduction" );
//===========================//
//fill up array //
//===========================//
for(int count = 0; count < 10; count++)
{
inputNum = input("please input number " + (count + 1), "Input");
test[count] = inputNum;
}
for(int count = 0; count < 10; count++)
{
System.out.print(test[count]);
}
}
//====================================================//
//Functions //
//====================================================//
public static void info(String a, String b)
{
//================================//
//Introduction window //
//================================//
int close = JOptionPane.showConfirmDialog(null,
a, b,
JOptionPane.DEFAULT_OPTION,
JOptionPane.INFORMATION_MESSAGE);
checkCloseInt(close);
}
public static void checkCloseInt(int close)
{
//=====================================
//checks to see if user closed program
//=====================================
if ((close == JOptionPane.CLOSED_OPTION) ||
(close == JOptionPane.NO_OPTION) ||
(close == JOptionPane.CANCEL_OPTION))
System.exit(0);
}
public static int input(String a, String b)
{
//================================//
//input //
//================================//
boolean parsable;
int inputParse = 999;
String input;
do
{
input = JOptionPane.showInputDialog(null,
a, b,
JOptionPane.QUESTION_MESSAGE);
//======================//
//Check if close //
//======================//
if(input == null)
{
System.exit(0);
}
parsable = error(input);
}
while(parsable == false);
inputParse = Integer.parseInt(input);
System.out.print(inputParse);
return inputParse;
}
public static boolean error(String input)
{
//======================
//Check if parsable
//=======================
boolean parsable = true;
try
{
int inputParse = Integer.parseInt(input);
}
catch(NumberFormatException e)
{
parsable = false;
}
if(parsable == false)
{
errorWindow("Please input a number");
}
return parsable;
}
public static void errorWindow(String a)
{
//================================//
//Introduction window //
//================================//
int close = JOptionPane.showConfirmDialog(null,
a, "Error",
JOptionPane.DEFAULT_OPTION,
JOptionPane.ERROR_MESSAGE);
checkCloseInt(close);
}
}
'

Use System.out.println(); this works for meĀ“.

Related

Algorithm to find `balanced number` - the same number of even and odd dividers

We define balanced number as number which has the same number of even and odd dividers e.g (2 and 6 are balanced numbers). I tried to do task for polish SPOJ however I always exceed time.
The task is to find the smallest balance number bigger than given on input.
There is example input:
2 (amount of data set)
1
2
and output should be:
2
6
This is my code:
import java.math.BigDecimal;
import java.util.Scanner;
public class Main {
private static final BigDecimal TWO = new BigDecimal("2");
public static void main(String[] args) throws java.lang.Exception {
Scanner in = new Scanner(System.in);
int numberOfAttempts = in.nextInt();
for (int i = 0; i < numberOfAttempts; i++) {
BigDecimal fromNumber = in.nextBigDecimal();
findBalancedNumber(fromNumber);
}
}
private static boolean isEven(BigDecimal number){
if(number.remainder(new BigDecimal("2")).compareTo(BigDecimal.ZERO) != 0){
return false;
}
return true;
}
private static void findBalancedNumber(BigDecimal fromNumber) {
BigDecimal potentialBalancedNumber = fromNumber.add(BigDecimal.ONE);
while (true) {
int evenDivider = 0;
int oddDivider = 1; //to not start from 1 as divisor, it's always odd and divide potentialBalancedNumber so can start checking divisors from 2
if (isEven(potentialBalancedNumber)) {
evenDivider = 1;
} else {
oddDivider++;
}
for (BigDecimal divider = TWO; (divider.compareTo(potentialBalancedNumber.divide(TWO)) == -1 || divider.compareTo(potentialBalancedNumber.divide(TWO)) == 0); divider = divider.add(BigDecimal.ONE)) {
boolean isDivisor = potentialBalancedNumber.remainder(divider).compareTo(BigDecimal.ZERO) == 0;
if(isDivisor){
boolean isEven = divider.remainder(new BigDecimal("2")).compareTo(BigDecimal.ZERO) == 0;
boolean isOdd = divider.remainder(new BigDecimal("2")).compareTo(BigDecimal.ZERO) != 0;
if (isDivisor && isEven) {
evenDivider++;
} else if (isDivisor && isOdd) {
oddDivider++;
}
}
}
if (oddDivider == evenDivider) { //found balanced number
System.out.println(potentialBalancedNumber);
break;
}
potentialBalancedNumber = potentialBalancedNumber.add(BigDecimal.ONE);
}
}
}
It seems to work fine but is too slow. Can you please help to find way to optimize it, am I missing something?
As #MarkDickinson suggested, answer is:
private static void findBalancedNumberOptimized(BigDecimal fromNumber) { //2,6,10,14,18,22,26...
if(fromNumber.compareTo(BigDecimal.ONE) == 0){
System.out.println(2);
}
else {
BigDecimal result = fromNumber.divide(new BigDecimal("4")).setScale(0, RoundingMode.HALF_UP).add(BigDecimal.ONE);
result = (TWO.multiply(result).subtract(BigDecimal.ONE)).multiply(TWO); //2(2n-1)
System.out.println(result);
}
}
and it's finally green, thanks Mark!

Java Input Validation

So I am working with a program that is supposed to incorporate try-catch blocks for exception handling. What I can't figure out is how to write a simple if statement for checking input from the user via Scanner to make sure it is a double and not a letter or a character so that if it is the program will catch it, display the error message, and tell the user to re-enter another value until a suitable input is entered. What I am looking for is a simple if(_width equals a letter/character) then return false along with an error message to go along with my already present if statement that checks whether the input is greater than zero.
my current code is below:
public class Rectangle {
//two double data fields width and height, default values are 1 for both.
private double width = 1;
private double height = 1;
private String errorMessage = "";
//no-arg constructor creates default rectangle
public Rectangle() {
}
//fpzc, called by another program with a statement like Rectangle rec = new Rectangle(#, #);
public Rectangle (double _width, double _height) throws Exception {
setWidth(_width);
setHeight(_height);
}
//get functions
public double getArea(){
return (width * height);
}
public double getPerimeter() {
return (2*(width + height));
}
public String getErrorMessage() {
return errorMessage;
}
//set functions
public void setWidth(double _width) throws Exception {
if( !isValidWidth(_width)){
Exception e = new Exception(errorMessage);
throw e;
//System.out.println(errorMessage);
//return false;
}
width = _width;
}
public void setHeight(double _height) throws Exception {
if ( !isValidHeight(_height)){
Exception e = new Exception(errorMessage);
throw e;
//System.out.println(errorMessage);
//return false;
}
height = _height;
}
//isValid methods
public boolean isValidWidth(double _width) {
if(_width > 0){
return true;
}
else {
errorMessage = "Invalid value for width, must be greater than zero";
return false;
}
if ()
}
public boolean isValidHeight(double _height) {
if(_height > 0){
return true;
}
else {
errorMessage = "Invalid value for height, must be greater than zero";
return false;
}
}
}
My class is being called by another test program that i have written correctly. Any help is appreciated! Thank you.
maybe something like:
String errorMessage = "error";
Scanner in = new Scanner(System.in);
String str = in.nextLine();
try {
Double.parseDouble(str);
}
catch( Exception e ){
System.out.println(errorMessage);
}
or iterate through the input and check if each character is digit:
String errorMessage = "error";
Scanner in = new Scanner(System.in);
String str = in.nextLine();
for(int i=0;i<str.length();i++){
char token = str.charAt(i);
if(!Character.isDigit(token) && token!='.' ) {
System.out.println(token + " doesnt work");
break;
}
}
On declaring your scanner you could also:
double num;
String errorMessage = "error";
while(true) {
Scanner in = new Scanner(System.in);
if (in.hasNextDouble()) {
num = in.nextDouble();
System.out.println(num);
break;
}
else System.out.println(errorMessage);
}
Maybe this code helps you:
double Input=0;
while(!(Input > 0)){{
System.out.println("Enter Valid Number");
Input = new Scanner(System.in).nextDouble();
}

Change output after each run to one output after all runs

My program is pretty much all finished except for the output, I want it to display everything in one output rather than one after each run, it is supposed to run 500 times but made it only 10 until I have this problem fixed.
package assignment5;
import javax.swing.JOptionPane;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import java.text.*;
public class assignment5
{
public static void main(String[] args)
{
lottery pic=new lottery();for(int i = 0; i <10; i++)
{
pic.Get_player_numbers();
pic.Get_jackpot_number();
pic.Check_winner ();
pic.Write_data();
}
}
}
class lottery
{
int[] picks= new int[5];
int[] cpick=new int[5];
int i;
int j,c;
int match=0;
double matchcount0=0;
double matchcount1=0;
double matchcount2=0;
double matchcount3=0;
double matchcount4=0;
double matchcount5=0;
int jackpot = 25000000;
int payout;
void Get_player_numbers ()
{
int temp,dupflag=0;
for(i=0;i<=4;++i)
{
//YOU DO NOT NEED THE CNUMBERFLAG
//IF YOU GENERATED THE NUMBERS CORRECLTY, THE COMPUTER WILL NOT GENERATE ONE ABOVE 99 OR LESS THAN 1
dupflag=0;
while(dupflag==0)
{
temp = (int)Math.round(Math.random()*99)+1;
dupflag=1;
for(c=0;c<=i;++c)
{
if(temp==picks[c])
{
dupflag=0;
}
}//inner for loop
if(dupflag==1)
picks[i]=temp;
}
}
}
//void jackpot()
void Get_jackpot_number()
{
int ctemp,cdupflag=0;
for(j=0;j<=4;++j)
{
//YOU DO NOT NEED THE CNUMBERFLAG
//IF YOU GENERATED THE NUMBERS CORRECLTY, THE COMPUTER WILL NOT GENERATE ONE ABOVE 99 OR LESS THAN 1
cdupflag=0;
while(cdupflag==0)
{
ctemp = (int)Math.round(Math.random()*99)+1;
cdupflag=1;
for(c=0;c<=j;++c)
{
if(ctemp==cpick[c])
{
cdupflag=0;
}
}//inner for loop
if(cdupflag==1)
cpick[j]=ctemp;
}
}
String Jackpot="Computer Lottery numbers are: "+"\n";
//String computer = "";
for(j=0;j<=4;++j)
{
if(j==4)
Jackpot=Jackpot+cpick[j];
else
Jackpot=Jackpot+cpick[j]+"-";
}
}
void Check_winner ()
{
match=0;
for(int i=0;i<=4;++i)
{
for(int j=0;j<=4;++j)
{
if(picks[i]==cpick[j])
{
match=match+1;
}
}
}
}
void Write_data ()
{
if(match==0)
{
matchcount0=matchcount0+1;
payout=0;
jackpot=jackpot+25000;
}
else if(match==1)
{
matchcount1=matchcount1+1;
payout=100;
jackpot=jackpot+100000;
}
else if(match==2)
{
matchcount2=matchcount2+1;
jackpot=jackpot+250000;
payout=1000;
}
else if(match==3)
{
matchcount3=matchcount3+1;
jackpot=jackpot+500000;
payout=10000;
}
else if(match==4)
{
matchcount4=matchcount4+1;
jackpot=jackpot+1000000;
payout=100000;
}
else if(match==5)
{
matchcount5=matchcount5+1;
payout=jackpot;
jackpot=jackpot-jackpot+2500000;
}
System.out.println("Current Jackpot Player# Winner# #Matched Payout\n"+jackpot+" "+picks[0]+" "+picks[1]+" "+picks[2]+" "+picks[3]+" "+picks[4]+" "+cpick[0]+" "+cpick[1]+" "+cpick[2]+" "+cpick[3]+" "+cpick[4]+" "+match+" "+payout+"\nThe percent of plays where 0 numbers matched = "+matchcount0/i*100+"%\nThe percent of plays where 1 numbers matched = "+matchcount1/10+"%\nThe percent of plays where 2 numbers matched = "+matchcount2/10+"%\nThe percent of plays where 3 numbers matched = "+matchcount3/10+"%\nThe percent of plays where 4 numbers matched = "+matchcount4/10+"%\nThe percent of plays where 5 numbers matched = "+matchcount5/10+"%\n");
}
}
Use StringBuilder class. In each run you can just append new line two your StringBuilder instance.
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 10; ++i) {
builder.append(System.getProperty("line.separator") + "Current Jackpot player...");
}
When everything is done you can use
builder.toString();
to get your output.

match and delete elements in arraylists

I am making a robot maze where the robot reaches a target automatically without crashing into walls. I want the robot to do the maze once, learn the correct route and then the second time be able to get there straight away without going to any deadends. I thought I could do this by making three arraylists.
One for all the squares the robot visits.
Two for all the squares that lead to a deadend.
Three for all the directions the robot goes.
If the squares that lead to a dead end are found in the first arraylist then i can delete the same indexes in the third arraylist. That way, the second time, i can just iterate the third Arraylist.
My full code is below:
import java.util.ArrayList;
import java.util.*;
import java.util.Iterator;
import java.util.stream.IntStream;
public class Explorer {
private int pollRun = 0; // Incremented after each pass.
private RobotData robotData; // Data store for junctions.
private ArrayList<Integer> nonWallDirections;
private ArrayList<Integer> passageDirections;
private ArrayList<Integer> beenbeforeDirections;
private Random random = new Random();
int [] directions = {IRobot.AHEAD, IRobot.LEFT, IRobot.RIGHT, IRobot.BEHIND};
private ArrayList<Square> correctSquares;
private ArrayList<Square> wrongSquares;
private ArrayList<Integer> correctDirections;
public void controlRobot (IRobot robot) {
// On the first move of the first run of a new maze.
if ((robot.getRuns() == 0) && (pollRun ==0))
robotData = new RobotData();
pollRun++; /* Increment poll run so that the data is not reset
each time the robot moves. */
int exits = nonwallExits(robot);
int direction;
if ((robot.getRuns() != 0))
direction = grandfinale(robot);
nonWallDirections = new ArrayList<Integer>();
passageDirections = new ArrayList<Integer>();
beenbeforeDirections = new ArrayList<Integer>();
correctSquares = new ArrayList<Square>();
correctDirections = new ArrayList<Integer>();
// Adding each direction to the appropriate state ArrayList.
for(int item : directions) {
if(robot.look(item) != IRobot.WALL) {
nonWallDirections.add(item);
}
}
for(int item : directions) {
if(robot.look(item) == IRobot.PASSAGE) {
passageDirections.add(item);
}
}
for(int item : directions) {
if(robot.look(item) == IRobot.BEENBEFORE) {
beenbeforeDirections.add(item);
}
}
// Calling the appropriate method depending on the number of exits.
if (exits < 2) {
direction = deadEnd(robot);
} else if (exits == 2) {
direction = corridor(robot);
} else {
direction = junction(robot);
robotData.addJunction(robot);
robotData.printJunction(robot);
}
robot.face(direction);
addcorrectSquares(robot);
correctDirections.add(direction);
}
/* The specification advised to have to seperate controls: Explorer and Backtrack
and a variable explorerMode to switch between them.
Instead, whenever needed I shall call this backtrack method.
If at a junction, the robot will head back the junction as to when it first approached it.
When at a deadend or corridor, it will follow the beenbefore squares until it
reaches an unexplored path. */
public int backtrack (IRobot robot) {
if (nonwallExits(robot) > 2) {
addwrongSquares(robot);
return robotData.reverseHeading(robot);
} else {
do {
addwrongSquares(robot);
return nonWallDirections.get(0);
} while (nonwallExits(robot) == 1);
}
}
// Deadend method makes the robot follow the only nonwall exit.
public int deadEnd (IRobot robot) {
return backtrack(robot);
}
/* Corridor method will make the robot follow the one and only passage.
The exception is at the start. Sometimes, the robot will start with
two passages available to it in which case it will choose one randomly.
If there is no passage, it will follow the beenbefore squares
until it reaches an unexplored path.*/
public int corridor (IRobot robot) {
if (passageExits(robot) == 1) {
return passageDirections.get(0);
} else if (passageExits(robot) == 2) {
int randomPassage = random.nextInt(passageDirections.size());
return passageDirections.get(randomPassage);
} else {
return backtrack(robot);
}
}
/* Junction method states if there is more than one passage, it will randomly select one.
This applies to crossroads as well as essentially they are the same.
If there is no passage, it will follow the beenbefore squares until it reaches an unexplored
path. */
public int junction(IRobot robot) {
if (passageExits(robot) == 1) {
return passageDirections.get(0);
} else if (passageExits(robot) > 1) {
int randomPassage = random.nextInt(passageDirections.size());
return passageDirections.get(randomPassage);
} else {
return backtrack(robot);
}
}
// Calculates number of exits.
private int nonwallExits (IRobot robot) {
int nonwallExits = 0;
for(int item : directions) {
if(robot.look(item) != IRobot.WALL) {
nonwallExits++;
}
}
return nonwallExits;
}
// Calculates number of passages.
private int passageExits (IRobot robot) {
int passageExits = 0;
for(int item : directions) {
if(robot.look(item) == IRobot.PASSAGE) {
passageExits++;
}
}
return passageExits;
}
// Calculates number of beenbefores.
private int beenbeforeExits (IRobot robot) {
int beenbeforeExits = 0;
for(int item : directions) {
if(robot.look(item) == IRobot.PASSAGE) {
beenbeforeExits++;
}
}
return beenbeforeExits;
}
// Resets Junction Counter in RobotData class.
public int reset() {
return robotData.resetJunctionCounter();
}
public void addcorrectSquares(IRobot robot) {
Square newSquare = new Square(robot.getLocation().x, robot.getLocation().y);
correctSquares.add(newSquare);
}
public void addwrongSquares(IRobot robot) {
Square badSquare = new Square(robot.getLocation().x, robot.getLocation().y);
wrongSquares.add(badSquare);
}
public int grandfinale (IRobot robot) {
IntStream.range(0, correctSquares.size())
.map(index -> correctSquares.size() - index - 1)
.filter(index -> (((wrongSquares.x).contains(correctSquares.x)) && ((wrongSquares.y).contains(correctSquares.y))).get(index))
.forEach(index -> correctDirections.remove(index));
Iterator<Integer> routeIterator = correctDirections.iterator();
while (routeIterator.hasNext()) {
break;
}
return (routeIterator.next());
}
}
class RobotData {
/* It was advised in the specification to include the variable:
private static int maxJunctions = 10000;
However, as I am not using arrays, but ArrayLists, I do not
need this. */
private static int junctionCounter = 0;
private ArrayList<Junction> junctionList = new ArrayList<Junction>();
// Resets the Junction counter.
public int resetJunctionCounter() {
return junctionCounter = 0;
}
// Adds the current junction to the list of arrays.
public void addJunction(IRobot robot) {
Junction newJunction = new Junction(robot.getLocation().x, robot.getLocation().y, robot.getHeading());
junctionList.add(newJunction);
junctionCounter++;
}
// Gets the junction counter for Junction info method in Junction class.
public int getJunctionCounter (IRobot robot) {
return junctionCounter;
}
// Prints Junction info.
public void printJunction(IRobot robot) {
String course = "";
switch (robot.getHeading()) {
case IRobot.NORTH:
course = "NORTH";
break;
case IRobot.EAST:
course = "EAST";
break;
case IRobot.SOUTH:
course = "SOUTH";
break;
case IRobot.WEST:
course = "WEST";
break;
}
System.out.println("Junction " + junctionCounter + " (x=" + robot.getLocation().x + ", y=" + robot.getLocation().y +") heading " + course);
}
/* Iterates through the junction arrayList to find the
heading of the robot when it first approached the junction.
It does this by finding the first junction in the ArrayList
that has the same x and y coordinates as the robot.*/
public int searchJunction(IRobot robot) {
Junction currentJunction = null;
Iterator<Junction> junctionIterator = junctionList.iterator();
while (junctionIterator.hasNext()) {
currentJunction = junctionIterator.next();
if ((((currentJunction.x)==(robot.getLocation().x))) && ((currentJunction.y)==(robot.getLocation().y)))
break;
}
return currentJunction.arrived;
}
// Returns the reverse of the heading the robot had when first approaching the junction.
public int reverseHeading(IRobot robot) {
int firstHeading = searchJunction(robot);
int reverseHeading = 1; // Random integer to Iniitalise variable.
switch (firstHeading) {
case IRobot.NORTH:
if (robot.getHeading() == IRobot.NORTH)
reverseHeading = IRobot.BEHIND;
else if (robot.getHeading() == IRobot.EAST)
reverseHeading = IRobot.RIGHT;
else if (robot.getHeading() == IRobot.SOUTH)
reverseHeading = IRobot.AHEAD;
else
reverseHeading = IRobot.LEFT;
break;
case IRobot.EAST:
if (robot.getHeading() == IRobot.NORTH)
reverseHeading = IRobot.LEFT;
else if (robot.getHeading() == IRobot.EAST)
reverseHeading = IRobot.BEHIND;
else if (robot.getHeading() == IRobot.SOUTH)
reverseHeading = IRobot.RIGHT;
else
reverseHeading = IRobot.AHEAD;
break;
case IRobot.SOUTH:
if (robot.getHeading() == IRobot.NORTH)
reverseHeading = IRobot.AHEAD;
else if (robot.getHeading() == IRobot.EAST)
reverseHeading = IRobot.LEFT;
else if (robot.getHeading() == IRobot.SOUTH)
reverseHeading = IRobot.BEHIND;
else
reverseHeading = IRobot.RIGHT;
break;
case IRobot.WEST:
if (robot.getHeading() == IRobot.NORTH)
reverseHeading = IRobot.RIGHT;
else if (robot.getHeading() == IRobot.EAST)
reverseHeading = IRobot.AHEAD;
else if (robot.getHeading() == IRobot.SOUTH)
reverseHeading = IRobot.LEFT;
else
reverseHeading = IRobot.BEHIND;
break;
}
return reverseHeading;
}
}
class Junction {
int x;
int y;
int arrived;
public Junction(int xcoord, int ycoord, int course) {
x = xcoord;
y = ycoord;
arrived = course;
}
}
class Square {
int x;
int y;
public Square(int cordx, int cordy){
x = cordx;
y = cordy;
}
}
IntStream.range(0, al1.length)
.filter(index -> al2.contains(al1.get(index)))
.forEach(index -> al3.remove(index));
Slightly more complex than this if removing elements from al3 shifts them left but in that case just reverse the stream before the .filter- then it will delete from the end. The easiest way to do that is:
.map(index -> al1.length - index - 1)
Without Streams the equivalent would be
for (int i = 0; i < al1.length; i++) {
if (al2.contains(al1.get(i))) {
al3.remove(i);
}
}
Similarly, if you need to delete from the right then the for loop would need to count down rather than up.
Without further details on arraylist structure it's hard to give any more hints.

How to obscure Scanner input text? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Hide input on command line
I'm making a password security checker program and my question is odd in that my program runs just fine. What I'm wondering is whether there is any way of making text entered to the console appear as it would in a password field. i.e the word entered will appear as "****" BEFORE the user presses the return key.
I am aware that JFrame has a JPasswordField method but I don't think that helps me when in just using Scanner.
Here is my code:
import java.util.Scanner;
public class SecurityCheckerMain {
static String enteredPassword;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter your password: ");
enteredPassword = input.nextLine();
Checker tc = new Checker(enteredPassword);
tc.checkSecurity();
}
}
public class Checker {
//number of chars : the Higher the Better("password must be greater than 8 chars"){done}
//combination of uppercase and lowercase{done}
//contains numbers{done}
//non repeated characters (every char is different ascii char){done}
//is not a consecutive password ie 123456789 or 987654321{done}
//is not blank ("[space]"){done}
int pLength;
final int MAX_STRENGTH = 10;
int pStrength = 0;
String pass;
public Checker(String pwd){
pass = pwd;
pLength = pwd.length();
}
public void checkSecurity(){
if(pass.isEmpty()){
System.out.println("Password Field is Empty! Password is Very Insecure.");
}
if(pLength >= 8){
pStrength++;
if(pLength >= 12){
pStrength++;
if(pLength >= 16){
pStrength++;
}
}
}
if(hasUpperCase(pass) && hasLowerCase(pass)){
pStrength+=2;
}
if(containsNumbers(pass)){
pStrength+=2;
}
if(hasNoRepeats(pass)){
pStrength+=2;
}
if(!containsConsecutiveNums(pass)){
pStrength++;
}
System.out.println("Your password strength is rated at " + pStrength +"/" + MAX_STRENGTH);
}
//Component Methods
public boolean hasUpperCase(String str){
for(int i = 0; i<pLength; i++){
if(Character.isUpperCase(str.charAt(i))){
return true;
}
}
return false;
}
public boolean hasLowerCase(String str){
for(int i = 0; i<pLength; i++){
if(Character.isUpperCase(str.charAt(i))){
return true;
}
}
return false;
}
public boolean containsNumbers(String str){
for(int i = 0; i<pLength; i++){
if(Character.isDigit(str.charAt(i))){
return true;
}
}
return false;
}
public boolean hasNoRepeats(String str){
for(int i = 0; i<pLength; i++)
if(containsChar(str, str.charAt(i))){
return false;
}
return true;
}
public boolean containsChar(String s, char search) {
if (s.length() == 0)
return false;
else
return s.charAt(0) == search || containsChar(s.substring(1), search);
}
public boolean containsConsecutiveNums(String str){
for(int i = 0; i<pLength; i++){
if(Character.isDigit(str.charAt(i))){
if(str.charAt(i)-1 == str.charAt(i-1) || str.charAt(i)+1 == str.charAt(i+1)){
return true;
}
}
}
return false;
}
}
You can use Console.readPassword instead.
readPassword(String fmt, Object... args)
Provides a formatted prompt, then reads a password or passphrase from
the console with echoing disabled
public class SecurityCheckerMain {
static String enteredPassword;
public static void main(String[] args) {
Console console = System.console();
enteredPassword =
new String(console.readPassword("Please enter your password: "));
Checker tc = new Checker(enteredPassword);
tc.checkSecurity();
}

Categories