Is there any other way to shorten this condition?
if (oper.equals("add") || oper.equals("Add") || oper.equals("addition") ||
oper.equals("Addition") || oper.equals("+"))
I was just wondering if there's something I can do to 'shortcut' this. The user will type a string when prompted what kind of operation is to be performed in my simple calculator program. Our professor said our program should accept whether the user enters "add", or "Add", you know, in lowercase letters or not... Or is the only way I should do it?
You can use String#equalsIgnoreCase(String) for 1st four strings: -
if (oper.equalsIgnoreCase("add") ||
oper.equalsIgnoreCase("addition") ||
oper.equals("+"))
If number of strings increases, you would be better off with a List, and use its contains method. But just for these inputs, you can follow this approach only.
Another way to approach this is to use String#matches(String) method, which takes a regex: -
if (oper.matches("add|addition|[+]")
But, you don't really need a regex for this. Specially, this method can become ugly for greater inputs. But, it's just a way for this case. So, you can choose either of them. 1st one is more clear to watch on first go.
Alternatively, you can also use enum to store operators, and pass it's instance everywhere, rather than a string. It would be more easy to work with. The enum would look like this:
public enum Operator {
ADD,
SUB,
MUL,
DIV;
}
You can enhance it to your appropriate need. Note that, since you are getting user input, you would first need to identify the appropriate enum instance based on it, and from there-on you can work on that enum instance, rather than String.
In addition to #Rohit's answer, I would like to add this.
In case of comparison of strings, if oper is null a NullPointerException could be thrown. SO its always better to write
"addition".equalsIgnoreCase(oper)
instead of
oper.equalsIgnoreCase("addition")
If aDD is considered as invalid input, you can consider following approach:
ArrayList<String> possibleInputs = new ArrayList<String>();
possibleInputs.add("Add");
possibleInputs.add("add");
possibleInputs.add("Addition");
possibleInputs.add("addition");
possibleInputs.add("+");
if(possibleInputs.contains(oper))
{
// ...
}
throw that whole bit of code inside a function called: isOperationAddition(String s){...} that returns a boolean.
So this:
if (oper.equals("add") || oper.equals("Add") || oper.equals("addition") ||
oper.equals("Addition") || oper.equals("+")){...}
Changes to this
if (isOperationAddition(operation)){...}
Then inside that method, don't use Strings as branch material for your if statements. Have a variable that defines which kind of operation it is and "Keep the barbarians (confusion/ambiguous users) out at the moat". You should not be always iterating against a list to remember what operation we are dealing with.
You can take the input, and convert in to lower case then compare.
str.toLowerCase()
then pass to your if() statement
if(str.equals("add") || str.equals("addition") || str.equals("+"))
Related
It's my statment for example,I dont want '&&' every condition in the statment.Is there simple way to compare all object in one condition like in the exam?
int a = 3;
if(a!=0 && a!=1 && a!=2) // Example Statement
I looking for this type a thing.
if(a!=0,1,2)
Is there a function or a condition style, or something like that?
You can use !Arrays.asList(1,2,3).contains(a);
I have the following statement...
personName[0] = n[y].getName().equals ("Penny") ? personName[0]++ : personName[0];
personName[] is an integer array. getName returns a string. Every time getName is equal to "Penny," I want personName[0] to add one. How should I do this? When I run it, personName[0] does not add one and I don't know why.
Don't try to abuse the conditional operator like this. A plain old if is vastly more readable and concise:
if (n[y].getName().equals ("Penny")) {
personName[0]++;
}
If you must use a conditional operator, it would be clearer to use +=:
personName[0] += n[y].getName().equals ("Penny") ? 1 : 0;
If you want just to increment personName[0], wouldn't be better to use just an if? Sometimes, conditional operator is to much for simple problems.
I am trying to get a If statement to work in java.
I have a String startTime;
I want to make it so 06:00 to 9:59 is a peak time and some other times but I just want to get one if statement working right first
i use
*if (startTime >= "06:00" && startTime <= "9:59");*
I know that strings dont really search like that but I was told by the instructor that we can use strings to accomplish the task really easy. I was also told to only use the main method not use other classes
it comes up with:
**the operator >= is undefined for the argument type(s) java.lang.String, java.lang.String**
Use String.compareTo to accomplish this.
if (startTime.compareTo("06:00")>0 && startTime.compareTo("09:59")<0) ...;
Break your string in to the hours and minutes (use String.split), then convert the two to integers (use Integer.parseInt), then comparisons are easy.
String is an object and it does not have operators like <= and >=.
You can compare two strings using equals() and equalsIgnoreCase() methods or else you can check references of string using ==.
In your case since you are comparing two strings, you will not be able to determine if one string is greater than other unless you convert it to Java Date object or to Double object or else you can also use compareTo() method.
I'm doing the finishing touches for a class project and I'm adding in a safety net for one of my user inputs. I have it set so that if the user puts in "1" or "2", the data they enter will be displayed in different ways. I want to add a method that prevents the user from entering anything other than "1" or "2". Here is the code for it.
do
{
System.out.println("Please type either '1' or '2'.");
Scanner scan = new Scanner(System.in);
a = scan.nextInt();
}
while (a != (1||2));
//after user enters 1 or 2, return the choice
return a;
I've been reading about the operands and logic, but I'm kind of stuck. I've been badgering my teacher the whole way through so I figured I'd give him a break since I'm not his only student. My error is saying "bad operand types for binary operator '||'.
This is a common misconception when learning programming.
You, as a human, can easily read the statement which reads like this: "while a is not 1 or 2", but the computer has to follow certain rules, and one of the rules is that "or" takes precedence.
What this means is that it first triest to figure out what "1 or 2" means, since basically, your statement is similar to this:
while (a != SOMETHING);
|| in the Java language is "logical or", which translates to this: Take the two values (called operands) on each side of the || (called the operator), and combine them according to the rules of "logical or".
"logical or" uses two boolean values, which can only be True or False, and since you asked it to use the operator with numbers, that's why you get that particular error message.
If you had tried using the single pipe, |, the compiler might have stopped complaining, but it would still not do what you want it to do.
1 or 2 when dealing with numbers, using the | operator, which is the "bitwise or" operators, you would get the two numbers combined to form the number 3. You can read more about "bitwise operators" if you want to know why.
In short, you cannot write your comparison like this.
In programming languages, comparisons are done two values at a time, ie. one against another, so your only choice is to expand the expression to compare twice.
Here is some equivalent expressions which will give you what you want:
while (a != 1 && a != 2);
or this:
while (!(a == 1 || a == 2));
To be hones, I like the first better.
It is (a != 1 && a!=2) - You actually want to exit the loop when a is either 1 or 2.
You need to do separate conditional statements for a!= 1 and a!= 2.
Your conditional statement should look something like this:
(a!=1) && (a!=2)
You can't treat an int like pseudo-regex. Replace
while (a != (1||2));
with
while (a != 1 && a!= 2);
try this in your while loop condition
((a!=1) && (a!=2))
You have to write
while (a != 1 && a != 2)
because it's the equivalent of not (a == 1 || a == 2)
The binary operator '||' needs two boolean operand on both side. Since, your operands are integers, this is a syntax error.
You should do it in this way:
do{
// core of the loop...
}while(a!=1 && a!=2);
The problem here is you are trying to write code that makes sense read as English, but it doesn't work like that. The || operator takes two expressions and returns if one or the other is true. That means what you have written doesn't make sense.
The simplest way to replace this is to expand it out:
a != 1 && a != 2
(We need to use && as we are checking that neither of them is true).
Note that this can become verbose and awkward. Alternatively, a good replacement (given you have a lot of values to check) is a membership check in a collection (a Set is a good choice as you are guaranteed a O(1) membership test). E.g:
Set<Integer> possibles = new HashSet<Integer>();
Collections.addAll(possibles, new Integer[] {1, 2, ...});
while (!possibles.contains(a)) {
...
I asked about this array a little while ago, and I can't see what the problem is. Too tired. What have I done wrong? Basically, I am taking a string array and trying to check to see if it contains numbers or an x (ISBN number validation). I want to take the number from a given input (bookNum), check the input, and feed any valid input into a new array (book). At the line
'bookNum.charAt[j]==book[i]'
I get the 'not a statement error'. What gives?
String[] book = new String [ISBN_NUM];
bookNum.replaceAll("-","");
if (bookNum.length()!=ISBN_NUM)
throw new ISBNException ("ISBN "+ bookNum + " must be 10 characters");
for (int i=0;i<bookNum.length();i++)
{
if (Character.isDigit(bookNum.charAt(i)))
bookNum.CharAt[j]==book[i];
j++;
if (book[9].isNotDigit()||
book[9]!="x" ||
book[9]!="X")
throw new ISBNException ("ISBN " + bookNum + " must contain all digits" +
"or 'X' in the last position");
== is java is used for equivalence comparison. If you want to assign it, use a single =.
The first issue here is that charAt is a function, and thus needs parenthesis even though you are accessing with an index like an array.
The other issue is that the line is a boolean expression, which just by itself does not mean anything. A lot of people are suggestion that you mean to make an assignment to that character, but just changing to a single equals causes other problems. The left side of an equals sign needs to be a variable, and the result of a function is not a variable.
Strings are immutable, so you can not simply change one of the characters in the string. Earlier in your code, you have a call to replaceAll(), that returns a new string with the alterations. As written, this altered string is being lost.
There are few odd problems here. For starters, did you mean for book to be an array of Strings, as opposed to just one string? You're trying (assuming CharAt was written properly and the assignment was proper) to assign a character to a string.
Second, instead of copying character by character, why not check the whole string, and copy the whole thing at the end if it is a proper ISBN? Depending on what you do with Exceptions (if you continue regardless), you could add a boolean as a flag that gets set if there is an error. At the end, if there is no error, then make book = to booknumber.replace(etc...)
bookNum.CharAt[j]==book[i];
Should be
bookNum.CharAt[j]=book[i];
You are using an equality boolean operator, not an assignment one.
Looks like you're using .charAt(i) wrong! Assuming that "bookNum" is a String, you should use:
bookNum.charAt(i)==book[i];
Instead. Note that this is a boolean expression, and not "=".
The line bookNum.CharAt[j]==book[i]; isn't a statement. It's a comparison. Perhaps you want bookNum.CharAt[j]=book[i]; (single = instead of ==).
Edit: That's not going to fix things, though, since you can't assign to bookNum.CharAt[j].