how to make several different if condition Java - java

the If condition doesn't work always trade in allowance= 3,250.00 I need it depends on the state and car year. I attached what my code and more explanation.
The trade-in allowance depends on the year of manufacture of the vehicle and the state in which it had been registered at initial purchase. FHM does not accept vehicles manufactured earlier that 1990 for trade-in allowance. For vehicles manufactured between
1990 and 1999 and initially registered in Illinois, Indiana, Iowa, Kansas, Michigan, Minnesota, Missouri, or Nebraska, the trade-in allowance is $3000.00, for all other states it is $ 2750.00.
For vehicles manufactured between 2000 and 2009 and initially registered in Illinois, Indiana, Iowa, Kansas, Michigan, Minnesota, Missouri, Nebraska, North Dakota, Ohio, South Dakota or Wisconsin, the trade-in allowance is $3250.00, for all other states it is $ 3000.00.
For vehicles manufactured in 2010 and after, the trade-in allowance is $5000.00, irrespective of the state of initial registration.
if (vehiclesYear <= 1999 || vehiclesYear >= 1990
& (stateNames.getSelectedItem() == "IL")
|| (stateNames.getSelectedItem() == "IN")
|| (stateNames.getSelectedItem() == "IA")
|| (stateNames.getSelectedItem() == "KS")
|| (stateNames.getSelectedItem() == "MI")
|| (stateNames.getSelectedItem() == "MN")
|| (stateNames.getSelectedItem() == "MO")
|| (stateNames.getSelectedItem() == "NE")) {
tradeIn = 3000.00;
} else {
tradeIn = 2750.00;
}
if (vehiclesYear >= 2000
& (stateNames.getSelectedItem() == "IL")
|| (stateNames.getSelectedItem() == "IN")
|| (stateNames.getSelectedItem() == "IA")
|| (stateNames.getSelectedItem() == "KS")
|| (stateNames.getSelectedItem() == "MI")
|| (stateNames.getSelectedItem() == "MN")
|| (stateNames.getSelectedItem() == "MO")
|| (stateNames.getSelectedItem() == "NE")
|| (stateNames.getSelectedItem() == "ND")
|| (stateNames.getSelectedItem() == "OH")
|| (stateNames.getSelectedItem() == "SD")
|| (stateNames.getSelectedItem() == "WI")) {
tradeIn = 3250.00;
} else {
tradeIn = 3000.00;
}
if (vehiclesYear >= 2010) {
tradeIn = 5000.00;
}

let us walk through your code.
if you want to have a between check
change following
if (vehiclesYear <= 1999 || vehiclesYear >= 1990)
to
if (vehiclesYear <= 1999 && vehiclesYear >= 1990)
also i suggest you define a String variable and assign it to stateNames.getSelectedItem()
like
String item = stateNames.getSelectedItem();
and use this item for comparison
also as it is a string i suggest you to use .equals() method for comparison than == to avoid reference comparison issue
also for comparison you can implement method using switch(item) java 7 and above will support the same
like
switch (item)
{
case "IL":
case "IN":
.
.
case "KS":
return true;//or do something here
break;
}

One main problem is that you're comparing Strings using the == operator, which is not guaranteed to give the expected result.
In Java, Strings are objects, and the == operator compares for object reference equality.
So if I do
String myString = "Foo";
if (myString == "Foo") {
System.out.println("They are the same");
} else {
System.out.println("They are not the same");
}
the results are not guaranteed. To compare Strings for equality, use the String.equals(String) method.
On a more stylistic note, I would probably have inserted the state codes into separate Set<String> instances like so:
private boolean isInTheNineties(int year) {
return year >= 1990 && year <= 1999;
}
private double getTradeIn(int vehiclesYear, SomeClass stateNames) {
Set<String> s0 = new HashSet<>();
s0.addAll(Arrays.asList("IL", ... , "NE"));
String registrarState = stateNames.getSelectedItem();
if (isInTheNineties(vehiclesYear)) {
if (s0.contains(registrarState)) {
return 3000.00;
} else {
return 2750.00;
}
}
// And so on for the 2000s
}
Also, the Why not use Double or Float to represent currency? question seems relevant here.

Currently any year satisfies the following condition:
if (vehiclesYear <= 1999 || vehiclesYear >= 1990)
This is because every year is either before 1999 or after 1990.
If you want the years between 1999 and 1990 then you need to do this:
if (vehiclesYear <= 1999 && vehiclesYear >= 1990)

I'm not completely sure about this, but you might have to put the "tradein=3000.00;" inside of a block to get it to work out. {} after your 'if' statement and before your 'else' statement, everything should be surrounded in a block, this might alter and fix your problem!

Related

How to handle bad input

I'm trying to write a code that determines whether two inputs of DNA sequences are reverse compliments or not. The program asks the user to provide the sequences as a string.
I have the code executing properly but I want to write a single if statement that continues the program if the characters are all 'A' 'T' 'C' or 'G'.
This is what i came up with on my own, but it doesnt work, and it doesn't even look close. I'm new to the language and come from ADA and am just stumped any help would be great.
if ( seqFirst.charAt(i) != 'A' || seqFirst.charAt(i) != 'T' ||
seqFirst.charAt(i) != 'C' || seqFirst.charAt(i) != 'G' ||
seqSecond.charAt(i) != 'A' || seqSecond.charAt(i) != 'T' ||
seqSecond.charAt(i) != 'C' || seqSecond.charAt(i) != 'G' )
You simply need to change || to && throughout the conditional expression.
By way of an explanation, consider this simplified version of your code:
if (c != 'A' || c != 'T' ) { // IS BAD }
and consider the case where c is 'A'. The first predicate evaluates to false. The second predicate evaluates to true. The entire expression is false || true ... which is true ... "BAD"
Now change the || to && and you get false && true ... which is false ... "NOT BAD"
I'm new to the language and come from ADA ...
That's not the real problem. The problem is understanding how boolean algebra works; i.e. DeMorgan's Laws.
As i know, 2 DNA string are reverse compliments when one of these equals to another, but reversed and with changed nucleotides. Since i dont know your version of Java, i wrote some readable method in Java7:
public static boolean isComplimentaryReverse(String str1, String str2) {
//invalid input, could throw exception
if (str1.length() != str2.length()) {
return false;
}
//could be static final field
Map<Character, Character> replaceTable = new HashMap<>();
replaceTable.put('G', 'C');
replaceTable.put('C', 'G');
replaceTable.put('T', 'A');
replaceTable.put('A', 'T');
String reverseStr1 = new StringBuilder(str1).reverse().toString();
for (int i = 0; i < str2.length(); i++) {
//invalid input, could throw exception
if (!replaceTable.containsKey(reverseStr1.charAt(i))) {
return false;
}
if (str2.charAt(i) != replaceTable.get(reverseStr1.charAt(i))) {
return false;
}
}
return true;
}
Simplify with a regular expression.
private static final String VALID_DNA = "[ATCG]+";
...
if (seqFirst.matches(VALID_DNA) && seqSecond.matches(VALID_DNA)) {
// keep going...
}
I'm seeing a possible De Morgan's Law issue. Remember !(a or b) = !a and !b.

Improve my validation

When the user enters their ID I want it to be in a specific format, they are mostly explained within the comments. I was wondering if their was an easier more efficient way of doing this. Also whether or not there is a way to change the entered letters to capital the way I've done the code, or any other method.
private boolean setCustomerID(String id) {
//Validates the customerID contains 3 letters a hypthen then 4 numbers
if ((id.charAt(0) < 'A' || id.charAt(0) > 'Z')
|| (id.charAt(1) < 'A' || id.charAt(1) > 'Z')
|| (id.charAt(2) < 'A' || id.charAt(2) > 'Z')
|| (id.charAt(3) != '-')
|| !isDigit(id.charAt(4))
|| !isDigit(id.charAt(5))
|| !isDigit(id.charAt(6))
|| !isDigit(id.charAt(7))) {
return false;
//Checks the user enters P, B or C for first letter
} else if ((id.charAt(0) == 'P' || id.charAt(0) == 'B' || id.charAt(0) == 'E')
//Checks the second and third letter are in the correct region
&& ((id.charAt(1) == 'S' && id.charAt(2) == 'C')
|| (id.charAt(1) == 'S' && id.charAt(2) == 'C')
|| (id.charAt(1) == 'W' && id.charAt(2) == 'A')
|| (id.charAt(1) == 'N' && id.charAt(2) == 'I')
|| (id.charAt(1) == 'N' && id.charAt(2) == 'E')
|| (id.charAt(1) == 'N' && id.charAt(2) == 'W')
|| (id.charAt(1) == 'M' && id.charAt(2) == 'I')
|| (id.charAt(1) == 'E' && id.charAt(2) == 'A')
|| (id.charAt(1) == 'S' && id.charAt(2) == 'E')
|| (id.charAt(1) == 'S' && id.charAt(2) == 'W'))){
// SC (Scotland), WA (Wales), NI (Northern Ireland), NE (North-East), NW (North-West),
//MI (Midlands), EA (East Anglia), SE (South-East), SW (South-West).
return true;
}
return false;
}
Use regex.
private boolean matchCustomerID(String id) {
return id.matches("^[PBE](?:SC|WA|NI|NE|NW|MI|EA|SE|SW)-\\d{4}\\b");
}
Regular expressions are one way of solving the problem. You can compose the pattern in a way that makes maintenance easier. Building on rcorreia's pattern, you can do something like:
private boolean setCustomerID(String id) {
char[] validFirstLetters = { 'P', 'B', 'E' };
String[] validRegions = { "SC", "WA", "NI", "NE", "NW", "MI", "EA", "SE", "SW" };
String pattern =
String.format("^[%s](?:%s)-\\d{4}$", new String(validFirstLetters),
String.join("|", validRegions));
return id.matches(pattern);
}
Note that this uses String.join() from Java 8. If you don't use Java 8 yet, consider using StringUtils from Apache Commons Lang.
Regexp is a great feature, but not easy to write and understand..
In this case, I would follow your way, but I would define some testing method. In this manner the code will be readable and easy to write Unit tests for it.
If you need some change later, you will understand the code.
Example:
testForLength();
testForLetters();
testForFirstTwoLetters();

How to check if a string at a certain position contains character a-h?

I know there must be a simpler way to check, but this is what I'm doing right now.
if (g.charAt(0) == 'a' || g.charAt(0) =='b' || g.charAt(0) =='c' ||
g.charAt(0) == 'd' || g.charAt(0) =='e' || g.charAt(0) =='f' ||
g.charAt(0) == 'g' || g.charAt(0) =='h')
Relying on character ordering and that a..h is a consecutive range:
char firstChar = g.charAt(0);
if (firstChar >= 'a' && firstChar <= 'h') {
// ..
}
Use a regular expression for this one. Cut the first character of your String as a substring, and match on it.
if(g.substring(0, 1).matches("[a-h]") {
// logic
}
A variation on hemanth's answer:
if("abcdefgh".contains(g.substring(0,1))) do_something();
or
if("abcdefgh".indexOf(g.charAt(0)) >= 0) do_something();
Another way of doing it :
if(Array.asList("abcdefgh".toCharArray()).contains(g.charAt(0)))
{
//Logic
}

Multiple conditions in a while loop

import java.util.Calendar;
import java.util.GregorianCalendar;
public class CountingSundays {
public static void main(String args[]) {
Calendar cal = new GregorianCalendar(1901, 00, 01); // month set to 0for jan , 1= feb etc
while((cal.get(Calendar.YEAR) != 2001) && (cal.get(Calendar.MONTH) != 0) && cal.get(Calendar.DAY_OF_MONTH) != 1) { // while not 1/1/2001
System.out.print(cal.get(Calendar.MONTH));
// cal.add(Calendar.DAY_OF_MONTH, 1);
}
}
}
Im trying to iterate through the while loop by adding on a day at a time but it wont even access the while loop the first time. Are the conditions in the while loop right? When i tested it it worked with just one condition but stopped when i added the second condition.
It should be
while( !(cal.get(Calendar.YEAR) == 2001 && cal.get(Calendar.MONTH) == 0 && cal.get(Calendar.DAY_OF_MONTH) == 1) ) { // while not 1/1/2001
This is just a simple logic error. If even one of those is false (say, if the month IS 0), then you have true && false && true, which is false.
You need the "not" outside of the entire expression, or you need to use "||" to combine them:
while( !(year == 2001 && month == 0 && day == 1) )
or
while( (year != 2011) || (month != 0) || (day != 1) )

non printable characters in java

Please, can you give me a list of non printable characters in java programming? Thank you in advance.
Java uses the Unicode standard, so you should be asking about non-printable (non-printing?) characters in Unicode.
http://en.wikipedia.org/wiki/Unicode_control_characters
Java strings are unicode strings. Unicode doesn't have a concept of "non-printable" characters, exactly, but the ASCII non-printable range, along with several other characters, are considered Unicode control characters.
Are spaces printable? What about the private use area? Please modify the code to your definition of "printable" :)
import static java.lang.Character.*;
for (int i=0; i<MAX_CODE_POINT; i++) {
int t = getType(i);
boolean p = t == CONTROL || t == CONNECTOR_PUNCTUATION || t == CURRENCY_SYMBOL || t == DASH_PUNCTUATION || t == DECIMAL_DIGIT_NUMBER || t == ENCLOSING_MARK || t == END_PUNCTUATION || t == FINAL_QUOTE_PUNCTUATION || t == INITIAL_QUOTE_PUNCTUATION || t == LETTER_NUMBER || t == LOWERCASE_LETTER || t == MATH_SYMBOL || t == MODIFIER_LETTER || t == MODIFIER_SYMBOL || t == OTHER_LETTER || t == OTHER_NUMBER || t == OTHER_PUNCTUATION || t == OTHER_SYMBOL || t == START_PUNCTUATION || t == TITLECASE_LETTER || t == UPPERCASE_LETTER;
if (!p) {
System.out.println("Non printable codepoint " + i);
}
}

Categories