How to make program re-run without pressing the run button - java

I am trying to make a program that tests whether or not a password is valid or invalid. After the password is submitted, I would like to give the user a choice to re-run the program(by responding 'y'). Everything works in my code, except when y is pressed at the end, the program stops instead of starting over.
Any help would be greatly appreciated.
import java.util.Scanner;
import java.lang.*;
public class PasswordTest1
{
//Program main method
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String again = "y";
//Promt user to enter input
System.out.print("Enter a password: ");
String password = scan.nextLine();
//If-else to print whether the password is valid
if (checkPassword(password))
{
System.out.println("Valid Password");
System.out.println("Re-run Program (y/n)? ");
again = scan.next();
} else {
System.out.println("Invalid Password");
System.out.println("Re-run Program (y/n)? ");
again = scan.next();
}
}
//Program new method
public static boolean checkPassword(String password) {
String again = "y";
while((again == "Y") || (again == "y")){
boolean checkPassword = true;
{
//Make sure password is at least 7 digits
if (password.length() < 8) {
checkPassword = false;
}
else {
//A password has at least 1 digit
int numberOfDigit = 0;
for (int i = 0; i < password.length(); i++) {
if (isDigit(password.charAt(i))) {
if(isDigit(password.charAt(i))){
numberOfDigit++;
}
}
}
if (numberOfDigit < 1) {
checkPassword = false;
}
//Check for lower case
int numberOfLowerCase = 0;
for (int i = 0; i < password.length(); i++) {
if (isLowerCase(password.charAt(i))) {
if(isLowerCase(password.charAt(i))){
numberOfLowerCase++;
}
}
}
if (numberOfLowerCase < 1) {
checkPassword = false;
}
//Check for upper case
int numberOfUpperCase = 0;
for (int i = 0; i < password.length(); i++) {
if (isUpperCase(password.charAt(i))) {
if(isUpperCase(password.charAt(i))){
numberOfUpperCase++;
}
}
}
if (numberOfUpperCase < 1) {
checkPassword = false;
}
//Check for Special Characters
int numberOfSpecialCharacters = 0;
String specialCharactersString = "!##$%^&*()'+,-./:;<=>?[]_{}|";
for (int i = 0; i < password.length(); i++) {
char ch = password.charAt(i);
if(specialCharactersString.contains(Character.toString(ch))){
numberOfSpecialCharacters++;
}
}
if (numberOfSpecialCharacters < 1) {
checkPassword = false;
}
}
}
return checkPassword;
}
return true;
}
public static boolean isDigit(char ch) {
return (ch <= '9' && ch >= '0');
}
public static boolean isLowerCase (char ch) {
return (ch <= 'z' && ch >= 'a');
}
public static boolean isUpperCase (char ch) {
return (ch <= 'Z' && ch >= 'A');
}
}

I was able to get your code repeat as long as the 'n' key is not pressed. Right now if any key is pressed other than 'n', it will continue.
One problem was that your while loop needs to be inside of your main. The way it is setup, as soon as the checkPassword returns, there is no way for the program to repeat. Asking for y/n had no way to recall the function. You also had an issue with your string comparison, as #PM 77-1 mentioned in the comments. I would recommend keeping the curly brackets spaced out so it is easier to read, you had a pair of brackets that served no purpose.
import java.util.Scanner;
import java.lang.*;
public class PasswordTest1
{
//Program main method
public static void main(String[] args)
{
String again;
String n = "n";
while(true)
{
//Prompt user to enter input
Scanner scan = new Scanner(System.in);
System.out.println("\nEnter a password: ");
String password = scan.nextLine();
//If-else to print whether the password is valid
if (checkPassword(password))
{
System.out.println("\nValid Password");
System.out.println("Re-run Program (y/n)? ");
again = scan.next();
}
else
{
System.out.println("\nInvalid Password");
System.out.println("Re-run Program (y/n)? ");
again = scan.next();
}
if(again.equals(n))
{
break;
}
}
}
//Program new method
public static boolean checkPassword(String password)
{
boolean checkPassword = true;
//Make sure password is at least 7 digits
if (password.length() < 8)
{
checkPassword = false;
}
else
{
//A password has at least 1 digit
int numberOfDigit = 0;
for (int i = 0; i < password.length(); i++)
{
if (isDigit(password.charAt(i)))
{
if(isDigit(password.charAt(i)))
{
numberOfDigit++;
}
}
}
if (numberOfDigit < 1)
{
checkPassword = false;
}
//Check for lower case
int numberOfLowerCase = 0;
for (int i = 0; i < password.length(); i++)
{
if (isLowerCase(password.charAt(i)))
{
if(isLowerCase(password.charAt(i)))
{
numberOfLowerCase++;
}
}
}
if (numberOfLowerCase < 1)
{
checkPassword = false;
}
//Check for upper case
int numberOfUpperCase = 0;
for (int i = 0; i < password.length(); i++)
{
if (isUpperCase(password.charAt(i)))
{
if(isUpperCase(password.charAt(i)))
{
numberOfUpperCase++;
}
}
}
if (numberOfUpperCase < 1)
{
checkPassword = false;
}
//Check for Special Characters
int numberOfSpecialCharacters = 0;
String specialCharactersString = "!##$%^&*()'+,-./:;<=>?[]_{}|";
for (int i = 0; i < password.length(); i++)
{
char ch = password.charAt(i);
if(specialCharactersString.contains(Character.toString(ch)))
{
numberOfSpecialCharacters++;
}
}
if (numberOfSpecialCharacters < 1)
{
checkPassword = false;
}
}
return checkPassword;
}
public static boolean isDigit(char ch)
{
return (ch <= '9' && ch >= '0');
}
public static boolean isLowerCase (char ch)
{
return (ch <= 'z' && ch >= 'a');
}
public static boolean isUpperCase (char ch)
{
return (ch <= 'Z' && ch >= 'A');
}
}

Related

string length, number of capitals, and number of numbers in a string

I want to check if a string has 8 or more characters, and if it has 1 capital letter and 1 number.
This is my code:
import java.util.Scanner;
public class PasswordTest
{
public static void main(String[] args)
{
Scanner keyb = new Scanner(System.in);
System.out.printf("Enter a password to be checked: \n");
String passwordInput = keyb.next();
int numberCharaters = passwordInput.length();
int numberCount = 1;
for (int i = 1; i <= numberCharaters; i++)
{
for(char c = '0'; c <= '9'; c++)
{
if (passwordInput.charAt(i) == c)
{
numberCount++;
}
}
}
int numberNumbers = numberCount - 1;
int captialCount = 1;
for (int i = 1; i <= numberCharaters; i++)
{
for(char c = 'A'; c <= 'Z'; c++)
{
if (passwordInput.charAt(i) == c)
{
captialCount++;
}
}
}
int numberCaptials = captialCount - 1;
if (numberCharaters >= 8 && numberNumbers >= 1 && numberCaptials >= 1)
{
String strongEnough = "Password is strong enough.";
System.out.println(strongEnough);
}
else
{
String strongEnough = "Password is not strong enough.";
System.out.println(strongEnough);
}
}
}
and this is the error message I'm getting
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
at java.lang.String.charAt(String.java:658)
at passwordtest.main(passwordtest.java:23)
My input was: Test1
What am I doing wrong? I've been trying to figure out where the java.lang.StringIndexOutOfBoundsException: comes from.
Your program has some mistakes.
You should have initialized numberCount to 0 to avoid having to subtract later, and avoid having to create another variable. Also the error you're getting is because of the <=, since there is no string element = to the length of the string, i.e index is from 0 to length - 1.
int numberCount = 0;
for (int i = 0; i < numberCharaters; i++)
{
for(char c = '0'; c <= '9'; c++)
{
if (passwordInput.charAt(i) == c)
{
numberCount++;
}
}
}
Then, for the capital count you made the same mistake, I would also take into account the advice in the comments to improve the loops.
You are making a minor mistake.
Length = Actual number of elements(characters).
Index = starts from 0 and ends at length-1.
Your code should be look like this:
import java.util.Scanner;
public class PasswordTest
{
public static void main(String[] args)
{
Scanner keyb = new Scanner(System.in);
System.out.printf("Enter a password to be checked: \n");
String passwordInput = keyb.next();
int numberCharaters = passwordInput.length();
int numberCount = 0;
for (int i = 0; i <= numberCharaters-1; i++)
{
for(char c = '0'; c <= '9'; c++)
{
if (passwordInput.charAt(i) == c)
{
numberCount++;
}
}
}
int numberNumbers = numberCount - 0;
int captialCount = 0;
for (int i = 1; i <= numberCharaters; i++)
{
for(char c = 'A'; c <= 'Z'; c++)
{
if (passwordInput.charAt(i) == c)
{
captialCount++;
}
}
}
int numberCaptials = captialCount - 0;
if (numberCharaters >= 8 && numberNumbers >= 1 &&
numberCaptials >= 1)
{
String strongEnough = "Password is strong enough.";
System.out.println(strongEnough);
}
else
{
String strongEnough = "Password is not strong enough.";
System.out.println(strongEnough);
}
}
}
import java.util.*;
public class password
{
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.print("enter the password : ");
String s=sc.nextLine();
int l=s.length();
int k=0,k1=0;
if(l>=8)
{
for(int i=0;i<l;i++)
{
if(Character.isLetter(s.charAt(i)))
{
if(Character.isUpperCase(s.charAt(i)))
{
k++;
}
}
else
{
if(Character.isDigit(s.charAt(i)))
{
k1++;
}
}
}
if(k>0&&k1>0)
{
System.out.println("Password is strong enough");
}
else
{
System.out.println("Password shoud contain atleast capital letter and one number");
}
}
else
{
System.out.println("Password shoud contain atleast capital letter,one number and shoud have length of 8 or more");
}
}
}

Stop at the first occurence of a character

I want to only remove 'a' in " brealdeke "
This program works, it prints " breldeke " but if I were to put
" brealdeake" with 2 'a' in this string, it goes berserk and prints : breldeakebrealdeke How to fix it ? Thanks
I really want it to look this this :
class Example {
public static String suppression(char c, String s) {
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == c) {
int position = i;
for (int a = 0; a < position; a++) {
System.out.print(s.charAt(a));
}
for (int b = position + 1; b < s.length(); b++) {
System.out.print(s.charAt(b));
}
}
}
return "";
}
public static void main(String[] args) {
// prints "breldeke"
System.out.println(suppression('a', "brealdeke"));
// prints "breldeakebrealdeke"
System.out.print(suppression('a', "brealdeake"));
}
}
You could try :
"banana".replaceFirst("a", "");
This returns bnana
EDIT: Hopefully, this doesn't include anything you haven't been taught yet
public static void main(String[] args) {
String word = "banana";
String strippedWord = "";
boolean found = false;
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) == 'a' && !found) found = !found;
else strippedWord += word.charAt(i);
}
System.out.println(strippedWord);
}
This prints bnana
EDIT2 : You said you wanted it in a function, the same applies :
public static String suppression(char c, String word) {
String strippedWord = "";
boolean charRemoved = false; // This is a boolean variable used to know when the char was skipped!
for (int i = 0; i < word.length(); i++) {
// If the current letter is for example 'a' and we haven't yet skipped the char, skip this char we're at
if (word.charAt(i) == c && charRemoved == false) charRemoved = true;
else strippedWord += word.charAt(i);
}
return strippedWord;
}
public static void main(String[] args) {
// prints "breldeke"
System.out.println(suppression('a', "brealdeke"));
// prints "breldeake"
System.out.print(suppression('a', "brealdeake"));
}
Additional variables OK?
I'd do it like this personally:
public static String removeFirstLetter(string s, char c)
{
String word = "";
Bool foundChar = false;
for ( int i = 0; i<s.length();i++) {
if (s.charAt(i).toLower() != c)
{
word += s.char(i);
}
else
{
if (foundChar == false){
foundChar = true;
}
else
{
word += s.char(i);
}
}
}
}
System.out.print(word);

What am I doing wrong with my Java code for input validation? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
So this program is supposed to be a game where a user enters a phrase and another user tries to guess the phrase. I'm having a problem with buying a vowel, however. No matter what I enter at line 41 (, it just goes past the loop. I made the validAnswer(String answer) method in the hopes that it would be useful in the loop but it doesn't look to be much help. I know there is a small thing I'm missing but I'm too new to Java to recognize it yet. What am I doing wrong?
I apologize for the long amount of code.
import java.util.Scanner;
public class PhraseGame {
public static void main(String[] args) {
// Initialize scanner
Scanner stdIn = new Scanner(System.in);
// Initialize variables
String sPhrase;
String answer = "f";
char cGuess = 0;
char vGuess = 0;
int count = 0;
int vowels = 0;
int consonants = 0;
int spaces = 0;
boolean gameOver = false;
boolean correct = true;
// Start the "fun" game
System.out.print("Please enter the phrase to guess at: ");
sPhrase = stdIn.nextLine();
// Create the temporary Array
char [] tmpArr = new char[sPhrase.length()];
for (int i = 0; i < sPhrase.length(); i++) {
tmpArr[i] = sPhrase.charAt(i);
}
// Gets the number of spaces
spaces = initTemplateArray(sPhrase, tmpArr, spaces);
printTemplateArray(tmpArr);
while (!(endGame(gameOver, spaces, consonants, vowels, sPhrase))) {
cGuess = getConsonant(stdIn, cGuess);
do {
System.out.print("\nWould you like to buy a vowel?: ");
answer = stdIn.next();
if (answer == "y") {
getVowel(stdIn, vGuess); }
else if (answer == "n"){
break;
}
} while (!validAnswer(answer));
// Updates the array and prints it
updateTemplateArray(tmpArr, sPhrase, cGuess, vGuess, count, vowels, consonants);
printTemplateArray(tmpArr);
// Checks if the game is over
endGame(gameOver, spaces, consonants, vowels, sPhrase);
}
}
// returns the number of space characters used in the common phrase
public static int initTemplateArray(String sPhrase, char [] tmpArr, int spaces) {
for (int i = 0; i < sPhrase.length(); i++) {
if (tmpArr[i] != ' ') {
tmpArr[i] = '?';
} else {
tmpArr[i] = ' ';
spaces++;
}
}
return spaces;
}
public static void printTemplateArray(char [] tmpArr) {
System.out.println("\nCommon Phrase");
System.out.println("-------------");
for (int i = 0; i < tmpArr.length; i++) {
System.out.print(tmpArr[i]);
}
}
public static boolean isVowel(char c) {
return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
}
public static char getConsonant(Scanner stdIn, char cGuess) {
do {
System.out.println("\nEnter a lowercase consonant guess: ");
cGuess = stdIn.next().charAt(0);
} while (isVowel(cGuess));
return cGuess;
}
public static char getVowel(Scanner stdIn, char vGuess) {
do {
System.out.println("\nEnter a lowercase vowel guess: ");
vGuess = stdIn.next().charAt(0);
} while (!(isVowel(vGuess)));
return vGuess;
}
public static int updateTemplateArray(char [] tmpArr, String sPhrase, char cGuess, char vGuess, int count, int vowels, int consonants) {
for (int i = 0; i < sPhrase.length(); i++) {
if (cGuess == sPhrase.charAt(i)) {
tmpArr[i] = sPhrase.charAt(i);
count++;
consonants++;
}
if (vGuess == sPhrase.charAt(i)) {
tmpArr[i] = sPhrase.charAt(i);
count++;
vowels++;
}
}
return count & vowels & consonants;
}
public static boolean endGame(boolean gameOver, int spaces, int consonants, int vowels, String sPhrase) {
int total = spaces + consonants + vowels;
if (total == sPhrase.length()) {
return true;
}
else {
return false;
}
}
public static boolean validAnswer(String answer) {
if (answer.equalsIgnoreCase("y")) {
return true;
}
else if (answer.equalsIgnoreCase("n")) {
return true;
}
else {
return false;
}
}
}
You need to check for null.
public static boolean validAnswer(String answer) {
if (answer!=null && (answer.equalsIgnoreCase("y") || answer.equalsIgnoreCase("n"))) {
return true;
}
return false;
}
or an other unconventional way.
public static boolean validAnswer(String answer) {
if ("y".equalsIgnoreCase(answer) || "n".equalsIgnoreCase(answer))) {
return true;
}
return false;
}
You need to fix
do {
System.out.print("\nWould you like to buy a vowel?: ");
answer = stdIn.nextLine();
if ("y".equalsIgnoreCase(answer)) {
getVowel(stdIn, vGuess);
} else if ("n".equalsIgnoreCase(answer)){
break;
}
} while (!validAnswer(answer));

Java, Program to check if a string is a palindrome

I have a Java Assignment where I have to prompt for a line input, check if its a palindrome and then say if the palindrome is made of all text, all numbers, or mixed. I haven't added the part where I check what kind of palindrome it is yet, but I need help with the code to check if it's a palindrome. The code I posted below recognizes everything as a palindrome even if it isn't. This is basic Java so I'm limited to what I used below.
import java.util.Scanner;
public class Project4{
public static void main (String [] args)
{
String line = getInputLine();
while (!isEmptyLine (line))
{
if (isPalindrome (line))
System.out.println ("\"" + line + "\" is a palindrome.");
else
System.out.println ("\"" + line + "\" is not a palindrome");
line = getInputLine();
}
System.out.println ("End of program");
}
public static String getInputLine ( )
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a line of input: ");
String inputline = in.nextLine();
return inputline;
}
public static boolean isEmptyLine(String str)
{
boolean truefalse;
if(str.length()==0)
truefalse = true;
else
truefalse = false;
return truefalse;
}
public static boolean isPalindrome(String str)
{
int left = 0;
int right = str.length();
boolean okay = true;
char ch1; char ch2;
while(okay && left<right)
{
ch1 = str.charAt(left);
if(!Character.isDigit(ch1)||!Character.isLetter(ch1))
left++;
else
{
ch2 = str.charAt(right);
if(!Character.isDigit(ch2)||!Character.isLetter(ch2))
right--;
else
{
ch1 = Character.toUpperCase(ch1);
ch2 = Character.toUpperCase(ch2);
if(ch1==ch2)
{
left++;
right--;
}
else
okay = false;
}
}
}
return okay;
}
}
You need to do logical AND of the 2 checks instead of OR -
if(!Character.isDigit(ch1) && !Character.isLetter(ch1))
Use a method like the following:
boolean isPalindrome (String input) {
int strLength = input.length;
for (int i=0; i < input.length/2; ++i) {
if (input.charAt(i) != input.charAt(strLength-i)) {
return false;
}
}
return true;
}
A late answer although it might help some in the future. The method posted below doesn't use any of StringBuilder functions.
public boolean isPalindrome(String value) {
boolean isPalindrome = true;
for (int i = 0 , j = value.length() - 1 ; i < j ; i ++ , j --) {
if (value.charAt(i) != value.charAt(j)) {
isPalindrome = false;
}
}
return isPalindrome;
}

Can't proceed with main method after do while loop

I am new to Java and working on simple task - TicTacToe console game. Today I've faced a problem that I can't proceed with the main method after do while loop. The project has two classes - Main and Field. Field is responsive for all game field updates. I'm calling Field methods in do while loop of the main method but when the result is on the loop has to be finished and the main method has to go on(it should ask if the user wants to play again). Unfortunately the programm stops after do while loop.
Here is my code:
import java.io.IOException;
import java.util.Scanner;
public class Main {
private static char playerSym, compSym;
private static int Sym;
public static int playerChoice;
public static boolean result;
public static void main(String args[]) throws IOException {
Field field = new Field();
// start of the game
System.out.println("Let`s play");
System.out.println("Choose your symbol please");
System.out.println("0='O', 1='X'");
Scanner sc = new Scanner(System.in);
Sym = sc.nextInt();
while (Sym != 0 & Sym != 1) {
System.out
.println("The symbol you entered is incorrect, please repeat");
System.out.println("0='O', 1='X'");
Sym = sc.nextInt();
}
// setting player character
if (Sym == 1) {
playerSym = 'X';
compSym = 'O';
} else if (Sym == 0) {
playerSym = 'O';
compSym = 'Х';
}
System.out.println("There is a game field");
System.out.println("Please choose the cell number you`d like to fill with " + playerSym);
field.firstShowFields();
do {
playerChoice = (Integer) sc.nextInt();
field.updateFields(playerChoice, playerSym);
field.showFields(field.fields);
} while (result==false);
System.out.println("Want to play once more? Y-Yes, N-No");
char answer = (char) System.in.read();
switch (answer) {
case 'Y':
System.out.println("Restarting the game");
break;
case 'N':
System.out.println("Thank you! Bye-Bye!");
break;
default:
break;
}
}
}
public class Field {
public static final int FIELD_SIZE = 3;
// private static final char DEFAULT_CHAR=' ';
public char[][] fields;
public boolean result = true;
public char playerSym;
public Field() {
fields = new char[FIELD_SIZE][FIELD_SIZE];
}
public void firstShowFields() {
int cellValue = 1;
for (int i = 0; i < FIELD_SIZE; i++) {
for (int j = 0; j < FIELD_SIZE; j++) {
System.out.print("[" + cellValue + "]");
cellValue++;
}
System.out.println();
}
}
public char[][] updateFields(int choice, char sym) {
playerSym = sym;
int cellValue = 1;
int playerChoice = choice;
do {
for (int i = 0; i < FIELD_SIZE; i++) {
for (int j = 0; j < FIELD_SIZE; j++) {
if (playerChoice == cellValue) {
fields[i][j] = (char) playerSym;
} else if (fields[i][j] == (char) playerSym) {
fields[i][j] = (char) playerSym;
} else {
fields[i][j] = (char) ('0' + cellValue);
}
cellValue++;
}
}
this.checkWin(fields, playerSym);
return fields;
} while (this.checkWin(fields, playerSym) == false);
}
public void showFields(char[][] fields) {
this.fields = fields;
for (int i = 0; i < FIELD_SIZE; i++) {
for (int j = 0; j < FIELD_SIZE; j++) {
System.out.print("[" + fields[i][j] + "]");
}
System.out.println();
}
}
public boolean checkWin(char[][] field, char playerSym) {
char[][] checkField = field;
this.playerSym = playerSym;
// checkline
if (((checkField[0][0] == checkField[0][1]) && (checkField[0][1] == checkField[0][2]))
|| ((checkField[1][0] == checkField[1][1]) && (checkField[1][1] == checkField[1][2]))
|| ((checkField[2][0] == checkField[2][1]) && (checkField[2][1] == checkField[2][2]))) {
System.out.println("The game is over. The winner is player " + playerSym);
return true;
}
// checkraw
else if (((checkField[0][0] == checkField[1][0]) && (checkField[1][0] == checkField[2][0]))
|| ((checkField[0][1] == checkField[1][1]) && (checkField[1][1] == checkField[2][1]))
|| ((checkField[0][2] == checkField[1][2]) && (checkField[1][2] == checkField[2][2]))) {
System.out.println("The game is over. The winner is player " + playerSym);
return result = true;
} // checkdiagonal
else if (((checkField[0][0] == checkField[1][1]) && (checkField[1][1] == checkField[2][2]))
|| ((checkField[0][2] == checkField[1][1]) && (checkField[1][1] == checkField[2][0]))) {
System.out.println("The game is over. The winner is player " + playerSym);
return result = true;
}
return false;
}
}
Here is an infinite loop:
do {
playerChoice = (Integer) sc.nextInt();
field.updateFields(playerChoice, playerSym);
field.showFields(field.fields);
} while (result==false);
result is never updated so the while (result==false); will never fail as long as it was true the first time. You may try modifying it like below:
do {
playerChoice = (Integer) sc.nextInt();
field.updateFields(playerChoice, playerSym);
field.showFields(field.fields);
result = field.checkWin(field.fields, playerSym);
} while (result==false);
Also, it is not a good practice to pass fields that are already attached to the instance to instance methods. You can remove the parameter char[][] field from the checkWin method and simply have it operate on the instance variable fields. But that's not the cause of your loop issue.
As user506 points out the only reason why it won't progress past the loop is because the boolean result is never set to true.
Why do you have 2 classes to separate the main method?

Categories