JAVA: if/else statements producing incorrect result - java

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.");
}
//...

Related

Problem in program to input a 3 digit number and check which digits are even and replace it with odd digits

Problem while entering a 3 digit no and getting no result. after entering 123 and when 2 is detected as even, and if user enters 7, it should display 173. but the program is immediately ending. It might be a problem in the last 0 check if-block. but removing it also doesn't help. Thanks in advance!
// in 3 dig, check even dig., replace them with odd and disp.
import java.util.*;
public class p24123 {
public static void main(String[] args) {
int n,h,t,o,m,z=0,z1=0,z2=0,fn;
Scanner ob = new Scanner(System.in);
n=ob.nextInt();
if(n>99&&n<1000){
h= n/100;
o=n%10;
m=n/10;
t=m%10;
if(h%2==0){
z=h;
System.out.println("Enter the odd number you would like to replace the EVEN hundred's digit"+h+" with \n");
z=ob.nextInt();
if(z%2==0){
System.out.println("That's not odd. So we will keep the original digit in it's place");
z=h;
}
else if(t%2==0) {
System.out.println("Condition enter bokachpda");
z1 = t;
System.out.println("Enter the odd number you would like to replace the EVEN ten's digit" + t + " with \n");
z1 = ob.nextInt();
if (z % 2 == 0) {
System.out.println("That's not odd. So we will keep the original digit in it's place");
z1 = t;
}
}
else if(o%2==0){
z2=o;
System.out.println("Enter the odd number you would like to replace the EVEN one's digit"+h+" with \n");
z2=ob.nextInt();
if(z2%2==0){
System.out.println("That's not odd. So we will keep the original digit in it's place");
z2=o;
}
}
else if(2==2){
if(h<1||t<1||o<1||z<1||z1<1||z2<1){
System.out.println("Error");
System.exit(0);
}
}
fn=z*100+z1*10+z;
}
}
}
}
Here's your code cleaned up and fixed. I modified as little as possible to keep it at a level a beginner would be comfortable with. Some improvements to be made:
Repeated code like this screams, "Put me in my own function!"
A loop can be used to handle any number of digits, not just three.
Error checking/handling. You should handle bad input. What if the user enters "hello" instead of a number?
Improvements I made:
Your original code never printed a result.
Better formatting. It makes the code easier to read.
Descriptive variable names!
Scanner ob = new Scanner(System.in);
int n = ob.nextInt();
if (n > 99 && n < 1000) {
int hundredsDigit = n / 100;
int tensDigit = n / 10 % 10;
int onesDigit = n % 10;
if (hundredsDigit % 2 == 0) {
System.out.println("Enter the odd number you would like to replace the EVEN hundred's digit " + hundredsDigit +" with \n");
int replacementDigit = ob.nextInt();
if (replacementDigit % 2 == 0) {
System.out.println("That's not odd. So we will keep the original digit in it's place");
}
else {
hundredsDigit = replacementDigit;
}
}
if (tensDigit % 2 == 0) {
System.out.println("Enter the odd number you would like to replace the EVEN ten's digit " + tensDigit + " with \n");
int replacementDigit = ob.nextInt();
if (replacementDigit % 2 == 0) {
System.out.println("That's not odd. So we will keep the original digit in it's place");
}
else {
tensDigit = replacementDigit;
}
}
if (onesDigit % 2 == 0) {
System.out.println("Enter the odd number you would like to replace the EVEN one's digit " + onesDigit + " with \n");
int replacementDigit = ob.nextInt();
if (replacementDigit % 2 == 0) {
System.out.println("That's not odd. So we will keep the original digit in it's place");
}
else {
onesDigit = replacementDigit;
}
}
System.out.println(hundredsDigit * 100 + tensDigit * 10 + onesDigit);
}

Less then or equal to Else IF Java stuck

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");
}
}

Why are my lines printing several two times instead of one? How do I use a loop to avoid invalid answers?

I'm using a main method and two smaller methods to play a human vs. computer game of Nim. However, when it is the computer's turn, sometimes two lines are printed with different output values. For example, the output may say:
*** There are 66 marbles in the pile.
Computer will take 3.
Computer will take 2.
I'm not sure why it continues to print twice. It doesn't always happen either. Here is my full code:
import java.util.Scanner;
public class Program10 {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int take = 0;
int turn = (int)(Math.random() * 2 + 0);
int start = turn;
int marbles = (int)(Math.random() * 100 + 10);
int moveType;
while (marbles > 0) {
System.out.println("\n*** There are " + marbles + " marbles in the pile.");
if (turn % 2 == 0) {
if (marbles == 1) {
System.out.print("How many do you want to take (1-1)");
take = input.nextInt();
while (take < 1 && take >= (marbles / 2)) {
System.out.println("\n\n*** Illegal entry!");
System.out.print("How many do you want to take (1-" + (marbles / 2) + ") ");
take = input.nextInt();
}
}
else {
System.out.print("How many do you want to take (1-" + (marbles / 2) + ") ");
take = input.nextInt();
while (take < 1 && take >= (marbles / 2)) {
System.out.println("\n\n*** Illegal entry!");
System.out.print("How many do you want to take (1-" + (marbles / 2) + ") ");
take = input.nextInt();
}
}
}
else {
moveType = (int)(Math.random() * 2 + 0);
if (moveType == 0) {
take = getSmartMove(marbles);
}
else {
take = getStupidMove(marbles);
}
}
marbles = marbles - take;
turn++;
}
if (turn % 2 == start) {
System.out.println("Human wins!");
}
else {
System.out.println("Computer wins :(");
}
}
public static int getSmartMove(int marbles) {
int take;
if (marbles == 1) {
take = 1;
System.out.println("Computer will take " + take + ".");
}
if (marbles > 63) {
take = (marbles - 63);
System.out.println("Computer will take " + take + ".");
}
if (marbles > 31 && marbles < 63) {
take = (marbles - 31);
System.out.println("Computer will take " + take + ".");
}
if (marbles > 15 && marbles < 31) {
take = (marbles - 15);
System.out.println("Computer will take " + take + ".");
}
if (marbles > 7 && marbles < 15) {
take = (marbles - 7);
System.out.println("Computer will take " + take + ".");
}
if (marbles > 3 && marbles < 7) {
take = (marbles - 3);
System.out.println("Computer will take " + take + ".");
}
else {
take = (int)(Math.random() * (marbles / 2) + 1);
System.out.println("Computer will take " + take + ".");
}
return take;
}
public static int getStupidMove(int marbles) {
int take = (int)(Math.random() * (marbles / 2) + 1);
System.out.println("Computer will take " + take + ".");
return take;
}
}
The user should also not be allowed to enter a value less than one or higher than the number of marbles divided by two. The valid input range is listed beside the question like so:
How many do you want to take (1-33)
However, it seems that I can still enter invalid numbers like 0. Please let me know if I'm doing something wrong with my coding. I've been trying to find patterns that may lead me to the answer, but so far I'm blank. Thank you!
UPDATE:
I figured out how to solve the issue of multiple lines, and I realized that I was using && instead of || when invalid inputs are entered.

Advice and help if there is shorter way to write code for this task

I recently started to get into Java (about a week ago) and I have a question for the code bellow:
The program written checks if the input number from a user (whole number) can be divided on both 5 and 7, only by 5, only by 7 and if it cannot be divided at all.
My question is, is there some other way to reduce the code written?
First post here, sorry if I ask dumb question, I am just curious.
Thank you in advance.
Scanner sc = new Scanner(System.in);
System.out.println("Enter number: ");
int number = sc.nextInt();
int five = 5;
int seven = 7;
boolean a = (number % five == 0) && (number % seven == 0);
if (a == true)
{
System.out.println(number + " divides on both 5 and 7.");
}
else
{
System.out.println(number + " doesn't divide on both 5 and 7.");
}
if (number % five == 0)
{
System.out.println(number + " divides successfuly by 5.");
}
else
{
System.out.println(number + " can't be divided successfuly by 5.");
}
if (number % seven == 0)
{
System.out.println(number +" divides successfuly by 7.");
}
else
{
System.out.println(number + " can't be divided successfuly by 7.");
}
Yes of course. What you need to do is nest if statements.
int number = sc.nextInt();
if (number % five == 0)
{
if (number % seven == 0)
System.out.println(number + " is divisible by both 5 and 7.");
else
System.out.println(number + " is divisible by 5.");
}
else {
if (number % seven == 0)
System.out.println(number + " is divisible by 7.");
else
System.out.println(number + " is not divisible by either 5 or 7.");
}
This means that any code inside the curly braces of the first if statement can only be reached if number%five == 0. Therefore, after that point, there are two possibilities: either it is divisible by 7 as well or it is not.
Likewise, code in the first else can only be reached if number%five != 0. Therefore, after that point, there are two possibilities: either it is divisible by 7 or it is divisible by neither of them.

Code doesn't work in Java (arrays)

I have an assignment to write a code that ask you for 10 seats (some are taken and some are empty) and you need to get a seat, check if it is available and if not find the closest seat that is empty.
Some times my code works, but most of the time it doesn't. Can someone help me?
import java.util.Scanner;
public class Main {
static Scanner reader = new Scanner(System. in );
public static void main(String[] args) {
int mult = 1;
int[] manage = new int[10];
System.out.println(" 0- empty 1-taken ");
for (int i = 0; i < 10; i++) {
System.out.println("enter the " + (i + 1) + " place");
manage[i] = reader.nextInt();
}
int a = 0, check = 0;
System.out.println("What the place you want to seat in?: ");
a = (reader.nextInt()) + 1;
System.out.println("checking...");
while (check != 5) {
if (manage[a] == 0) {
System.out.println(" your seat is in the " + a + " place");
check = 5;
} else if (manage[a - mult] == 0) {
System.out.println(" your seat is in the " + ((a - mult) + 1) + " place");
check = 5;
} else if (manage[a + mult] == 0) {
System.out.println(" your seat is in the " + ((a + mult) + 1) + " place");
check = 5;
} else {
mult++;
}
}
}
}
I think what you want for this line is
a = (reader.nextInt()) - 1;
instead of
a = (reader.nextInt()) + 1;
Since you are always displaying the 'actual index + 1' for all your outputs, i.e.
The user deals with 1 - 10 and not 0 - 9?
Note: manage[a - mult] and manage[a + mult] can throw ArrayIndexOutOfBoundsException if the value is < 0 or the value is >= array length.
Note #2: In the else clause, once mult is >= array length, you can break out of the loop. If you do not add that in, the loop will keep repeating if all the seats are taken right from the start.
So, add a check before accessing that array index, as shown here:
if (manage[a] == 0) {
System.out.println("Your seat is in the " + a + " place");
check = 5;
} else if ( a - mult >= 0 && manage[a - mult] == 0) {
System.out.println("Your seat is in the " + ((a - mult) + 1)
+ " place");
check = 5;
} else if (a + mult < manage.length && manage[a + mult] == 0) {
System.out.println("Your seat is in the " + ((a + mult) + 1)
+ " place");
check = 5;
} else {
mult++;
// Check is necessary here, infinite loop if all seats are taken!
if(mult >= manage.length) {
System.out.println("All seats taken!");
break;
}
}
Input/Output (after making the change):
0 - Empty 1 - Taken
Enter the 1 place: 0
Enter the 2 place: 0
Enter the 3 place: 1
Enter the 4 place: 1
Enter the 5 place: 1
Enter the 6 place: 1
Enter the 7 place: 1
Enter the 8 place: 1
Enter the 9 place: 1
Enter the 10 place: 1
What is the place you want to sit in?: 10
checking...
Your seat is in the 2 place
0 - Empty 1 - Taken
Enter the 1 place: 1
Enter the 2 place: 1
Enter the 3 place: 1
Enter the 4 place: 1
Enter the 5 place: 0
Enter the 6 place: 1
Enter the 7 place: 1
Enter the 8 place: 1
Enter the 9 place: 0
Enter the 10 place: 1
What is the place you want to sit in?: 1
checking...
Your seat is in the 5 place
In the above example, user enters 10, but your program checks for array index 9.Array index 9 is taken, so you check array index 8 (9-1), which is empty, and tells the user that seat #9 is his seat.

Categories