Is it possible to have a statement such as...
if(delco == 1 && heavy < 5)
System.out.println("The total cost of your delivery is: $" + OPT_ONE);
if(delco == 1 && heavy >= 5 && heavy <= 20)
System.out.println("The total cost of your delivery is: $" + OPT_TWO);
...that also applies boolean logic to express an output? Something like this...
boolean overnight;
if(delco == 1 && heavy < 5) && (overnightShip == YES)
System.out.println("The total cost of your delivery is: $" + OPT_ONE + OVERNIGHT);
if(delco == 1 && heavy >= 5 && heavy <= 20) && (overnightShip == NO)
System.out.println("The total cost of your delivery is: $" + OPT_TWO);
I have tried a few variations of this code and the error I'm receiving states that they are incomparable types. How do I go about making them comparable?
You just missed some parentheses, because your logic seems OK. It should be, e.g.:
if ( (delco == 1 && heavy < 5) && (overnightShip == YES) )
...
Note the outer parentheses.
Also that assumes that you've defined YES to be a boolean constant equal to true, and that is redundant, so:
if ( (delco == 1 && heavy < 5) && (overnightShip) )
...
And in this case, those parentheses are redundant as well, and the whole thing simplifies to:
if ( delco == 1 && heavy < 5 && overnightShip )
...
Just use the boolean on its own:
if (delco == 1 && heavy < 5 && overnightShip)
Comparing a boolean "flag" variable with a boolean constant is poor style - always prefer testing the boolean as-is.
Boolean types in Java have the values:
true
false
Not:
YES
NO
unless you have defined these constants yourself somewhere
So your code should look like:
(overnightShip == true)
(overnightShip == false)
or even:
(overnightShip) // true
(! overnightShip) // false
Related
What I need to do is write a program that makes the first character (which is charAt(0) )and the second character (which is charAt(1) ) to become a value that not exceeding 90 which is (0 ~ 90) , but I also have to define them as an independent digit , because my program will make it to invalid if it is other than a digit.
So for an example it will become invalid if I type in 91
and it will valid if I type in number between 0~90
but I have no idea how to do this...
if(Character.isDigit(loop1.charAt(0))&&
Character.isDigit(loop1.charAt(1)))
I have tried this ,but not working
if(Character.isDigit(loop1.charAt(0)) &&
Character.isDigit(loop1.charAt(1)) &&
((loop1 >= 0)&&(loop1 <= 90)))
also this one but this is not working( I have no idea what I'm doing)
if(Character.isDigit(loop1.charAt(0)) &&
(((int)loop1.charAt(0)) >= 0) && <=9
Character.isDigit(loop1.charAt(1)) &&
((int)loop1.charAt(1)) <= 9)
Please help me... thanks a million !
Assuming I understand your question, parse loop1 and test the values using a simple if check, like
int t = Integer.parseInt(loop1);
if (t < 0 || t > 90) {
System.out.println("Value outside accepted range.");
} else {
System.out.println("Value valid.");
}
If I am getting this right you want to convert the first two characters of a string into a number and check is that number bigger than 90. Also you want the digits to be stored in different variables(?). If so this code should do it:
int digit1 = loop1.charAt(0) - '0';
int digit2 = loop1.charAt(1) - '0';
int number = digit1 * 10 + digit2;
if ( number <= 90 && number >= 0 )
System.out.println("Input is good");
else
System.out.println("Input is bad");
I am making a counter between number ranges and not sure the correct way to do this. I have always used the || operator but reading some examples, I feel I should be using the && command. Here is my example problem...
if(value >= 1 || value <=10){
count1++;
}
else if(value >= 11 || value <= 20){
count2++;
// AND SO ON........
Or should I be using the && operator like
if(value >= 1 && value <= 10){
count1++;
}
else if value >= 11 && value <= 20){
count2++;
}
|| means "or".
&& means "and".
value >= 1 || value <= 10 makes no sense because it's always true. All numbers are 1 or more, or 10 or less. Some numbers are both, but that doesn't matter.
value >= 1 && value <= 10 makes far more sense. There's a limited range of numbers ([1..10]) for which both the first condition and the second condition are true.
|| is the or operator, so the condition value >= 1 || value <=10 is true for all values if you think about it. So, unless you want your counts to be meaningless, use && which is the and operator.
I am new to programming and wanted to make a dice rolling programm in Java for execise.
The code is the following:
import java.math.*;
public class Dices {
public static int dice1=0;
public static int dice2=0;
public static int x;
public static void main(String args[]){
do {
x++;
dice1=(int) (Math.random()*6+1);
dice2=(int) (Math.random()*6+1);
System.out.println(dice1+", "+dice2);
} while(dice1 !=1 || dice2 !=1);
System.out.println("Finalthrow: "+dice1+", "+dice2);
System.out.println("Snake-Eyes after "+x+" tries.");
}
}
This way it works fine, but in my opinion there is something wrong with the code. In the while condition should actually be. But if I use && it stops as soon as it rolls a 1 on the first dice. I thought && means "AND" and || means "OR". So actually it should behave exactly the other way around, or am I misinterpreting something?
Some understanding about Morgan's laws could help here. The law says (sorry for the weird syntax, but I think the message is clear) that :
(!P) OR (!Q) == !(P AND Q)
(!P) AND (!Q) == !(P OR Q)
So when you use || (OR) in your condition
while(dice1 !=1 || dice2 !=1)
is exactly the same as
while(!(dice1 == 1 && dice2 == 1))
so it will looop until both dice are 1.
On the other hand, if you use && (AND):
while(dice1 !=1 && dice2 !=1)
it's the same as
while(!(dice1 == 1 || dice2 == 1))
so it means that it will loop until one or two of the dice is/are 1.
&& means and
|| means or
So (dice1 != 1 || dice2 != 1) means continue the loop while dice1 is not 1 or dice 2 is not 1.
So (dice1 != 1 && dice2 != 1) means continue the loop while dice1 is not 1 and dice 2 is not 1.
The code is fine. You want the loop to end when dice1 == 1 and dice2 == 1. So it must loop until that is true, or until its opposite is false. The opposite of dice1 == 1 && dice2 == 1 is !(dice1 == 1 && dice2 == 1) which is equivalent to dice1 != 1 || dice2 != 1.
Think of it this way: if dice1 != 1, keep looping. Also, if dice2 != 1, keep looping. So if either is true, keep looping. And to test if either is true, regardless of if both are true, use ||.
The behavior is wright. You're saying with dice1 !=1 && dice2 !=1 that repeat the loopuntil BOTH of the dices are NOT 1. But when one dice rolls a 1 the condition is false and the loop escapes. Try it with a truth table.
Let's make a truth table.
What can we conclude from this? If you want your loop to continue while either A or B are different from 1 (or, as De Morgan's laws say: until both of them are equal to 1) then you can narrow it down to these values:
Since we need to find the operator that allows us to continue the loop (aka: the condition is true), we take the column that returns true for all 3 different kinds of inputs, which is A || B.
Note that A && B and A || B refer to the result of A != 1 and B != 1, not the actual input.
I am creating a program that asks the user for several integers and one of the statements ask the user "Enter an integer that is negative and even or positive and odd". How exactly would I go about setting up such a question? I have this so far. I have no idea how exactly I should do this, as my instructions are pretty confusing. This is what the question is for my problem:
4.
Ask the user for an integer that is either negative and even or positive
and odd. Use an if statement and compound conditional.
import java.util.Scanner;
public class ExerciseFour
{
public static void main ( String[] argsv )
{
int choice;
int choiceTwo;
int choiceThree;
Scanner input = new Scanner(System.in);
System.out.println( "Enter a number between 0 and 10" );
choice = input.nextInt();
if ( choice > 0 && choice < 10 )
{ System.out.println( "Valid number" );
}
else
{ System.out.println( "Invalid number" );
return;
}
System.out.println( "Enter a number divisible by 2 or 3?" );
choiceTwo = input.nextInt();
if ( choiceTwo % 2 == 0 && choiceTwo % 3 == 0 )
{ System.out.println( "Valid number" );
}
else
{ System.out.println( "Number not divisible by 2 or 3" );
return;
}
System.out.println( "Enter an integer that is negative and even or positive and odd (Ex. -2 or 7 )" );
choiceThree = input.nextInt();
if ( choiceThree )
{
}
else
{
}
((choiceThree > 0) && (choiceThree % 2 == 1)) || ((choiceThree < 0) && (choiceThree % 2 == 0))
The above is the compound condition you're looking for, which means:
(
(choiceThree > 0) //positive number / greater than zero
&& // AND
(choiceThree % 2 == 1) //odd number: (an odd number divided by two has a remainder of 1)
)
|| // OR
(
(choiceThree < 0) //negative number / less than zero
&&
(choiceThree % 2 == 0) //even number (an even number divided by two has a remainder of 0)
)
EDIT: % is the modulo operator.
The result of a % b is the remainder of the integer division a / b.
The key is to use The modulo operator. An even number is divisible by 2 with no remainder. So:
if (choiceThree < 0) {
if (choiceThree % 2 == 0) {
System.out.println ("Valid");
} else {
System.out.println ("Invalid");
}
} else {
if (choiceThree % 2 != 0) {
System.out.println ("Valid");
} else {
System.out.println ("Invalid");
}
}
This is a bit cumbersome, of course. A more elegant way to express this boolean logic would be by using the exclusive or (xor) operator. This operator returns true if one and only one of its operands evaluate to true:
if (choiceThree > 0 ^ choiceThree % 2 == 0) {
System.out.println ("Valid");
} else {
System.out.println ("Invalid");
}
I think there is a mistake in the second question
choiceTwo % 2 == 0 && choiceTwo % 3 == 0
you may want to write || instead of && becouse you sad devisible to 2 OR 3 ;-)
For your other problem: You have two boolean expressens wich may be true:
Ask the user for an integer that is either negative and even
(choiceThree < 0 && choiceThree % 2 == 0)
or positive and odd.
(choiceThree > 0 && choiceThree % 2 == 1)
Use an if statement and compound conditional.
So just combine these to statements with a logical OR (||)
Create a method that returns true if it's one of those scenarios:
public boolean isCorrectInteger(int number){
if ((number < 0) && (number % 2 == 0)) { //negative and even
return true;
} else if((number < 0) && (number % 2 == 1)) { // positive and odd
return true;
} else { // other cases
return false;
}
}
This can be written in a one bigger condition, I've just split it into two for the sake of a simple example.
Also take into consideration that zero is currently assigned neither to positive nor negative - you can change this as you please by using the <= or >= operators.
Try this:
System.out.println( "Enter an integer that is negative and even or positive and odd (Ex. -2 or 7 )" );
choiceThree = input.nextInt();
if ( (choiceThree>0 && choiceThree%2==1) || (choiceThree<0 && choiceThree%2==0) )
{
System.out.println("Correct");
}
else
{
System.out.printlnt("ERROR");
}
A programming + Statistics Question:
Context:
I am currently building a model simulation (an agent-based model) where each agent (read: person) as a series of variables (i.e. gender, race, martial status, income bracket, education, etc).
This is not a homework question, it's a problem I am trying to solve for work so I do not have to hard code everything, and will make implementing changes to my model much easier and faster.
The variables essentially break down as follows:
gender: 0 = female, 1 = male
race: 1 = white, 2 = black, 3 = hispanic, 4 = other
marital status: 1 = married, 2 = divorced, 3 = no married
income: 1 = <20k, 2 = 20k-75k, 3= 75+k
education: 1 = <HS, 2 = HS, 3 = >HS
In my dataset I want to predict, for example, smoking status (0 = non-smoker, 1 = smoker).
Easy, do a logistic regression. Programming in the main effects would not be too difficult since the population model would be as follows:
SmokingStatus = b_0 + b_1(gender1) + b_2(race2) + b_3(race3) + b_4(race4) + ... + e
Problem 1:
As you can see from the equation above, categorical variables create k-1 dummy variables. Essentially the stats program will create the following dummy variables (using race as an example): race2, race3, race4. and each will have a beta estimate (that is the ln(OR) relative to the reference group, race1).
Question 1:
How would I write my java program to calculate the probability of smoking status from the regression output (the tables I have are SAS ouputs), without creating the corresponding dummy variables in my agent class.
Problem 2:
This problem gets even worse when I have interaction terms in my model, since the parameter estimates are the combinations of each variable's dummy-variable. For example, in above population model + an interaction term between gender and race would be:
SmokingStatus = b_0 + b_1(gender1) + b_2(race2) + b_3(race3) + b_4(race4) + B_5(gender1race2) + B_6(gender1race3) + B_7(gender1race4) ... + e
Question 2:
Given this added complexity, what would be the best approach?
My ultimate goal:
I am trying to write a java program that will take in a (csv) file of variables and their parameter estimates, and essentially 'plug in the values' to generate a probability for my response variable (e.g. smoking status).
Yes I know after I plug in all the values I will have to transform my answer via:
Math.exp(logitP)/(1 + Math.exp(logitP))
My current (and terrible) solution involves initializing all the dummy variables to 0, then doing a series of if statements to assign a value of 1, then multiplying all the dummies by the corresponding beta estimate (many of the terms will equate to 0)
for example:
int race2 = 0;
int race3 = 0;
int race4 = 0;
int sex0 = 0;
// race
if (alcoholAgent.getRace() == 2) {race2 = 1;}
else if (alcoholAgent.getRace() == 3) {race3 = 1;}
else if (alcoholAgent.getRace() == 4) {race4 = 1;}
// sex female is reference group == 0
if (alcoholAgent.getGender() == 1) {sex0 = 1;}
// age2-6_race2-4
if ((alcoholAgent.getAgeCat() == 2) && (alcoholAgent.getRace()==2)) {age2race2 = 1;}
else if ((alcoholAgent.getAgeCat() == 2) && (alcoholAgent.getRace()==3)) {age2race3 = 1;}
else if ((alcoholAgent.getAgeCat() == 2) && (alcoholAgent.getRace()==4)) {age2race4 = 1;}
else if ((alcoholAgent.getAgeCat() == 3) && (alcoholAgent.getRace()==2)) {age3race2 = 1;}
else if ((alcoholAgent.getAgeCat() == 3) && (alcoholAgent.getRace()==3)) {age3race3 = 1;}
else if ((alcoholAgent.getAgeCat() == 3) && (alcoholAgent.getRace()==4)) {age3race4 = 1;}
else if ((alcoholAgent.getAgeCat() == 4) && (alcoholAgent.getRace()==2)) {age4race2 = 1;}
else if ((alcoholAgent.getAgeCat() == 4) && (alcoholAgent.getRace()==3)) {age4race3 = 1;}
else if ((alcoholAgent.getAgeCat() == 4) && (alcoholAgent.getRace()==4)) {age4race4 = 1;}
else if ((alcoholAgent.getAgeCat() == 5) && (alcoholAgent.getRace()==2)) {age5race2 = 1;}
else if ((alcoholAgent.getAgeCat() == 5) && (alcoholAgent.getRace()==3)) {age5race3 = 1;}
else if ((alcoholAgent.getAgeCat() == 5) && (alcoholAgent.getRace()==4)) {age5race4 = 1;}
else if ((alcoholAgent.getAgeCat() == 6) && (alcoholAgent.getRace()==2)) {age6race2 = 1;}
else if ((alcoholAgent.getAgeCat() == 6) && (alcoholAgent.getRace()==3)) {age6race3 = 1;}
else if ((alcoholAgent.getAgeCat() == 6) && (alcoholAgent.getRace()==4)) {age6race4 = 1;}
Any model which makes use of the numerical values of categorical variables is misleading at best. In what sense is race=2 "greater than" race=1? In no sense, of course. My advice is to dump the logistic regression.
Since there is no real ordering of the categorical variables, the best you can do is a look-up table. Just make a multidimensional table indexed by the categorical variables, and count up examples which fall into each bin in the table to find the proportional of examples in each output category. That proportion is your probability of the output category for that combination of input variables.
A look-up table takes all interactions of variables into account. The disadvantage is that the number of table elements may be very large. You may be able to compute the probability of the output category as a product of probabilities from smaller tables (i.e., with fewer indices per table). This is what is called a "naive Bayes" model; it makes an assumption that input variables (or groups of them) are independent given the output category.