JAVA- How to reinitialise the second statement in a for loop - java

My code takes the users input and checks it for certain characters. If a unwanted character is found the programme asks for user input again however if I were to type the special character at the end of the text eg 'hello#' and then when im asked for the input again I type 'hello' I get a 'String index out of range: 5' error. How could I reinitialize the max variable so that when the input length changes max variable in the for loop changes too.
I tried assigning the max variable again but there was no luck.
Scanner keyboard= new Scanner(System.in);
System.out.println("Please enter text to encrypt:");
String input = keyboard.nextLine();
String text = input.toUpperCase();
char letter;
int max = text.length();
for(int i =0; i<max;i++){
letter = text.charAt(i);
while(letter=='#'||letter=='\''||letter==';'||letter==':'||letter==','||letter=='<'||letter=='.'||letter=='>'||letter=='/'||letter=='?'||letter=='#'||letter=='~'||letter=='['||letter==']'||letter=='{'||letter=='}'||letter=='='||letter=='+'||letter=='-'||letter=='_'||letter==')'||letter=='('||letter=='*'||letter=='&'||letter=='^'||letter=='%'||letter=='$'||letter=='$'||letter=='£'||letter=='"'||letter=='!'||letter=='`'||letter=='¬'||letter=='\\'||letter=='|'){
System.out.println("Invalid Input\nPlease enter text to encrypt:");
input = keyboard.nextLine();
text = input.toUpperCase();
letter = text.charAt(i);
i=-1;
}
max=text.length();
}

You should take the user input and validate it. If the input is invalid, you request it again. One way of doing this is something like:
Scanner keyboard = new Scanner(System.in);
boolean ok;
do {
ok = true;
System.out.println( "Please enter text to encrypt:" );
String text = keyboard.nextLine().toUpperCase();
for ( char letter : text.toCharArray() ) {
if ( letter=='#' || letter=='\'' || letter==';' || letter==':' ||
letter==',' || letter=='<' || letter=='.' || letter=='>' ||
letter=='/' || letter=='?' || letter=='#' || letter=='~' ||
letter=='[' || letter==']' || letter=='{' || letter=='}' ||
letter=='=' || letter=='+' || letter=='-' || letter=='_' ||
letter==')' || letter=='(' || letter=='*' || letter=='&' ||
letter=='^' || letter=='%' || letter=='$' || letter=='$' ||
letter=='£' || letter=='"' || letter=='!' || letter=='`' ||
letter=='¬' || letter=='\\' || letter=='|' ) {
ok = false;
break;
}
}
if ( !ok ) {
System.out.println("Invalid Input");
}
} while ( !ok );
I'm assuming that you want a String with only alphanumerical characters. If it's true, it could be much simpler:
Scanner keyboard = new Scanner(System.in);
boolean ok;
do {
System.out.println( "Please enter text to encrypt:" );
String text = keyboard.nextLine().toUpperCase();
// does text contains only characters from A to Z and/or 0 to 9,
// one or more times (+)
ok = text.matches( "[A-Z0-9]+" );
if ( !ok ) {
System.out.println("Invalid Input");
}
} while ( !ok );

It appears you just want legal alphaNumeric words. \\w+ matches those so try this.
Scanner keyboard = new Scanner(System.in);
while(true) {
System.out.println("Please enter text to encrypt:");
String input = keyboard.nextLine();
if (input.matches("\\w+")) {
break;
}
System.out.println("Invalid input");
}

Related

How can I get the password to return back to password request if an invalid password is entered in Java?

I am trying to get the password to return and re-ask for the password if an invalid password is entered. And if a password is invalid 3 consecutive times, the system should terminate.
Is there an issue how I have structured the sequence of the lines of code? Please advise as I am rather new to Java.
public static void main(String []args){
final int MAX=10;
int invalidCount = 0;
final int MIN_Uppercase=1;
int uppercaseCounter=0;
int digitCounter=0;
int specialCounter=0;
System.out.println("Enter the password\n");
Scanner input = new Scanner(System.in);
String password = input.nextLine();
for (int i=0; i < password.length(); i++ ) {
char c = password.charAt(i);
if(Character.isDigit(c))
digitCounter++;
if(Character.isUpperCase(c))
uppercaseCounter++;
if(c == '!' || c == '#' || c == '#' || c == '$' || c == '%' || c == '^' || c == '&' || c == '*' || c == '(' || c == ')' || c == '-' || c == '_' || c == '=' || c == '+'){
specialCounter++;
}
}
if (password.length() >= MAX && uppercaseCounter >= 1 && specialCounter == 1 && (digitCounter == 2 || digitCounter == 3)) {
System.out.println("Valid Password");
}
else {
invalidCount++;
if(password.length() < MAX)
System.out.println("Enter atleast 10 characters");
if (uppercaseCounter < MIN_Uppercase)
System.out.println("Enter at least 1 uppercase character");
if(digitCounter != 2 && digitCounter != 3)
System.out.println("Enter either 2 or 3 digits only");
if(specialCounter != 1)
System.out.println("Password must contain 1 special character");
if (invalidCount == 3)
System.out.println("Maximum tries reached");
System.exit(invalidCount);
}
return;
}
You need to put this entire logic in a while loop that keeps tracks of invalidCount.
The other solution is to put the entire logic in a while loop which is always true and it breaks out of the loop in case correct password is entered.
Also, by seeing the if condition in your code, I would like to point out only the first println statement is inside the if part and not the second println statement.
if (invalidCount == 3)
System.out.println("Maximum tries reached");
System.exit(invalidCount);
but i think you wanted to put it something like this. such that when the count reaches 3, then it should terminate.
if (invalidCount == 3) {
System.out.println("Maximum tries reached");
System.exit(invalidCount);
}
Place the Password prompt into a while loop with a counter, for example:
Scanner userInput = new Scanner(System.in);
int maxPasswordAttempts = 3;
int passwordCounter = 0;
String password = "";
while (password.isEmpty()) {
passwordCounter++;
if (passwordCounter > maxPasswordAttempts) {
System.out.println("Maximum allowable password attempts (" + maxPasswordAttempts
+ ")has been\ncarried out! No longer accepting a passwords!");
System.exit(0);
}
System.out.print("Please enter a password (c to cancel): --> ");
password = userInput.nextLine().trim();
if (password.equalsIgnoreCase("c")) {
System.out.println("Password Entry - CANCELED!");
return;
}
/* Regex from the website:
https://mkyong.com/regular-expressions/how-to-validate-password-with-regular-expression/
Give it a read... */
if (!password.matches("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[!##&()–[{}]:;',?/%*~$^+=<>]).{8,20}$")) {
System.out.println();
System.out.println("INVALID PASSWORD! - Secure Password requirements:\n" +
"-------------------------------------------------\n" +
"Password must contain at least one digit [0-9].\n" +
"Password must contain at least one lowercase Latin character [a-z].\n" +
"Password must contain at least one uppercase Latin character [A-Z].\n" +
"Password must contain at least one special character like: ! # # & ( ). %, etc.\n" +
"Password must contain a length of at least 8 characters and a maximum of 20 characters.\n" +
"Try Again...\n");
password = "";
}
}
System.out.println("\nYour VALID password is: " + password);
System.out.println("Now HASH it! :)");

Java Entry Validation

I'm working on a server/client battleship game using sockets. Part of the project requires entry validation on the client side for entering tile locations. A user is supposed to enter a letter A-E and a number 1-5, and right now if you type in something invalid, it seems to freeze. Any help would be much appreciated, thanks in advance!
do{
System.out.println("------------------------------------------------------------------------------------------------");
System.out.println("Please type in a board position in the format of a letter followed by number, such as 'A1'. ");
Scanner sc = new Scanner(System.in);
String BoardChoice = sc.next();
if(BoardChoice.equals("A1" ) || BoardChoice.equals("B1" ) || BoardChoice.equals("C1" ) || BoardChoice.equals("D1" ) || BoardChoice.equals("E1" ) ||
BoardChoice.equals("A2" ) || BoardChoice.equals("B2" ) || BoardChoice.equals("C2" ) || BoardChoice.equals("D2" ) || BoardChoice.equals("E2" ) ||
BoardChoice.equals("A3" ) || BoardChoice.equals("B3" ) || BoardChoice.equals("C3" ) || BoardChoice.equals("D3" ) || BoardChoice.equals("E3" ) ||
BoardChoice.equals("A4" ) || BoardChoice.equals("B4" ) || BoardChoice.equals("C4" ) || BoardChoice.equals("D4" ) || BoardChoice.equals("E4" ) ||
BoardChoice.equals("A5" ) || BoardChoice.equals("B5" ) || BoardChoice.equals("C5" ) || BoardChoice.equals("D5" ) || BoardChoice.equals("E5" ))
{
flagtoo = false;
writer.writeUTF(BoardChoice);
}
else
{
System.out.println("Invalid Input Please re-enter!");
}
}while(flagtoo);
I would suggest you test each character separately by breaking them out with charAt, and please respect variable naming conventions. Something like
boolean valid = false;
String boardChoice = sc.nextLine(); // <-- not next
if (boardChoice.length() == 2) {
char col = boardChoice.charAt(0);
char row = boardChoice.charAt(1);
// The parenthesis here are just for clarity.
valid = ((col >= 'A' && col <= 'E') && (row >= '1' && row <= '5'));
}
My suggestion on the other hand will suggest to implement regex with a pattern that allows you to match 1st char alpha(no matter capitalization) followed by a number,
both in a range from a → e and 1 → 5
Scanner sc = new Scanner(System.in);
System.out.println("Please type in a ....y number, such as 'A1'. ");
do {
inp = sc.nextLine();
if (inp.matches("^[a-eA-E1-5]{0,2}")) {
inpArr[k++] = inp;
} else {
System.out.println("invalid input");
}
} while (k < numberOfElements);
System.out.println(Arrays.toString(inpArr));

Java error: java.lang.ArrayIndexOutOfBoundsException: 1

I am making a simple program that will take one word with "*" in the middle of the word ex: "Some*ing" and will take another string to replace it with the "*" in the first word. Like "th" -> output "Something".
Sample Run 1:
Enter the first String:
D*g
Enter the replacement String:
in
Ding
Simple enough. I made this program in IDEA (running Java 8) and it works alright (though I still need to add some minor stuff).
But in CodeRunner I have some problems. It says "java.lang.ArrayIndexOutOfBoundsException: 1". There is some mistake in my code and I have no idea where it is.
My code:
import java.util.Scanner;
import java.lang.Math;
import java.io.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the first String:");
//The inital String
String first = scan.nextLine();
System.out.println("Enter the replacement String:");
// SubString
String subs = scan.nextLine();
if (!(first.contains("!") || first.contains("#") || first.contains("#") || first.contains("$") || first.contains("%") || first.contains("^") || first.contains("&") || first.contains("(") || first.contains(")") || first.contains("+") || first.contains("-") || first.contains("_") || first.contains("~") || first.contains("`") || first.contains("\\") || first.contains("[") || first.contains("]") || first.contains("{") || first.contains("}") || first.contains(":") || first.contains(";") || first.contains("'") || first.contains("\"") || first.contains("/") || first.contains("?") || first.contains(".") || first.contains(">") || first.contains(",") || first.contains("<"))) {
if (first.contains("*") ) {
String parts[] = first.split("\\*");
String part1 = parts[0];
String part2 = parts[1];
String newString = part1 + subs + part2;
System.out.println(newString);
} else {
System.out.println("Error: no *");
}
} else {
System.out.println("Error: Incorrect characters");
}
}
}
The CodeRunner gives me that
Runtime Error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Main.main(Main.java:298)
at Ideone.assertRegex(Main.java:125)
at Ideone.test(Main.java:61)
at Ideone.main(Main.java:28)
Though code works at my IDE and we assume that it is possible to make so the code will work at the codeRunner
Thank you
Note: StringBuilder used only for demo
if (YOURSTRING.contains("*")) {
StringBuilder builder=new StringBuilder();
String parts[] = YOURSTRING.split("\\*");
for (int i = 0; i < parts.length; i++) {
builder.append(parts[i]);
}
System.out.println(builder.toString());
} else {
System.out.println("Error: no *");
}
use for loop instead of getting value statically from array
because if spit will done 1 time of non then this line
String part1 = parts[0];
String part2 = parts[1]; return ArrayIndexOutOfBoundsException because there is not a second element int array to get it, understood?
Thank's everybody who was helping me! I've learned about 10 new methods while solving this assignment until I found the resolution. That was a helpful experience. This assignment is done, I got an A for it (100%)! Thank you guys!
import java.util.Scanner;
public class AsmntFive {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the first String:");
String first = scan.nextLine();
System.out.println("Enter the replacement String:");
String subs = scan.nextLine();
if (!(first.contains("!") || first.contains("#") || first.contains("#") || first.contains("$") || first.contains("%") || first.contains("^") || first.contains("&") || first.contains("(") || first.contains(")") || first.contains("+") || first.contains("-") || first.contains("_") || first.contains("~") || first.contains("`") || first.contains("\\") || first.contains("[") || first.contains("]") || first.contains("{") || first.contains("}") || first.contains(":") || first.contains(";") || first.contains("'") || first.contains("\"") || first.contains("/") || first.contains("?") || first.contains(".") || first.contains(">") || first.contains(",") || first.contains("<"))) {
if (first.contains("*")) {
System.out.println(first.replace("*", subs));
} else {
System.out.println("Error: no *");
}
} else {
System.out.println("Error: Incorrect characters");
}
}
}

Java: How do I return user to main menu if user input is not a single alphabetic lowercase letter?

I'm trying to run a program that will allow the user to input both a char keyCharacter and a String theString. Then, using these inputs, I will mask the keyCharacter if it occurs in theString with a "$", remove the keyCharacter from the theString, and finally, count the number of times the keyCharacter occurs in theString altogether.
Every method is working fine, except the method getKeyCharacter where the user has to input a char:
The user can only enter a single letter (e.g. q, or z).
If the user enters anything other than that single letter (which can be anything from a word, phrase, sentence, special character like # or $, blank space or tabs, or just pressing enter), then the program returns the user to the original question that asks for the keyCharacter from the user. This should continue looping back to that original question until the user enters a valid input.
Since I'm still a beginner to java and loops are my weakness so far, this part is causing me a lot of trouble. I know I should be using a while loop, it is the logic behind the nested loops that is really confusing me.
From searching for possible solutions, I know there are these things called regex and try-catch exception that could help with my issue, but since we haven't gone over that explicitly in class, I'd prefer not to deal with that for now. Thank you.
Here's a paste of my code:
import java.util.*;
public class Foothill {
// main method
public static void main (String[] args) {
char keyCharacter = getKeyCharacter();
String theString = getString();
maskCharacter(theString, keyCharacter);
countKey(theString, keyCharacter);
removeCharacter(theString, keyCharacter);
}
// get keyCharacter
public static char getKeyCharacter() {
Scanner inputStream = new Scanner(System.in);
boolean stop = false;
String firstPrompt, strKeyCharacter;
char keyCharacter = ' ';
while (stop != true) {
firstPrompt = "Please enter a SINGLE character to act as key: ";
System.out.print(firstPrompt);
strKeyCharacter = inputStream.nextLine();
while (strKeyCharacter.length() != 1) {
firstPrompt = "Please enter a SINGLE character to act as key: ";
System.out.print(firstPrompt);
strKeyCharacter = inputStream.nextLine();
}
keyCharacter = strKeyCharacter.charAt(0);
while (strKeyCharacter.length() == 1) {
firstPrompt = "Please enter a SINGLE character to act as key: ";
System.out.print(firstPrompt);
strKeyCharacter = inputStream.nextLine();
if (keyCharacter == 'a' || keyCharacter == 'b' || keyCharacter == 'c' || keyCharacter == 'd'
|| keyCharacter == 'e' || keyCharacter == 'f' || keyCharacter == 'g' || keyCharacter == 'h'
|| keyCharacter == 'i' || keyCharacter == 'j' || keyCharacter == 'k' || keyCharacter == 'l'
|| keyCharacter == 'm' || keyCharacter == 'n' || keyCharacter == 'o' || keyCharacter == 'p'
|| keyCharacter == 'q' || keyCharacter == 'r' || keyCharacter == 's' || keyCharacter == 't'
|| keyCharacter == 'u' || keyCharacter == 'v' || keyCharacter == 'w' || keyCharacter == 'x'
|| keyCharacter == 'y' || keyCharacter == 'z') {
System.out.println("You entered: " + keyCharacter + '\n');
stop = true;
} else {
break;
}
}
}
return keyCharacter;
}
// declare final = 4 to be constant
public static final int minimumLength = 4;
// get theString
public static String getString() {
Scanner inputStream = new Scanner(System.in);
String secondPrompt, theString;
do {
secondPrompt = "Please enter a phrase or sentence >= 4: ";
System.out.print(secondPrompt);
theString = inputStream.nextLine();
System.out.print('\n');
} while (theString.length() < minimumLength || theString == null || theString.length() == 0);
inputStream.close();
return theString;
}
// mask keyCharacter with $
public static String maskCharacter(String theString, char keyCharacter) {
theString = theString.replace(keyCharacter, '$');
System.out.println("String with " + " '" + keyCharacter + "' " + " masked.");
System.out.println(theString + '\n');
return theString;
}
// count number of times keyCharacter occurs in theString
public static void countKey(String theString, char keyCharacter) {
int countChar = 0;
for (int charTimes = 0; charTimes < theString.length(); charTimes++) {
if (theString.charAt(charTimes) == keyCharacter) {
countChar++;
}
}
System.out.println( "The key character occurs " + countChar + " times. \n");
return;
}
// remove keyCharacter from theString
public static void removeCharacter(String theString, char keyCharacter) {
theString = theString.replace(String.valueOf(keyCharacter), "");
System.out.println("String with " + "'" + keyCharacter + "' removed: ");
System.out.println(theString);
return;
}
}
And here's a paste of my run (as you can see, there is some serious debugging to be done in my program):
Please enter a SINGLE character to act as key: f
Please enter a SINGLE character to act as key: f
You entered: f
Please enter a SINGLE character to act as key: f
You entered: f
Please enter a SINGLE character to act as key: f
You entered: f
Please enter a SINGLE character to act as key: f
You entered: f
Please enter a SINGLE character to act as key:
// which then continues so on so forth...
public static char getKeyCharacter(){
Scanner inputStream = new Scanner(System.in);
boolean stop = false;
String firstPrompt, strKeyCharacter;
char keyCharacter = ' ';
while(!stop){
firstPrompt = "Please enter a SINGLE character to act as key: ";
System.out.println(firstPrompt);
strKeyCharacter = inputStream.nextLine();
//check if the input contains only 1 character
boolean isSingleChar = (strKeyCharacter.length() == 1);
//check if the input character is within the ASCII code of 97 (a) to 122 (z)
boolean isValidChar =
strKeyCharacter.charAt(0) >= 97 &&
strKeyCharacter.charAt(0) <= 122;
if(isSingleChar && isValidChar){
keyCharacter = strKeyCharacter.charAt(0);
stop = true;
}
}
return keyCharacter;
}

Java - charAt(), equalsIgnoreCase, if statement testing?

What I want is no matter what the user inputs, if the first letter of their input is either a 'y' or 'n' regardless of case, it will print "game start".
I've tried equalsIgnoreCase() with the "letter" variable but it gives the error: char cannot be dereferenced. Any recommendations will be really appreciated on this! Thanks!
Scanner input = new Scanner(System.in);
System.out.println("Do you want to continue?");
String wesker = input.nextLine();
char letter = wesker.charAt(0);
if(letter == 'y' || letter == 'p'){
System.out.println("Game start");
} else {
System.out.println("Game over");
}
Try use Character#toLowercase():
if (Character.toLowerCase(letter) == 'y' || Character.toLowerCase(letter) == 'n') {
or
if (Character.toUpperCase(letter) == 'Y' || Character.toUpperCase(letter) == 'N') {
or simply
if( letter == 'y' || letter == 'Y' || letter == 'n' || letter == 'N' )
Just check against both cases:
if( letter == 'y' || letter == 'Y' || letter == 'p' || letter == 'P' )
equalsIgnoreCase can be used only by Strings. For your case, if you want to use that method, you can do this:
Scanner input = new Scanner(System.in);
String wesker = input.nextLine();
String letter = wesker.substring(0,1);
if(letter.equalsIgnoreCase("y") || letter.equalsIgnoreCase("n")){
System.out.println("Game start");
} else {
System.out.println("Game over");
}
You could pre-build a set of acceptable characters.
Set<Character> yes = new HashSet<>(Arrays.asList('y','Y','p','P'));
public void test() {
char letter = 'c';
if ( yes.contains(letter)) {
}
}

Categories

Resources