I have a class I wrote in Java and one of the methods is getCommand()
The purpose of this method is to read in a string and see what the user typed in matches any of the acceptable commands.
This is how I wrote it initially:
public char getCommand(){
System.out.println("Input command: ");
command = input.nextLine();
while(command.length() != 1){
System.out.println("Please re-enter input as one character: ");
command = input.nextLine();
}
while( command.substring(0) != "e" ||
command.substring(0) != "c" ||
command.substring(0) != "s" ||
command.substring(0) != "r" ||
command.substring(0) != "l" ||
command.substring(0) != "u" ||
command.substring(0) != "d" ||
command.substring(0) != "k" ||
command.substring(0) != "f" ||
command.substring(0) != "t" ||
command.substring(0) != "p" ||
command.substring(0) != "m" ||
command.substring(0) != "q"){
System.out.println("Please enter a valid character: ");
command = input.nextLine();
}
fCommand = command.charAt(0);
return fCommand;
}
Now, I see the problem with this is that since I use the OR operator, it won't escape that loop because the character I type in will always not equal one of them. I tried changing it to the AND operator, but same problem. What would be the best way to only accept those specific characters?
Much appreciated.
Your logic is incorrect. You should be using logical ANDs and not ORs. Also I believe you want to use charAt() instead of substring() then compare characters.
i.e.,
while( command.charAt(0) != 'e' &&
command.charAt(0) != 'c' &&
command.charAt(0) != 's' &&
...)
Otherwise if you want to test for actual single-character string inputs, just check using string equality.
while( !command.equals("e") &&
!command.equals("c") &&
!command.equals("s") &&
...)
You should define your commands as constants (individually). Hard coding values like this makes it harder to update your code in the future.
If the program is simply proof of concept or homework I would use:
private static final String COMMANDS = "ecsrludkftpmq";
while(!COMMANDS.contains(command.getChar(0)) {
System.out.println("Please enter a valid character: ");
command = input.nextLine();
}
Otherwise, if this is production code I would consider making a simple Command(char) class and providing individual command constants as part of a collection (possibly a Map against the Character key), which can be tested to see if contains a matching command.
Related
I have an error checker that makes sure the guess entered by the user
a) Has a certain size (this works)
b) Has no numbers (doesn't work)
c) Doesn't use certain letters (doesn't work)
Here is my code, I'm not sure what I'm doing wrong:
System.out.println("Enter Code:");
guess = input.nextLine();
guess = guess.toUpperCase();
while (guess.length() != v || guess.contains("[0-9]") || guess.contains("[ACDEFHIJKLMNQSTUVWXZ]")) {
System.out.println("Bad input! Try again");
System.out.println("Use the form \"BGRY\" with your respective length of letters");
guess = input.nextLine();
guess = guess.toUpperCase();
}
The java Sting.contains() method only checks if the string entered is a substring. To use a regex, try String.matches().
For example, to that the string only contains certain letters, use
while (guess.length() != v || !guess.matches("^[VALID CHARACTERS]*$")
{
}
I am confused on how to use || and && in the same if statement.
What I am trying to do is have it print something if the string starts with an "D" or an "O", and if one is true check if the string has a character length of two.
Example: if the string is "DE" it will print something. However, if it is "SE" it will not print anything.
else if( (answer.startsWith("D") || answer.startsWith("O"))
&& (answer.length() == 2) ) {
//print something
}
Java is applying a "short circuit" to your logic. It does the first part (starts with "D" or "O") and if that's true it proceeds to the second part (length is 2). However if the first part evaluates to false then it never even bothers to execute the second part.
So your "SE" string will never go into the "print something" bit because it doesn't meet your first criteria of starting with D or O. And based on your description of what the logic should be, that is correct.
If you actually mean that if it starts with "D" or "O" OR is 2 characters long then your logic statement should have been:
else if( answer.startsWith("D") || answer.startsWith("O")
|| (answer.length() == 2 ) {
//print something
}
Edit: Oops, just pasted the original code in the first time...!
I would check first the length and after the two conditions e.g.
else if (answer.lenght()==2) {
if (answer.startsWith("D") || answer.startsWith("O"){
//print something that lenght is 2 and starts with D or O
}
}
}
In that case you have to check length first because && will true if left side and right side both true
else if( (answer.length() == 2)&&(answer.startsWith("D") || answer.startsWith("O"))
{
//your logic
}
I'm having trouble with a project, and I don't quite have the vocabulary to search for the issue I'm having. I think it has to do with syntax of Java regarding chars. Other than the code below, the input is taken as a string above and parsed into a char.
switch (accountType)
{
case 'c':
case 'C':
// Determine interest based on balance
if (balance >= 5000)
interest = balance * .03;
else
interest = balance * .01;
break;
case 's':
case 'S':
interest = balance * .04;
break;
default:
// Catch all for invalid account types
if (accountType != 'c' || 'C' || 's' || 'S');
validAccount = false;
}
Replace
if (accountType != 'c' || 'C' || 's' || 'S');
by
if (accountType != 'c' || accountType != 'C' || accountType != 's' || accountType != 'S')
But to be honest, the condition inside this if will always be true. Take for example, if accountType is c, the first condition will fail but others still pass, and since it's a logical OR, even one true is enough for the entire conjunction to return true. You can take any other value of accountType but it will always return true.
Also, you should remove the ; at the end of if statement for the sake of correct semantics. But you may remove the entire if as well.
Why are you using the last if condition?
I think it is unnecessary. All invalid accounts will fall to the default block automatically.
You have to write accountType every time for comparision:
if(accountType != 'c' || accountType != 'C' || accountType != 's' || accountType != 'S'){
//your code...
}
http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.24
"Each operand of the conditional-or operator must be of type boolean or Boolean, or a compile-time error occurs."
char is not boolean.
Too many or's hurting my head... Just use a string that contains what you want and see if the character is contained within it like so
String chars = "cCsS";
if(!chars.contains(accountType + ""))
validAccount = false;
While comparing, each time you have to compare against the variable:
if (accountType !='c'|| accountType !='C' || accountType != 's' || accountType !='S')
validAccount = false;
Replace your code with above one.
Note: Remove the ; at the end.
As mentioned in the comments, since it reaches the default case, you can assume it's a invalid account. So in your switch case
default:
validAccount = false
will suffice...
In my if statement, I'm trying to check if the first letter of a string is either Y or y, and then proceed as such. Below is what I have, but I don't believe it to be correct.
System.out.print("Do you wish to do another calculation (Yes/No): ")
option = scan.next();
if (option.substring(0,1) == "N" && option.substring(0,1) == "n" )
{
System.out.println("Have a good day");
System.exit(0);
}
bmi.setOption(option);
I instantiated option as String option = " "; earlier on in my program. I know how to check if strings equal a certain character, however am having trouble checking to see if only the FIRST character of the string is equal to something.
Thank you!
if (Character.toLowerCase(option.charAt(0)) == 'n')
The first char can't be both "N" and "n", looks like you want it to be "N" or "n"
if (option.substring(0,1).equals("N") || option.substring(0,1).equals("n") )
We had == before which is more like a memory comparison we want to compare value so we use equals
I'm writing a simple spell checker program , but i'm having trouble with a loop and i can't seem to figure it out. Here's my code
public class spellchecker {
public static void main(String[] args) {
// setting up dictionary
String[] dictionary = {"win","winner","know","born","were","plan","must","you","correct","college", "to"} ;
//defining our sentence
String sentence = "You were born to win but to be a winners you must plan to win prepare to win and expect to win";
//splitting sentence into an array of words
String[] split = sentence.split("\\s");
for(int i = 0; i<split.length; i++)
{
if(split[i].equals(dictionary[0]) || split[i].equals(dictionary[1]) || split[i].equals(dictionary[2]) || split[i].equals(dictionary[3]) || split[i].equals(dictionary[4]) || split[i].equals(dictionary[5]) || split[i].equals(dictionary[6]) || split[i].equals(dictionary[7]) || split[i].equals(dictionary[8]) || split[i].equals(dictionary[9]) || split[i].equals(dictionary[10]) || split[i].equals(dictionary[11]))
{
System.out.println(split[i] + " is valid");
}
else
{
System.out.println(split[i] + " is invalid, please correct");
}
}
}
}
Indices for an array only run from 0 through n - 1. Here, with a dictionary array of length 11, that's 0 through 10. However, you explicitly reference index 11 here:
|| split[i].equals(dictionary[10]) || split[i].equals(dictionary[11]))
You're checking all of them explicitly, starting with 0, so just remove that last one (11).
|| split[i].equals(dictionary[10]))
But what if you add 5 more words to the dictionary? 50? Your long chain of if conditions will also need to grow. For flexibility, you should consider a for loop over all of the contents of the dictionary array. Even better, consider using a HashSet to store your dictionary words, so that you don't have to scan the entire dictionary for every entered word.
Your array has 11 elements (0 - 10). So 11 is out of bounds.
split[i].equals(dictionary[11]
You might really want to consider using a loop in some way rather than hardcoding your indexes.
for a more general solution, replace your big if with:
if(Arrays.asList(dictionary).contains(split[i]))
This will work for any dictionary.
Remove split[i].equals(dictionary[11]) from your if() condition
i.e.
Your if could be
if(split[i].equals(dictionary[0]) || split[i].equals(dictionary[1]) || split[i].equals(dictionary[2]) || split[i].equals(dictionary[3]) || split[i].equals(dictionary[4]) || split[i].equals(dictionary[5]) || split[i].equals(dictionary[6]) || split[i].equals(dictionary[7]) || split[i].equals(dictionary[8]) || split[i].equals(dictionary[9]) || split[i].equals(dictionary[10]))