This program enters in a temperature and based on the temperature a message is outputted. My program is getting stuck tempOutside <= 50 message.. When I enter -10 the output is "Time to turn on the heat". I cannot use && as this is an assignment questions and we have not used this concept.
if (tempOutside > 50)
System.out.println("Enjoy the weather");
else if (tempOutside <= 50)
System.out.println("Time to turn on the heat");
else if (tempOutside <= 30)
System.out.println("Check the gas in you car before leaving");
else if (tempOutside <= -10)
System.out.println("BUNDLE UP it's \"COLD\" outside ");
else
1) if-else must be in numerical order (hi to low)
2) Default must be coded
3) Repeat the code, but reverse the order(low to hi)
All ints are either > 50 or <= 50. The first two conditions match everything.
Change the second condition to
> 30
And the third condition to
> -10
Etc.
it would have been more clear if you could have mentioned your exact question directly and then your implementation as it looks like there could be a misunderstanding of the question here.
But I think perhaps this is what is being asked here??
if (tempOutside > 50)
{
System.out.println("Enjoy the weather");
}
else if (tempOutside <= 50)
{
if(tempOutside <= 30)
{
if(tempOutside <= -10)
{
System.out.println("BUNDLE UP it's \"COLD\" outside ");
}
else {
System.out.println("Check the gas in you car before leaving");
}
}
else
{
//when the temp is between 30 and 50
System.out.println("Time to turn on the heat");
}
}
Related
I have a little issue, my code prints the if(RanNum >= 4) and if(RanNum >=8 ) together, but I just want to print (RanNum >=8), I want to put a limit between then, but I don't know how, thank's in advance!
int Min = 1;
int Max = 10;
int RanNum = Min + (int)(Math.random() * (Max - Min) );
System.out.println(RanNum);
if(RanNum <= 3){
System.out.println("hello");
}
if(RanNum >= 4 ){
System.out.println("four four four four four");
}
if(RanNum >= 8){
System.out.println("here it is");
}
You have an issue with your logic. For example if RanNum is greater than 8 then it will also be greater than 4. Use else if you want a branch of code that only runs when the if condition is not satisfied.
Use if else and re order the conditions
if(RanNum <= 3){
System.out.println("hello");
}else if(RanNum >= 8 ){
System.out.println("here it is");
}
else{
System.out.println("four four four four four");
}
I am creating a guessing-game program where the user must enter a number between 1 and 100 and try and guess the 'magic number'.
I am trying to add a 'hint' feature where depending on how close the users guess was to the random number chosen by the computer, a message will appear displaying messages such as:
Freezing—more than 50 away.
Cold—more than 25 away.
Cool—more than 15 away.
Warm—more than 10 away.
Hot—more than 5 away.
Boiling—between 1 and 4 away.
Unfortunately when I enter a number and press the button "GUESS", the wrong 'hint' shows up for the number guessed. Specifically, "Boiling! Between 1 and 4 away!"
However, when I enter the exact 'Magic Number', the correct text shows up. ""YOU GOT IT! " (the magic number) " is the magic number!"
In order for me to see what the 'Magic Number' is each time, I have added a line of code that I will remove later.
FYI: This is for a school project, and my teacher added this hint to the assignment:
In the Math class, there is a method that you can use to find the absolute (positive) value of a number. You will need to use this method to help you determine how far the guess is from the secret number. This will allow you to determine which message you should report for a hint. Sample code below:
int numAbsolute = Math.abs(num);
System.out.println(num); // output: -12
System.out.println(numAbsolute); // output: 12
Also, you will need to set up two conditional control structures to produce the two different messages (one from the basic assignment and one for the enrichment). You can join the two messages to form one message using the concatenate operator (+) and display the concatenated message in a text field.
Here is my conditional control structure code:
public class GuessingGame extends javax.swing.JFrame {
//Create the random number between 1 & 100
int randNum = (int)Math.ceil(Math.random()*100);
int numAbsolute = Math.abs(randNum);
And the rest of my code:
private void guessButtonActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("Secret number is " + randNum); // to be removed later
int input;
input = Integer.parseInt (guessInput.getText());
if (input == randNum)
{
guessOutput.setText("YOU GOT IT! " + randNum + " is the magic number!");
}
else if (input - randNum + numAbsolute > 1)
{
guessOutput.setText("Boiling! Between 1 and 4 away!");
}
else if (input - randNum + numAbsolute > 5)
{
guessOutput.setText("Hot! More than 5 away!");
}
else if (input - randNum + numAbsolute > 15)
{
guessOutput.setText("Cool: More than 15 away.");
}
else if (input - randNum + numAbsolute > 10)
{
guessOutput.setText("Warm! More than 10 away!");
}
else if (input - randNum + numAbsolute > 25)
{
guessOutput.setText("Cold: More than 25 away.");
}
else if (input - randNum + numAbsolute > 50)
{
guessOutput.setText("Sheesh, Freezing: more than 50 away.");
}
}
Any help would be greatly appreciated!
if you want - you can change the sequence of if-else execution.
Now you started at
if (input - randNum + numAbsolute > 1){
guessOutput.setText("Boiling! Between 1 and 4 away!");
}
and this condition is always true.
As an option, you can start
if (input - randNum + numAbsolute > 50){
guessOutput.setText("Sheesh, Freezing: more than 50 away.");
}else if (input - randNum + numAbsolute > 25){
guessOutput.setText("Cold: More than 25 away.");
}
and so on...
Because randNum is a positive number, numAbsolute will be equal to randNum.
That of course means that input - randNum + numAbsolute will always be equal to input. And unless input is equal to zero, then it will always be larger than 1. So the first else if will always be true, and the rest won't be checked.
I believe that the purpose is to take the difference between the input and the randNum, and get the absolute value of that:
numAbsolute = Math.abs(input - randNum);
Then you need to consider the order in which you do the checks. If the absolute difference is larger than 5, then it's also larger than 1. So you need to reverse the order you check:
if (input == randNum) { ... }
else if (numAbsolute > 50) { ... }
else if (numAbsolute > 25) { ... }
else if (numAbsolute > 15) { ... }
else if (numAbsolute > 10) { ... }
else if (numAbsolute > 5) { ... }
else if (numAbsolute > 1) { ... }
You have made a logical mistake. Let's analyze the following condition:
else if (input - randNum + numAbsolute > 1)
{
guessOutput.setText("Boiling! Between 1 and 4 away!");
}
If input - randNum + numAbsolute = 2, it will become true.
If input - randNum + numAbsolute = 6, it will become true.
If input - randNum + numAbsolute = 15, it will become true.
and so on...i.e. it will cover all numbers greater than 1.
In other words, this condition will not allow the following other conditions to be executed:
else if (input - randNum + numAbsolute > 5)
{
guessOutput.setText("Hot! More than 5 away!");
}
else if (input - randNum + numAbsolute > 15)
{
guessOutput.setText("Cool: More than 15 away.");
}
else if (input - randNum + numAbsolute > 10)
{
guessOutput.setText("Warm! More than 10 away!");
}
else if (input - randNum + numAbsolute > 25)
{
guessOutput.setText("Cold: More than 25 away.");
}
else if (input - randNum + numAbsolute > 50)
{
guessOutput.setText("Sheesh, Freezing: more than 50 away.");
}
How to solve it?
Rearrange your conditions in reverse order i.e.
if (input == randNum)
{
guessOutput.setText("YOU GOT IT! " + randNum + " is the magic number!");
}
else if (input - randNum + numAbsolute > 50)
{
guessOutput.setText("Sheesh, Freezing: more than 50 away.");
}
else if (input - randNum + numAbsolute > 25)
{
guessOutput.setText("Cold: More than 25 away.");
}
//...
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
This is a simple class exercise I'm working on. (I'm very new to programming so if this was a simple 'rookie' mistake I apologize for wasting your time.) I'm not going to lie: I'm finding it difficult to know where to insert certain pieces of code when programming.
import java.util.*;
public class SuperSaveRandallTWyngaardC {
static Scanner console=new Scanner(System.in);
public static void main(String[] args) {
char newCust;
char promo;
int itemNr=0;
int qty=0;
int price=0;
int totalPrice=0;
int custTot=0;
int noOfItems=0;
int grandTot=0;
int custCount=0;
System.out.println(" ");
System.out.println("*******SuperSave - your friendly local store.....*******");
System.out.println(" ");
System.out.print("New customer? (Y/N)>> ");
newCust=console.next().charAt(0);
newCust=Character.toUpperCase(newCust);
while((newCust!='Y')&&(newCust!='N'))
{
System.out.print("Invalid option, please re-enter (Y/N)>> ");
newCust=console.next().charAt(0);
newCust=Character.toUpperCase(newCust);
}
if (newCust == 'N')
{
System.out.println("*******NO SALES THE WHOLE DAY.....*******");
}
else if (newCust == 'Y')
{
System.out.print("Please enter the item number (1000 -> 5000 or zero for none)>> ");
itemNr=console.nextInt();
while ((itemNr<1000)&&(itemNr>5000)||(itemNr!=0))
{
System.out.print("Invalid item number, please re-enter (1000 -> 5000 or zero to stop)>> ");
itemNr=console.nextInt();
}
if (itemNr==0)
{
System.out.println("*******NO ITEMS WERE BOUGHT BY THIS CUSTOMER.....*******");
}
else if ((itemNr>1000)&&(itemNr<5000))
{
System.out.print("Enter quantity>> ");
qty=console.nextInt();
}
}
}
}
Run the program. Sample output...
*******SuperSave - your friendly local store.....*******
New customer? (Y/N)>> y
Please enter the item number (1000 -> 5000 or zero for none)>> 1000
Invalid item number, please re-enter (1000 -> 5000 or zero to stop)>> 5000
Invalid item number, please re-enter (1000 -> 5000 or zero to stop)>> 999
Invalid item number, please re-enter (1000 -> 5000 or zero to stop)>> 5001
Invalid item number, please re-enter (1000 -> 5000 or zero to stop)>> 1234
Invalid item number, please re-enter (1000 -> 5000 or zero to stop)>> 4000
Invalid item number, please re-enter (1000 -> 5000 or zero to stop)>> 0
*******NO ITEMS WERE BOUGHT BY THIS CUSTOMER.....*******
The while loop says that any item number input is invalid (even when inside the specified range of 1000-5000)
Your loop condition is off.
Since the negatives seems to confuse, first write what is good:
(itemNr >= 1000 && itemNr <= 5000) || itemNr == 0
I.e. must be between 1000 and 5000 (inclusive), OR must be 0.
Since most people can't get the precedence of && vs || right, you should always use parenthesis to explicitly specify the precedence when mixing them, as I just did.
This makes reversing the expression easy, since you just reverse everything, and leave the parenthesis alone:
(itemNr < 1000 || itemNr > 5000) && itemNr != 0 // correct #1
Compare that to what you had, and you'll see the problem:
(itemNr < 1000) && (itemNr > 5000) || (itemNr != 0) // wrong
Since > 5000 means that it definitely is != 0, you can rearrange the expression like this, as others have shown:
(itemNr < 1000 && itemNr != 0) || itemNr > 5000 // correct #2
Technically, #2 performs better than #1, but that's a difference you will not ever notice. Personally, I find #2 less intuitive than #1, but that's a matter of opinion. They both get you want you want.
(itemNr<1000)&&(itemNr>5000)||(itemNr!=0)
There is no itemNr that makes it true.
Consider -1, 1, 1001, 5001.
((itemNr<1000)&&(itemNr!=0))||(itemNr>5000)
You should try this.
(itemNr < 1000) && (itemNr > 5000) Item number has to be smaller than 1000 AND greater than 5000 at the same time, that is not possible.
You are doing a similar check later with (itemNr > 1000) && (itemNr < 5000).
It would be useful to make a function isInRange(int) that does this check. So you can use !isInRange(itemNr) (not in range) for the first check.
The second check is not needed, since the number will always be in range (or 0) after the while loop.
private static boolean isInRange(int i) {
return ((i > 1000) && (i < 5000));
}
...
while(!isInRange(itemNr) && itemNr != 0) {
...
}
if (itemNr == 0) {
...
} else { // no need to check here
...
}
To correct the check for valid inputs, 1000... 5000 and 0, update
while ((itemNr<1000)&&(itemNr>5000)||(itemNr!=0))
to
while ((itemNr < 1000 && itemNr != 0) || itemNr > 5000)
If 1000 and 5000 are valid inputs, then you have to include them while getting the quantity.
else if ((itemNr>1000)&&(itemNr<5000))
to
else if ((itemNr >= 1000) && (itemNr <= 5000))
So the last block will look like
while ((itemNr < 1000 && itemNr != 0) || itemNr > 5000) {
System.out.print("Invalid item nyumber, please re-enter (1000 -> 5000 or zero to stop)>> ");
itemNr = console.nextInt();
}
if (itemNr == 0) {
System.out.println("*******NO ITEMS WERE BOUGHT BY THIS CUSTOMER.....*******");
} else if ((itemNr >= 1000) && (itemNr <= 5000)) {
System.out.print("Enter quantity>> ");
qty = console.nextInt();
}
NOT ASKING FOR ANYONE TO WRITE THE PROGRAM FOR ME
I am having trouble understanding how to setup the logic for a program given these following conditions:
For every day late up to and including 7 days, the late fee is $0.10/day
After 7 days, for every day late up to and including 90 days, the late fee is $0.20/day.
(Example: a book returned 10 days late incurs a late fee of $1.30 late fee, $0.10 for each of the first 7 days plus $0.20 for each of the remaining 3 days)
This is where I am having issues. I am not sure how to include the previous condition along with this one. My best guess is some sort of nested loop or an elseif containing this condition and something about the last one?
After 90 days, an unreturned book is considered lost. All late fees are waived, but the borrower is charged the cost of the book, plus a $10 restocking fee.
This is my best attempt, but I'm not sure this is the most efficient logic:
if (daysLate > 90)
{
costDue = bookPrice + 10;
}
else if (daysLate <= 90)
{
costDue = (7*0.10) * (daysLate*0.20);
}
else if (daysLate <= 7)
{
costDue = daysLate*0.10;
}
else
{
IO.reportBadInput();
}
The second condition should be changed, otherwise the third if won't be reached. Also the third condition should be changed to check if the daysLate variable is greater or equal to zero:
if (daysLate > 90)
{
costDue = bookPrice + 10;
}
else if (daysLate >= 7)
{
costDue = (7*0.10) + ((daysLate - 7) * 0.20); // change here
}
else if (daysLate >= 0)
{
costDue = daysLate*0.10;
}
else
{
IO.reportBadInput();
}
if (daysLate > 90)
{
costDue = bookPrice + 10;
}
else if (daysLate > 7 && daysLate <= 90)
{
costDue = (7*0.10) * (daysLate*0.20);
}
else
{
costDue = daysLate*0.10;
}
Simply update the second clause and drop that last one, that'll straighten it out.
addition to all previous answers - the calculation for mid-term (between 7 days and 90) should have an addition instead of multiplication (7*0.10) + (daysLate*0.20); or even 1.30 + (daysLate*0.20); (as the problem description suggests)
When you use an if statement you have to make sure that it separates the cases that you want to keep separate. In your code, the first else if statement includes all instances where daysLate <= 90, so the second else if would never execute.
Also check your past 7 days due computation, its seems like you would be overcharging people for those first 7 days.
if (daysLate > 90)
{
costDue = bookPrice + 10;
}
else if (daysLate >= 0)
{
costDue = daysLate * 0.10;
if (daysLate > 7) {
costDue += (daysLate - 7) * 0.10;
}
} else {
IO.reportBadInput();
}
Another way to do this, while sacrificing readability a bit, and eliminating one else-if condition:
if (daysLate > 90) {
costDue = bookPrice + 10;
}
else if (daysLate >= 0 && daysLate <= 90) {
costDue = Math.min(7, daysLate) * 0.10 + Math.max(daysLate - 7, 0) * 0.20;
}
else {
IO.reportBadInput();
}
Is this
if (score >= 93)
grade = "A";
if (score >= 84 && score <= 92)
grade = "B";
if (score >= 75 && score <= 83)
grade = "C";
if (score < 75)
grade = "F";
the same as this
if (score>= 93)
grade = "A";
else if (score >= 84)
grade = "B";
else if (score >= 75)
grade = "C";
else
grade = "F";
I think they are both different because for the bottom one, if somebody has a score of 95 it is greater than 84 and 75. Which means the grade will be A, B, and C. The first if statement gives a restriction on the upper and lower bound of the score so there can be only one grade per score.
Your two pieces of code happen to produce the same result because your conditions do not overlap. Each condition is checking a specific range of values for score.
However, the following two segments of code would produce different results.
if (a > 5) {
System.out.println("a is greater than 5");
}
if (a > 3) {
System.out.println("a is greater than 3");
}
Given a=10, that code would produce: "a is greater than 5" and "a is greater than 3".
But with this code:
if (a > 5) {
System.out.println("a is greater than 5");
}
else if (a > 3) {
System.out.println("a is greater than 3");
}
Given a=10, that code would only produce: "a is greater than 5".
These logically are the same in your example.
When an if is true in an if-else block, all the subsequent elses are skipped.
The result from your two examples will be the same.
The difference in actual execution is that in your first example at least 4 and up to 6 comparisons will be made regardless of the value held in score.
In your second example as soon as an expression yields true none of the subsequent comparisons are made.