I'm trying to have my program check the name that the player enters to see if it uses any invalid characters. It seems to make sense in my mind how to make it work, but it seems not to work in the actual environment. When I run it, and I use invalid characters then it will just go on to the next part of the program. Any Ideas on how to fix it?
Here is my relevant code block:
if (!(nameInput.getText().equals(""))) {
boolean allow = true;
String check = nameInput.getText();
for (int i = 0;i>check.length();i++) {
if (check.charAt(i) == '`' || check.charAt(i) == '~' ||
check.charAt(i) == '!' || check.charAt(i) == '#' ||
check.charAt(i) == '#' || check.charAt(i) == '$' ||
check.charAt(i) == '%' || check.charAt(i) == '^' ||
check.charAt(i) == '&' || check.charAt(i) == '*' ||
check.charAt(i) == '(' || check.charAt(i) == ')' ||
check.charAt(i) == '_' || check.charAt(i) == '+' ||
check.charAt(i) == '=' || check.charAt(i) == '[' ||
check.charAt(i) == ']' || check.charAt(i) == '{' ||
check.charAt(i) == '}' || check.charAt(i) == ';' ||
check.charAt(i) == '\''|| check.charAt(i) == ':' ||
check.charAt(i) == '"' || check.charAt(i) == '<' ||
check.charAt(i) == '>' || check.charAt(i) == '?' ||
check.charAt(i) == ',' || check.charAt(i) == '.' ||
check.charAt(i) == '/' || check.charAt(i) == '\\'||
check.charAt(i) == '|' || check.charAt(i) == '1' ||
check.charAt(i) == '2' || check.charAt(i) == '3' ||
check.charAt(i) == '4' || check.charAt(i) == '5' ||
check.charAt(i) == '6' || check.charAt(i) == '7' ||
check.charAt(i) == '8' || check.charAt(i) == '9' ||
check.charAt(i) == '0') {
allow = false;
}
}
if (allow == true) {
player = new Player(check);
window.refresh();
mainMenu();
} else {
JOptionPane.showMessageDialog(window, "Invalid Name(Uses invalid Characters","Invalid!", JOptionPane.OK_OPTION);
}
} else {
JOptionPane.showMessageDialog(window, "Can Not Leave Name Blank!", "Missing Name!", JOptionPane.OK_OPTION);
window.refresh();
createPlayer();
}
}
for(int i = 0;i>check.length();i++)
Your for loop is never going to be entered, as I don't believe a String's length can ever be negative...
Did you mean to use < instead?
Also, there are significantly better ways to check for valid names than a gigantic chain of character checks.
One way is by using regular expressions; check out Java's Pattern class and Google to learn regex. That way you can reduce your loop-and-if-block to this (I think; I just accepted alphabetic characters only and rejected everything else based on a really quick glance at that monstrosity):
allow = String.matches("[a-zA-Z]{1,}");
If you really are interested in allowing only Strings that consist of characters not on that list, you can do it with a regular expression like this.
allow = check.matches("[^]`~!##$%^&*()_+=[{};':\"<>?,./\\\\|1234567890]*");
This will set allow to true if check is made up entirely of characters not on the list.
Note that I placed ^ just inside the [ - this means "not". I also moved ] to immediately after the ^, so that it's not interepreted as closing the list.
Change
for(int i = 0;i>check.length();i++)
to
for(int i = 0;i<check.length();i++)
Since i is 0 which is obviously less that check.length() program flow never really enters the for loop.
Also instead of just check for "" add a null check.
if(nameInput.getText()!=null && !(nameInput.getText().equals(""))){..}
Related
This question already has answers here:
PrintWriter append method not appending
(5 answers)
How to append text to an existing file in Java?
(31 answers)
Closed 5 years ago.
I need HELP. I tried to separate the valid serial keys from invalid ones. I got the output correctly. but then when i tried to write it in a file, ONLY the last line is being written.
the output is:
1A000000
1A000001
1A000002
1A000003
1A000004
1A000005
2B200012
3C343455
4D342423
5E324344
6F435435
7G245347
and I want to write this to a file. But ONLY 7G245347 is being written.
import java.util.*;`
import java.io.*;
public class ValidSerialKey {
public static void main(String[] args) throws IOException {
String keys = "";
File file = new File("serialkeys.txt");
try{
Scanner scan = new Scanner(file);
while (scan.hasNext()){
keys = scan.nextLine();
if ((keys.charAt(0) == '1' || keys.charAt(0) == '2' || keys.charAt(0) == '3' || keys.charAt(0) == '4' || keys.charAt(0) == '5' ||
keys.charAt(0) == '6' || keys.charAt(0) == '7' || keys.charAt(0) == '8' || keys.charAt(0) == '9' ) &&
(keys.charAt(1) == 'A' || keys.charAt(1) == 'B' || keys.charAt(1) == 'C' || keys.charAt(1) == 'D' || keys.charAt(1) == 'E' ||
keys.charAt(1) == 'F' || keys.charAt(1) == 'G' || keys.charAt(1) == 'H' || keys.charAt(1) == 'I' || keys.charAt(1) == 'J' ||
keys.charAt(1) == 'K' || keys.charAt(1) == 'L' || keys.charAt(1) == 'M' || keys.charAt(1) == 'N' || keys.charAt(1) == 'O' ||
keys.charAt(1) == 'P' || keys.charAt(1) == 'Q' || keys.charAt(1) == 'R' || keys.charAt(1) == 'S' || keys.charAt(1) == 'T' ||
keys.charAt(1) == 'U' || keys.charAt(1) == 'V' || keys.charAt(1) == 'W' || keys.charAt(1) == 'X' || keys.charAt(1) == 'Y' ||
keys.charAt(1) == 'Z' )){
System.out.println(keys);
File filein = new File("ValidKeys.txt");
try{
try
(PrintWriter pw = new PrintWriter(filein)){
pw.print(keys);
pw.close();
}
}catch (FileNotFoundException ex){
System.out.println(ex.getMessage());
}
}//end of if
}//end of while
scan.close();
}catch (FileNotFoundException exp){
System.out.println(exp.getMessage());
}
}
}
You want to keep the PrintWriter opened to write other things during the next iterations of the loop
So don't create a new one at each iteration.
As a side note, you don't need to close explicitly the PrintWriter instance when you use try with resources.
You should replace this logic :
loop
try
(PrintWriter pw = new PrintWriter(uniqueFile)){
pw.print(keys);
}//end of inner try
end loop
by a logic where you include the whole logic in the try with resources statement :
try(PrintWriter pw = new PrintWriter(uniqueFile)){
loop
pw.print(keys);
end loop
}
catch (IOException e){
... // exception handling
}
This question already has answers here:
Scanner NoSuchElementException when calling .next() method
(3 answers)
Closed 5 years ago.
if (charIte.next()=='{' || charIte.next()=='}'
|| charIte.next()=='[' || charIte.next()==']'
|| charIte.next()=='(' || charIte.next()==')'
|| charIte.next()=='*' || charIte.next()=='"'
|| charIte.next()=='/'){
}
The program returns:
Exception in thread "main" java.util.NoSuchElementException at line
|| charIte.next()=='(' || charIte.next()==')'
What is the problem?
Each invocation of next() consumes one token. Call it once, and save and then compare with the result. Like,
char ch = charIte.next();
if (ch == '{' || ch == '}' || ch == '[' || ch == ']' || ch == '('
|| ch == ')' || ch == '*' || ch == '"' || ch == '/') {
// ...
}
Each time you do charIte.next() you're asking to read the next token.
I think what you should do to ischar ite = charIte.next.chartAt(0) and then use ite in your if statement
if (ite next()=='{' || next()=='}'
|| ite.next()=='[' || ite.next()==']'
|| ite.next()=='(' || ite.next()==')'
|| ite.next()=='*' || ite.next()=='"'
|| ite.next()=='/'){
Info on Scanner
This question already has answers here:
PrintWriter append method not appending
(5 answers)
How to append text to an existing file in Java?
(31 answers)
Closed 5 years ago.
I need HELP. I tried to separate the valid serial keys from invalid ones. I got the output correctly. but then when i tried to write it in a file, ONLY the last line is being written.
the output is:
1A000000
1A000001
1A000002
1A000003
1A000004
1A000005
2B200012
3C343455
4D342423
5E324344
6F435435
7G245347
and I want to write this to a file. But ONLY 7G245347 is being written.
import java.util.*;`
import java.io.*;
public class ValidSerialKey {
public static void main(String[] args) throws IOException {
String keys = "";
File file = new File("serialkeys.txt");
try{
Scanner scan = new Scanner(file);
while (scan.hasNext()){
keys = scan.nextLine();
if ((keys.charAt(0) == '1' || keys.charAt(0) == '2' || keys.charAt(0) == '3' || keys.charAt(0) == '4' || keys.charAt(0) == '5' ||
keys.charAt(0) == '6' || keys.charAt(0) == '7' || keys.charAt(0) == '8' || keys.charAt(0) == '9' ) &&
(keys.charAt(1) == 'A' || keys.charAt(1) == 'B' || keys.charAt(1) == 'C' || keys.charAt(1) == 'D' || keys.charAt(1) == 'E' ||
keys.charAt(1) == 'F' || keys.charAt(1) == 'G' || keys.charAt(1) == 'H' || keys.charAt(1) == 'I' || keys.charAt(1) == 'J' ||
keys.charAt(1) == 'K' || keys.charAt(1) == 'L' || keys.charAt(1) == 'M' || keys.charAt(1) == 'N' || keys.charAt(1) == 'O' ||
keys.charAt(1) == 'P' || keys.charAt(1) == 'Q' || keys.charAt(1) == 'R' || keys.charAt(1) == 'S' || keys.charAt(1) == 'T' ||
keys.charAt(1) == 'U' || keys.charAt(1) == 'V' || keys.charAt(1) == 'W' || keys.charAt(1) == 'X' || keys.charAt(1) == 'Y' ||
keys.charAt(1) == 'Z' )){
System.out.println(keys);
File filein = new File("ValidKeys.txt");
try{
try
(PrintWriter pw = new PrintWriter(filein)){
pw.print(keys);
pw.close();
}
}catch (FileNotFoundException ex){
System.out.println(ex.getMessage());
}
}//end of if
}//end of while
scan.close();
}catch (FileNotFoundException exp){
System.out.println(exp.getMessage());
}
}
}
You want to keep the PrintWriter opened to write other things during the next iterations of the loop
So don't create a new one at each iteration.
As a side note, you don't need to close explicitly the PrintWriter instance when you use try with resources.
You should replace this logic :
loop
try
(PrintWriter pw = new PrintWriter(uniqueFile)){
pw.print(keys);
}//end of inner try
end loop
by a logic where you include the whole logic in the try with resources statement :
try(PrintWriter pw = new PrintWriter(uniqueFile)){
loop
pw.print(keys);
end loop
}
catch (IOException e){
... // exception handling
}
This is my code
import java.util.*;
public class PhoneKeypad {
public static void main(String[] args){
System.out.print("Enter an uppercase letter ");
Scanner input = new Scanner(System.in);
String phNumber = input.next();
String output = "";
for(int i = 0 ; i < phNumber.length() ; i++){
char ch = Character.toUpperCase(phNumber.charAt(i));
if(Character.isLetter(ch)){
int digit = getNumber(ch);
output = output + digit;
}
else{
output = output + ch;
}
}
System.out.println(output);
}
public static int getNumber(char upperCaseLetter){
if(upperCaseLetter == 'A' || upperCaseLetter == 'B'
|| upperCaseLetter == 'C')
return "The Corresponding number is 2";
else if(upperCaseLetter == 'D' || upperCaseLetter == 'E'
|| upperCaseLetter == 'F')
return "The Corresponding number is 3";
else if(upperCaseLetter == 'G' || upperCaseLetter == 'H'
|| upperCaseLetter == 'I')
return "The Corresponding number is 4";
else if(upperCaseLetter == 'J' || upperCaseLetter == 'K'
|| upperCaseLetter == 'L')
return "The Corresponding number is 5";
else if(upperCaseLetter == 'M' || upperCaseLetter =='N'
|| upperCaseLetter == 'O')
return 6 "The Corresponding number is 6";
else if(upperCaseLetter == 'P' || upperCaseLetter == 'Q'
|| upperCaseLetter == 'R')
return "The Corresponding number is 7";
else if(upperCaseLetter == 'S' || upperCaseLetter =='T'
|| upperCaseLetter == 'U')
return "The Corresponding number is 8";
else if(upperCaseLetter == 'V' || upperCaseLetter == 'W'
|| upperCaseLetter == 'Y' || upperCaseLetter == 'Z')
return "The Corresponding number is 9";
else
return 0;
}
}
This gives me errors. I need the output to say the corresponding number is _
and not just the number
These are the types of errors I am getting
PhoneKeypad.java:67: error: ';' expected
return 6 "The Corresponding number is 6";
^
PhoneKeypad.java:69: error: 'else' without 'if'
else if(upperCaseLetter == 'P' || upperCaseLetter == 'Q'
^
PhoneKeypad.java:69: error: illegal start of type
else if(upperCaseLetter == 'P' || upperCaseLetter == 'Q'
^
PhoneKeypad.java:69: error: <identifier> expected
else if(upperCaseLetter == 'P' || upperCaseLetter == 'Q'
^
PhoneKeypad.java:69: error: ';' expected
else if(upperCaseLetter == 'P' || upperCaseLetter == 'Q'
^
PhoneKeypad.java:69: error: illegal start of type
else if(upperCaseLetter == 'P' || upperCaseLetter == 'Q'
^
PhoneKeypad.java:69: error: <identifier> expected
else if(upperCaseLetter == 'P' || upperCaseLetter == 'Q'
^
PhoneKeypad.java:69: error: ';' expected
else if(upperCaseLetter == 'P' || upperCaseLetter == 'Q'
^
PhoneKeypad.java:69: error: <identifier> expected
else if(upperCaseLetter == 'P' || upperCaseLetter == 'Q'
^
PhoneKeypad.java:69: error: illegal start of type
else if(upperCaseLetter == 'P' || upperCaseLetter == 'Q'
^
Look at line 67. You have return 6 "The Corresponding number is 6"; when you should have return "The Corresponding number is 6";
If you want to return Strings instead of ints just change the method signature.
i.e. public static String getNumber(char upperCaseLetter){ instead of public static int getNumber(char upperCaseLetter){
I would recommend downloading an IDE such as "Eclipse" to help you write your code. It will pinpoint a lot of the errors that are present in your code.
public static int getNumber(char upperCaseLetter)
As for your question, remove the intand replace it with either 'String' or 'void'
Your return values for getNumber are Strings, but the method, as well as your main method, expects an int value. For example, the following should work better:
public static int getNumber(char upperCaseLetter) {
if (
upperCaseLetter == 'A'
|| upperCaseLetter == 'B'
|| upperCaseLetter == 'C') {
return 2;
} else if (
upperCaseLetter == 'D'
|| upperCaseLetter == 'E'
|| upperCaseLetter == 'F') {
return 3;
}
//etc.
return 0;
}
However, since you use that many if / else if in this method, you could also consider using a switch case:
public static int getNumber2(char upperCaseLetter) {
switch (upperCaseLetter) {
case 'A':case 'B':case 'C':
return 2;
case 'D':case 'E':case 'F':
return 3;
//etc.
default:
return 0;
}
}
I have a hangman game created in java. I want to create a simple function that will check if the word input has white space and/or special characters.
I've found the functions String.replaceAll(), but I haven't been able to dig up a premade function that returns a boolean value for if there are special charactors and/or white space.
Is there a function out there already? Or at least a simpler way of specifying no white space or special characters other than doing the following?
public void checkWord()
{
boolean flag = false;
for(int i=0;i<wordArray.length;i++)
{
if(wordArray[i] == '1' || wordArray[i] == '2' || wordArray[i] == '3' || wordArray[i] == '4' || wordArray[i] == '5' || wordArray[i] == '6' || wordArray[i] == '7' || wordArray[i] == '8' || wordArray[i] == '9' )
{
flag = true;
}
}
if(flag == true)
{
System.out.println("Invalid characters used in the word");
System.exit(0);
}
}
The function is getting dense, and I've only covered digits. Thoughts?
You can use a simple regular expression:
public boolean isValidWord(String w) {
return w.matches("[A-Za-z]*");
}
Explanation of the regex:
[A-Za-z] - capital or lowercase letter
* - zero or more
More info on regexes: http://www.regular-expressions.info/