Does a method used in main method need its own class? - java

I am writing a code that checks password entries. The main method checks a secondary method and outputs a line depending on whether it's true or false. My problem is when I compile it gives expected class error for the second method, but if I try to use the same class as my main it gives duplicate class error. I didn't think I needed a second class. Anyone care to help me out?
import java.util.Scanner;
public class CheckPassword {
public static void main(String[] args) {
scanner input = new Scanner(System.in);
System.out.println("Enter a password");
password = input.nextLine();
if (check(password)) {
System.out.println("Valid Password");
}
else{
System.out.println("Invalid Password");
}
}
}
public class CheckPassword {
public static boolean check(String password) {
boolean check = true;
if(password.length() < 8) {
check = false;
}
int num = 0;
for(int x = 0; x < password.length(); x++) {
if(isLetter(password.charAt(x)) || isDigit(password.charAt(x))){
if(isDigit(password.charAt(x))){
num++;
if (num >=2){
check = true;
}
else{
check = false;
}
}
}
}
}
}

No need another class, but needed to static import isDigit and isLetter. I fixed your code:
import java.util.Scanner;
import static java.lang.Character.isDigit;
import static java.lang.Character.isLetter;
public class CheckPassword {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a password");
String password = input.nextLine();
if (check(password)) {
System.out.println("Valid Password");
}
else{
System.out.println("Invalid Password");
}
}
public static boolean check(String password) {
boolean check = true;
if(password.length() < 8) {
check = false;
}
int num = 0;
for(int x = 0; x < password.length(); x++) {
if(isLetter(password.charAt(x)) || isDigit(password.charAt(x))){
if(isDigit(password.charAt(x))){
num++;
if (num >=2){
check = true;
}
else{
check = false;
}
}
}
}
return check;
}
}

Related

The user must enter a string that is greater than 6 characters long

How can I code this using subroutines in java with a loop so if they don't get it right it keeps repeating till they do. This is all i have so far. The user must enter a string that is greater than 6 characters long.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package containsmethod;
import java.util.*;
import java.lang.String;
import java.lang.Character;
import java.util.Scanner;
public class ContainsMethod {
public static boolean isValid(String password) {
if (password.length() < 6) {
return false;
} else {
char c;
for (int i = 0; i < password.length() -1; i ++) {
c = password.charAt(i);
if (!Character.isLetterOrDigit(c)) {
return false;
} else if (Character.isDigit(c)) {
return false;
}
}
}
return false;
}
public static void main (String [] args) {
Scanner input = new Scanner (System.in);
{
System.out.print ("Please enter a string that is greater than 6 characters long. ");
String password = input.next();
if (isValid(password)) {
System.out.println ("That is a valid string onto stage 2.");
}
else
{
System.out.println ("That is a invalid string. Try again.");
}
}
First of all, your isValid function never returns true, even the case that user enters a password that is greater than 6 characters. So you should update your method like that:
public static boolean isValid(String password) {
if (password.length() < 6) {
return false;
} else {
char c;
for (int i = 0; i < password.length() - 1; i++) {
c = password.charAt(i);
if (!Character.isLetterOrDigit(c)) {
return false;
} else if (Character.isDigit(c)) {
return false;
}
}
}
return true;
}
Then, you can take the user input in a do-while loop. So if the password is invalid it will keep asking. Here is your updated main method:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
{
String password;
do {
System.out.print("Please enter a string that is greater than 6 characters long. ");
password = input.next();
if (isValid(password)) {
System.out.println("That is a valid string onto stage 2.");
} else {
System.out.println("That is a invalid string. Try again.");
}
}while (!isValid(password));
}
}

Need help confirming password after validation

The main program should ask for a password that is 8 characters, 1 upper, 1 lower & 1 digit. Once passed requirements it should ask the user to re-enter the password and check that the two passwords match. I need help adding that section to my code. Currently, the code compiles with no problem.
import java.util.Scanner;
public class PassChecker2 {
public static void main (String [] args) {
Scanner input = new Scanner(System.in);
String inputPassword;
System.out.println(" Please enter your Password:");
inputPassword = input.next();
System.out.println(checkerPass(inputPassword));
System.out.println("");
//main(args);
}
public static boolean lenthgCk (String password) {
if (password.length() > 7) {
if(checkerPass(password)) {
return true;
}
}
else {
System.out.println("Password must be at least 8 characters long.");
return false;
}
return true;
}
public static boolean checkerPass (String password) {
boolean hasUpperCase = false;
boolean hasLowerCase = false;
boolean hasDigit = false;
char c;
for (int i = 0; i < password.length(); i++) {
c = password.charAt(i);
if(Character.isUpperCase(c)) {
hasUpperCase = true;
}
else if(Character.isLowerCase(c)) {
hasLowerCase = true;
}
else if(Character.isDigit(c)) {
hasDigit = true;
}
if(hasUpperCase && hasLowerCase && hasDigit) {
return true;
}
else {
System.out.println("Password is invalid must meet all requirements.");
return false;
}
}
return true;
}
}
Just input another string the same way you inputted the original password and check that they are both equal:
System.out.println(" Please confirm your Password:");
Stirng confirmPassword = input.next();
if (!confirmPassword.equals(inputPassword)) {
System.out.println("Passwords do not match");
// And possibly exit the program here?
}

Validating a Password

I want to check whether a password has at least 8 characters and consist of numbers and letters only.
The problem here is even though I entered a valid password it says 'Invalid' all the time. Here's the code. Thanks.
public static void main(String[] args)
{
String pw;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a password: ");
pw = sc.next();
if(isValid(pw)==true)
{
System.out.println("Valid Password");
}
else
{
System.out.println("Invalid Password");
}
}
public static boolean isValid(String pw)
{
if(pw.length()<8)
{
return false;
}
else
{
for(int x=0; x<pw.length(); x++)
{
return Character.isLetterOrDigit(pw.charAt(x));
}
}
return true;
}
}
Logic of your code is correct except return statement in 'for' loop in isValid method. Here is edited code:
public static void main(String[] args)
{
String pw;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a password: ");
pw = sc.next();
if(isValid(pw))
{
System.out.println("Valid Password");
}
else
{
System.out.println("Invalid Password");
}
}
public static boolean isValid(String pw)
{
if(pw.length()<8)
{
return false;
}
else
{
for(int x=0; x<pw.length(); x++)
{
if(!Character.isLetterOrDigit(pw.charAt(x)))
return false;
}
}
return true;
}
Note that your code does not print 'invalid' if your password is valid but could print 'valid' for some invalid passwords such as a########
You're returning the result within the first iteration of the loop, rather you should make a flag variable and return the result at the end of the loop or you could invert the if condition within the loop and return false if that evaluates to true and if it does not then return true at the end of the loop.
public static boolean isValid(String password){
if(password.length() < 8)
return false;
for(int x = 0; x < password.length(); x++)
if(!Character.isLetterOrDigit(password.charAt(x)))
return false;
return true;
}

Loop not ending when it's supposed to?

I've been tasked to make a secret word guessing game and it is supposed to be game over and user is asked if they want to play again if the number of guesses for the character reaches 5.
I thought my incrementor is correct but perhaps not...
Here's the class:
public class SecretWord {
private String secretWord;
private String hintWord ;
private int numberOfTurns;
//Default Constructors
public SecretWord()
{
hintWord = "";
secretWord = "juice";
for (int i = 0; i < secretWord.length(); i++)
{
hintWord+="*";
}
this.numberOfTurns = 0;
}
//Accessors
public String getSecretWord()
{
return this.secretWord;
}
public String getHintWord()
{
return this.hintWord;
}
public int getNumberOfTurns()
{
return this.numberOfTurns;
}
//Mutators
public void setSecretWord ()
{
this.secretWord = "juice";
}
public void setHintWord ()
{
//Setting the hint word which sets the asterisks when you guess something right
char[] correctLetters = new char[secretWord.length()];
for (int i = 0; i<secretWord.length();i++)
{
hintWord+="*";
correctLetters[i] += '*';
}
}
public void setNumberOfTurns (int i)
{
this.numberOfTurns = 5;
}
//Methods
public void guessLetter(char guess)
{
String tempHintWord="";
for (int i = 0; i < secretWord.length(); i++)
{
if (secretWord.charAt(i) == guess)
{
tempHintWord += guess;
}
else
{
tempHintWord += hintWord.charAt(i);
}
}
hintWord = tempHintWord;
}
Here's the driver with my loops:
public class SecretWordGame {
//Constant for number of tries
public static final int NUM_TRIES = 5;
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in);
//Starts game
boolean quit = false;
while (quit == false)
{
System.out.println("Welcome to the word guessing game! You have " +
+NUM_TRIES+" tries to guess the secret word!");
SecretWord myWord = new SecretWord();
System.out.println("The current hint is \n"+myWord.getHintWord());
while (myWord.getNumberOfTurns() <=NUM_TRIES)
{
System.out.println("Guess a lowercase letter");
//Gets the first letter of what is entered
char tempGuess = keyboard.nextLine().charAt(0);
//Updates the hint by calling guess letter method
myWord.guessLetter(tempGuess);
System.out.println(myWord.getHintWord());
System.out.println("Guess the secret word");
String myGuess = keyboard.nextLine();
//Checks correct guess
if (myGuess.equals(myWord.getSecretWord()))
{
System.out.println("You win!");
break;
}
else
{
System.out.println("Keep trying!");
}
myWord.setNumberOfTurns(myWord.getNumberOfTurns()+1);
}
//Prompts user to play again
System.out.println("Game over! Try again?");
String userInput = keyboard.nextLine();
if(userInput.equalsIgnoreCase("no"))
{
quit = true;
}
else
{
System.out.println("Let's go again!");
}
}
System.out.println("Goodbye!");
}
Maybe the while loop (myWord.getNumberOfTurns() <=NUM_TRIES) comparison is wrong? Or perhaps the getNumberOfTurns incrementor is in the wrong place? I'm unsure.
change
public void setNumberOfTurns (int i)
{
this.numberOfTurns = 5;
}
to
public void setNumberOfTurns (int i)
{
this.numberOfTurns = i;
}
otherwise it would be set to 5 when this code is called myWord.setNumberOfTurns(myWord.getNumberOfTurns()+1);

How to use do-while loop to check user input again?

I want to add a loop to my program so that when a user enters an incorrect name it goes back to the start of the program and asks them to enter their name again. I think I need a do-while loop but I am not sure how to implement it with the if statements and boolean already included. I want the user to be only have three entries and if they get it wrong three times then the program closes.
import java.util.Scanner;
public class Username
{
public static void main(String[] args)
{
{
Scanner kb = new Scanner(System.in);
// array containing usernames
String[] name = {"barry", "matty", "olly", "joey"}; // elements in array
System.out.println("Enter your name");
String name1 = kb.nextLine();
boolean b = true;
for (int i = 0; i < name.length; i++)
{
if (name[i].equals(name1))
{
System.out.println("you are verified you may use the lift");
b = false;
break;// to stop loop checking names
}
}
if (b)
{
System.out.println("Invalid entry 2 attempts remaining, try again");
}
}
You can use a condition in the while loop. Something along the lines of:
boolean b = false;
while(!b){
System.out.println("Enter your name");
String name1 = kb.nextLine();
for (int i = 0; i < name.length; i++) {
if (name[i].equals(name1)) {
b = true;
System.out.println("you are verified you may use the lift");
}else{
System.out.println("Invalid entry 2 attempts remaining, try again");
}
}
}
The loop will quit if the name condition is fulfilled and will loop around if it is not.
You can do it like this:
int count = 0;
point:
do {
System.out.println("Enter your name");
String name1 = kb.nextLine();
boolean b = true;
for (int i = 0; i < name.length; i++) {
if (name[i].equals(name1)) {
System.out.println("you are verified you may use the lift");
b = false;
break point;// to stop loop checking names
}
}
if (b) {
count++;
System.out.println("Invalid entry 2 attempts remaining, try again");
}
while(!b || count <=3)
Use the following approach. Good thing is that it is a clean and robust solution.
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class AccessPoint
{
private Scanner scanner;
private List<String> usernames;
public AccessPoint()
{
scanner = new Scanner(System.in);
usernames = Arrays.asList("Barry", "Matty", "Olly", "Joey");
if (tryAccessForTimes(3))
{
allowAccess();
}
else
{
denyAccess();
}
scanner.close();
}
public static void main(String[] args)
{
new AccessPoint();
}
private boolean tryAccessForTimes(int times)
{
boolean accessAllowed = false;
for (int tryIndex = 1; tryIndex <= times && !accessAllowed; tryIndex++)
{
String userInput = getUserName();
for (String userName : usernames)
{
if (userName.equals(userInput))
{
accessAllowed = true;
break;
}
}
if (!accessAllowed)
{
printNumberOfTriesLeft(times, tryIndex);
}
}
return accessAllowed;
}
private void printNumberOfTriesLeft(int times, int tryIndex)
{
int triesLeft = times - tryIndex;
if (triesLeft != 0)
{
System.out.println("You have " + triesLeft
+ (triesLeft == 1 ? " try" : " tries") + " left.");
}
}
private String getUserName()
{
System.out.print("Enter Username: ");
return scanner.nextLine();
}
private void allowAccess()
{
System.out.println("Access Granted. Allowed to use lift.");
}
private void denyAccess()
{
System.out.println("Access Denied.");
}
}
package com.loknath.lab;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class User1 {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
// array containing usernames
String[] name = {"zerr", "barry", "matty", "olly", "joey" }; // elements
String []temp=name;
Arrays.sort(temp);
while (true) {
System.out.println("Enter your name");
String name1 = kb.nextLine();
if (Arrays.binarySearch(temp,name1)>=0) {
System.out.println("you are verified you may use the lift");
break;
} else {
System.out.println("Not a verified user try again!");
}
}
System.out.println("Done");
}
}
output
Enter your name
loknath
Not a verified user try again!
Enter your name
chiku
Not a verified user try again!
Enter your name
zerr
you are verified you may use the lift
Done

Categories