Nesting if statements no strings - java

I am doing a Palindrome number sequence. I've got the math set up, but I'm having trouble nesting my if statements only showing one answer.
I've attempted to remove the 'if' from the 'else if' but then java doesn't recognize. The output doesn't provide the "Not 5 digits" and when I enter 5 digits that are a Palindrome it sends an output both True and False instead of just true. However it works perfect for a false 5 digit number input. Can I have some help on how to nest appropriately is what I'm asking for or an example of a good explanation to help me achieve the results as I've been to quite a few sites, but most are too simple and lack examples to compare.
import java.util.Scanner;
public class Palindrome
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.print ("Enter 5-digit integer value: ");
int userNumber = input.nextInt();
System.out.println("Input value: " + "\t" + userNumber);
//User input incorrect amount of digits
if (userNumber >= 100000 && userNumber <= 9999)
{
System.out.println("Not 5 digits.");
}
else if(userNumber < 100000 && userNumber > 9999)
{
int Number5 = (userNumber/10000) % 10;
int Number4 = (userNumber/1000) % 10;
int Number3 = (userNumber /100) % 10;
int Number2 = (userNumber/10) % 10;
int Number1 = userNumber % 10;
//Conditions are met for Palidrome Number
if(Number1 == Number5 && Number2 == Number4)
{
System.out.println("Judgement: " + "\t" + "\t" + "True");
}
//Conditions are not met for Palidrome Number
else if (Number1 != Number5 || Number2 !=Number4);
{
System.out.println("Judgement: " + "\t" + "\t" + "False");
}
}
}
}
The results should show true, false, or not 5 digits

There is no number that is >= 100000 and <= 9999, this is why you never see Not 5 digits.
You must change that condition to:
if (userNumber <= 9999 || userNumber > 99999)
and change:
else if(userNumber < 100000 && userNumber > 9999)
to a simple
else
because if the code reaches the else part then userNumber < 100000 && userNumber > 9999 is always true.
The same applies to
else if (Number1 != Number5 || Number2 !=Number4);
(Note: the ; at the end is wrong and a source of serious headaches)
which must be changed to:
else
This statement:
int Number3 = (userNumber / 100) % 10;
is redundant as the value of Number3 is not useful in this case.
So your code should be simplified like this:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print ("Enter 5-digit integer value: ");
int userNumber = input.nextInt();
System.out.println("Input value: " + "\t" + userNumber);
if (userNumber <= 9999 || userNumber > 99999) {
System.out.println("Not 5 digits.");
}
else {
int Number5 = (userNumber / 10000) % 10;
int Number4 = (userNumber / 1000) % 10;
int Number2 = (userNumber / 10) % 10;
int Number1 = userNumber % 10;
if (Number1 == Number5 && Number2 == Number4) {
System.out.println("Judgement: " + "\t" + "\t" + "True");
} else {
System.out.println("Judgement: " + "\t" + "\t" + "False");
}
}
}

This can work:
import java.util.Scanner;
import java.lang.*;
public class Main
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.print ("Enter 5-digit integer value: ");
String userNumber = input.next();
System.out.println("Input value: " + "\t" + userNumber);
//User input incorrect amount of digits
if (userNumber.length()!=5)
{
System.out.println("Not 5 digits.");
}
else{
//Conditions are met for Palidrome Number
if(new StringBuilder(userNumber).reverse().toString().equals(userNumber))
{
System.out.println("Judgement: " + "\t" + "\t" + "True");
}
//Conditions are not met for Palidrome Number
else
{
System.out.println("Judgement: " + "\t" + "\t" + "False");
}
}
}
}
Your 2nd else if statement is redundant, and you have an extra semicolon in your last if statement.

Related

My "Else If" Code Isn't Working As Expected

I am a new coder. Working on an assignment. This is also my first post here so I apologize if it's a little sloppy.
I'm having some troubles with my if/else statements in Java...the "if" conditions seem to work okay. But my "else" conditions do not. Take a look at the code and the build results below.
Basically, I enter an ingredient. And then I put in the number of cups needed. And the number of calories the ingredient has per x cup. That all seems to work as long as I input what I want to for "successful" results.
Successful Build Image
But when I start to input values outside of my criteria, my application doesn't seem to care. If I input 0, I should get that output of "your response is invalid" or whatever it is I coded. But it just seems to skip over that entirely.
Bad Code Image
package recipe_collection_manager;
import java.util.Scanner;
public class Ingredient {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
//Initializes the variables
String nameOfIngredient = "";
int numberCups = 0;
int numberCaloriesPerCup = 0;
int totalCaloriesPerCup = 0;
double totalCalories = 0.0;
// Enter the name of the ingredient.
System.out.println("Please enter the name of the ingredient: ");
nameOfIngredient = scnr.next();
// Enter the number of cups needed for the ingredient.
// If Else statements used to establish if the number of cups is valid.
System.out.println("Please enter the number of cups of "
+ nameOfIngredient + " we'll need. The number of cups must be between 1 and 100: ");
numberCups = scnr.nextInt();
if (numberCups >= 1 || numberCups <= 100) {
System.out.println("The number of cups is valid.");
} else if (numberCups <= 1 || numberCups >= 100) {
System.out.println("The number you have entered is invalid. Please try again.");
}
// Enter the number of calories used per cup.
// If Else statements are used to establish if the number of calories is valid.
System.out.println("Please enter the number of calories per cup: ");
numberCaloriesPerCup = scnr.nextInt();
if (numberCaloriesPerCup >= 1 || numberCaloriesPerCup <= 1000) {
System.out.println("The number of calories is valid.");
} else if (numberCaloriesPerCup <= 1 || numberCaloriesPerCup >= 1000) {
System.out.println("The number you have entered is invalid. Please try again.");
}
// Calculation for totalCalories based on numberCups and numberCaloriesPerCup
if (numberCups > 0 && numberCaloriesPerCup > 0) {
totalCalories = numberCups * numberCaloriesPerCup;
}
System.out.println(nameOfIngredient + " uses " + numberCups
+ " cups and has " + totalCalories + " calories.");
}
}
Problem was in line:
if (numberCups >= 1 || numberCups <= 100) {
...
}
When you entered 0, program checked if 0 is greater or equal to 1, and that was false but you had also "or" condition ( || ), and in that condition you were checking if 0 <= 100 and because that is true, false || true gives true and that's why your if statement was correct. You needed to use "and" ( && ) instead of "or". There was flaw in your logic.
Test code below, it should work now:
package recipe_collection_manager;
import java.util.Scanner;
public class Ingredient {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
//Initializes the variables
String nameOfIngredient = "";
int numberCups = 0;
int numberCaloriesPerCup = 0;
int totalCaloriesPerCup = 0;
double totalCalories = 0.0;
// Enter the name of the ingredient.
System.out.println("Please enter the name of the ingredient: ");
nameOfIngredient = scnr.next();
// Enter the number of cups needed for the ingredient.
// If Else statements used to establish if the number of cups is valid.
System.out.println("Please enter the number of cups of "
+ nameOfIngredient + " we'll need. The number of cups must be between 1 and 100: ");
numberCups = scnr.nextInt();
if (numberCups >= 1 && numberCups <= 100) {
System.out.println("The number of cups is valid.");
} else if (numberCups <= 1 || numberCups >= 100) {
System.out.println("The number you have entered is invalid. Please try again.");
}
// Enter the number of calories used per cup.
// If Else statements are used to establish if the number of calories is valid.
System.out.println("Please enter the number of calories per cup: ");
numberCaloriesPerCup = scnr.nextInt();
if (numberCaloriesPerCup >= 1 || numberCaloriesPerCup <= 1000) {
System.out.println("The number of calories is valid.");
} else if (numberCaloriesPerCup <= 1 || numberCaloriesPerCup >= 1000) {
System.out.println("The number you have entered is invalid. Please try again.");
}
// Calculation for totalCalories based on numberCups and numberCaloriesPerCup
if (numberCups > 0 && numberCaloriesPerCup > 0) {
totalCalories = numberCups * numberCaloriesPerCup;
}
System.out.println(nameOfIngredient + " uses " + numberCups
+ " cups and has " + totalCalories + " calories.");
}
}
Just to clarify. The following statement
if(numberCups >= 1 || numberCups <= 100) {
...
}
Is true any number of cups. Any number of cups >= 1 will be caught by the first condition. Any number of cups <= 0 will be caught by the second condition since in that case they will all be less than 100. With a logical || only one condition is required to be true for the statement to be true.
In fact,
if(numberOfCups is >= A || numberOfCups <= B) {
...
}
will always be true as long as B >= A-1.

How to loop quiz a certain amount of times and add lives, Java

I have a math quiz game I am making and I am not sure how to loop it, let's say 50 times. It ends after answering only 2 questions. I also want to add lives so after you get three questions wrong it ends the program. How am I able to do this?
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int Number1 = (int)(20 * Math.random()) + 1;
int Number2 = (int)(20 * Math.random()) + 1;
int correct = 0;
System.out.print(Number1 + " + " + Number2 + " = ");
int GuessRandomNumberAdd = keyboard.nextInt();
if (GuessRandomNumberAdd == Number1 + Number2) {
System.out.println("Correct!");
correct++;
}else {
System.out.println("Wrong!");
}
System.out.print(Number1 + " * " + Number2 + " = ");
int GuessRandomNumberMul = keyboard.nextInt();
if (GuessRandomNumberMul == Number1 * Number2) {
System.out.println("Correct!");
correct++;
}else{
System.out.println("Wrong!");
System.out.println("You got " + correct + " correct answers.");
After the int correct = 0;
add a lives counter.
eg:
int lives =3;
then start a while loop
while(lives > 0){
reduce the lives if a question is incorrect (where you put "wrong!" message)
lives--;
at the end of the while loop (before no of correct answers is printed out)
remember to put the last }
This will keep looping till you lose your lives
A couple things:
-There are multiple java structures which allow you to loop. The main loops out there in any kind of programming language are for loop, while loop, and do-while loop (uncommon)
-You can create lives by defining a variable and checking it in every iteration (an iteration is each "run" through the code of a loop).
Your code after implementing this 2 things would look like this:
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int Number1 = (int)(20 * Math.random()) + 1;
int Number2 = (int)(20 * Math.random()) + 1;
int correct = 0;
int lives = 3;
//The for loop is read as: having i equal 25 and the variable lives, iterate if i is lower than 25 AND lives is higher than 0. After an iteration, add 1 to i;
for (int i=25, lives; i<25 && lives > 0; i++) {
System.out.print(Number1 + " + " + Number2 + " = ");
int GuessRandomNumberAdd = keyboard.nextInt();
if (GuessRandomNumberAdd == Number1 + Number2) {
System.out.println("Correct!");
correct++;
} else {
System.out.println("Wrong!");
lives--;
}
System.out.print(Number1 + " * " + Number2 + " = ");
int GuessRandomNumberMul = keyboard.nextInt();
if (GuessRandomNumberMul == Number1 * Number2) {
System.out.println("Correct!");
correct++;
}else{
System.out.println("Wrong!");
lives--;
} //Forgot this bracket
} //Closes the for loop
System.out.println("You got " + correct + " correct answers.");
See if below example works as you intend. Here I have given the loop count as 5. So there will be 5 "addition" questions and 5 "multiplication" questions.
I'm printing the question number also. So, now the output is more clear.
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int correct = 0;
for (int i = 0; i < 5; i++) {
int Number1 = (int) (20 * Math.random()) + 1;
int Number2 = (int) (20 * Math.random()) + 1;
System.out.println("Question " + (i*2+1));
System.out.print(Number1 + " + " + Number2 + " = ");
int GuessRandomNumberAdd = keyboard.nextInt();
if (GuessRandomNumberAdd == Number1 + Number2) {
System.out.println("Correct!");
correct++;
}
else {
System.out.println("Wrong!");
}
System.out.println();
System.out.println("Question " + (i*2+2));
System.out.print(Number1 + " * " + Number2 + " = ");
int GuessRandomNumberMul = keyboard.nextInt();
if (GuessRandomNumberMul == Number1 * Number2) {
System.out.println("Correct!");
correct++;
}
else {
System.out.println("Wrong!");
}
System.out.println();
}
System.out.println("You got " + correct + " correct answers.");
}
}

Write a loop that should generate multiplication questions with single digit random integers

I'm stuck at the part where I loop back into: "yes" - I want to continue or "no" - I'd like to exit.
I'm aware I would need to display an if? to display results only if you exit the program
//Input your display and questions:
int num1 = (int) (Math.random() * 10 +1);
int num2 = (int) (Math.random() * 10 + 1);
int answer = 0;
int correctCount=0;
int count= 0;
//Scanner object input
Scanner input = new Scanner(System.in);
//Swap numbers if number2 is bigger than number 1
if (num1 < num2) {
int temp = num1;
num1 = num2;
num2 = temp;
}
//OUTPUT DISPLAY QUESTION: What is num1 + num2 = ?
System.out.print("What is "+num1 + " * " + num2 + " = ");
answer = input.nextInt();
//If answer is correct display: Good Job! Your got it right
if (answer == (num1 * num2))
{
System.out.println("Good job! You got it right!\n");
correctCount++; //Increases correct count for answer correct!
}
else
System.out.println("You got it wrong, try again!\n" +num1 + " * " +num2+ " should be " + (num1 * num2));
count++;
System.out.print("Enter Y to continue or N to exit: \n"); //Do you want to continue
System.out.println("\nYou got " +correctCount+ " out of "+count + " answer correct"); //Displays Correct with total# of questions
}
}
You have just to use a while loop to make the app loop until the user enter a character other than y.
also, try to use try-with-resource to avoid source leak with scanner object
Like this:
public static void main(String[] args) {
// Input your display and questions:
int answer = 0;
int correctCount = 0;
int count = 0;
String continueStr = "yes";
try (Scanner input = new Scanner(System.in)) {
while (continueStr.equalsIgnoreCase("yes")) {
// Scanner object input
int num1 = (int) (Math.random() * 10 + 1);
int num2 = (int) (Math.random() * 10 + 1);
// Swap numbers if number2 is bigger than number 1
if (num1 < num2) {
int temp = num1;
num1 = num2;
num2 = temp;
}
// OUTPUT DISPLAY QUESTION: What is num1 + num2 = ?
System.out.print("What is " + num1 + " * " + num2 + " = ");
answer = input.nextInt();
input.nextLine();
// If answer is correct display: Good Job! Your got it right
if (answer == (num1 * num2)) {
System.out.println("Good job! You got it right!\n");
correctCount++; // Increases correct count for answer correct!
} else {
System.out.println("You got it wrong, try again!\n" + num1 + " * " + num2 + " should be " + (num1 * num2));
}
count++;
System.out.print("\nEnter Yes to continue or No to exit: \n"); // Do you want to continue
continueStr = input.nextLine();
}
System.out.println("\nYou got " + correctCount + " out of " + count + " answer correct"); // Displays Correct with total# of questions
}
}

unable to get the correct output for input .11

I have an assignment at school and I have to display the correct change for an amount that is being input by the user that is less than 1.00 but greater than 0. Every amount works except anything in a double digit that has a 1 or a 6 on the tenth spot. for example .11, .16, .21, .26 etc.
this is my code
import java.util.Scanner;
public class AmountChange
{
public static void main(String[] args)
{
//
double amt;
int cents, quarter, dime, nickle, penny;
Scanner keyboard = new Scanner(System.in);
//To get the users input
System.out.println("Change in Coins");
System.out.println("---------------");
System.out.println("Enter the amount less than $1.00, " +
"\nbut more than zero.");
System.out.print("\nEnter amount: ");
amt = keyboard.nextDouble();
//Loop for incorrect input
while ( amt < 0 || amt > 1.00 )
{
System.out.println("Please enter the amount less than $1.00,"
+ "\nbut more than zero.");
System.out.print("\nRe-enter amount: ");
amt = keyboard.nextDouble();
}
//
cents = (int)( amt * 100 + .1 );
quarter = cents/25;
cents %= 25;
dime = cents/10;
cents %= 10;
nickle = cents/5;
cents %= 5;
penny = cents;
// ----------------------------------------------------------
if (quarter > 1)
{
System.out.print("\nYou will need " + quarter + " quarters, ");
}
else if (quarter == 1)
{
System.out.print("\nYou will need " + quarter + " quarter ,");
}
else
{
System.out.print("\nYou will need no quarters, ");
}
// ----------------------------------------------------------
if (dime > 1)
{
System.out.print(dime + " dimes, ");
}
else if (dime == 1)
{
System.out.print(dime + " dime, ");
}
else
{
System.out.print("no dimes, ");
}
// ----------------------------------------------------------
if (nickle > 1)
{
System.out.print(nickle + " nickles, ");
}
else if (nickle == 1)
{
System.out.print(nickle + " nickle, ");
}
else
{
System.out.print("no nickles, ");
}
// ----------------------------------------------------------
if (penny > 1)
{
System.out.print("and " + penny + " pennies.");
}
else if (quarter == 1)
{
System.out.print("and " + penny + " penny.");
}
else
{
System.out.print("and no pennies.");
}
}
}
Ah, the joys of cut and paste :-)
if (penny > 1)
{
System.out.print("and " + penny + " pennies.");
}
else if (quarter == 1) // <<<<< LOOK HERE !!!
{
System.out.print("and " + penny + " penny.");
}
else
{
System.out.print("and no pennies.");
}
That should be penny, not quarter.
And, in fact, it actually does work for .26 (despite your assertion) since quarter is set to 1, the same as penny. In fact it'll work for any value where the number of quarters equals the number of pennies (.26, .52, .78), but only by accident.
As an aside, one other thing you may want to think about is refactoring all that repeated code with something like:
import java.util.Scanner;
public class Test
{
static double getAmount(Scanner keyboard) {
System.out.println("Enter the amount between zero and $1.00.");
System.out.print("\nEnter amount: ");
return keyboard.nextDouble();
}
static String mkeTxt (int val, String prefix, String singular, String plural) {
if (val == 0)
return prefix + "no " + plural;
if (val == 1)
return prefix + "1 " + singular;
return prefix + val + " " + plural;
}
public static void main(String[] args)
{
double amt;
int cents, quarter, dime, nickle, penny;
Scanner keyboard = new Scanner(System.in);
System.out.println("Change in Coins");
System.out.println("---------------");
amt = getAmount(keyboard);
while ( amt < 0 || amt > 1.00 )
amt = getAmount(keyboard);
cents = (int)( amt * 100 + .1 );
quarter = cents/25;
cents %= 25;
dime = cents/10;
cents %= 10;
nickle = cents/5;
cents %= 5;
penny = cents;
System.out.print("\nYou will need ");
System.out.print(mkeTxt(quarter,"", "quarter", "quarters"));
System.out.print(mkeTxt(dime,", ", "dime", "dimes"));
System.out.print(mkeTxt(nickle,", ", "nickle", "nickles"));
System.out.print(mkeTxt(penny," and ", "penny", "pennies"));
System.out.println(".");
}
}
The use of a function to output the prompt and accept input makes the user input code a little easier to maintain as you only need to change interaction in one place.
The real saver is the mkTxt() function to give you a string that auto-magically adjusts to the quantity of coins. It gets rid of that voluminous group of if/then/else blocks in main(), aiding readability somewhat.
If you ever find yourself doing a similar thing many times but with different values, that positively cries out to be changed into a function or loop of some description.
You just have a simple typo!
Change:
else if (quarter == 1){
System.out.print("and " + penny + " penny.");
} else {
System.out.print("and no pennies.");
}
To,
else if (penny == 1){
System.out.print("and " + penny + " penny.");
} else {
System.out.print("and no pennies.");
}

English Language Calculator [java]

Create a java program that will do the following:
a) Read three inputs from the keyboard,
• two input numbers each being a single digit (0…9)
• one character representing one of five operations : + (addition), - (subtraction), * (multiplication), / (division), and ^ (exponentiation)
b) output the description of the operation in plain English as well as the numeric results
import java.util.Scanner;
public class EnglishCalc {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter first number");
int number1 = input.nextInt();
System.out.println("Enter second number");
int number2 = input.nextInt();
System.out.println("Enter operation: +,-,*,/,^");
String operation = input.next();
int output = 0;
if(number1 < 0 || number1 > 9 || number2 < 0 || number2 > 9) {
System.out.println("Number should be between 0 and 10");
}
else if (operation.equals("+"))
{
output = number1 + number2;
System.out.println("Sum of "+number1+" and "+number2+" is: " +output);
}
else if (operation.equals("-"))
{
output = number1 - number2;
System.out.println("Subtraction of "+number2+" from "+number1+" is: " +output);
}
else if (operation.equals("*"))
{
output = number1 * number2;
System.out.println("Product of "+number1+" and "+number2+" is: " +output);
}
else if (operation.equals("/"))
{
if(number2 == 0) {
System.out.println("You cannot divide by 0");
} else {
output = number1/number2;
System.out.println("Division of "+number1+" by "+number2+" is: " +output);
}
}
else if(operation.equals('^'))
{
output = Math.pow((double)number1 , (double)number2);
System.out.println("Value of "+num1+" raised to power of "+num2+" is: " +output);
} else {
System.out.println("Invalid input");
}
}
}
for pow. i tried casting wont work. and if i dont cast, it wont accept int. must be double.
Use
s1.equals(s2)
to compare strings, instead of using:
s1 == s2
This happens because == is used to compare object references (if the are the same object), so it doesn't compare the 'contain' of that object, in this case a String.
Edit
To print each number in 'words', you could use an array:
String[] numbers = {"zero", "one", "two", ... };
and then use them as:
System.out.println(numbers[2] + " plus " + numbers[5] + ...);

Categories

Resources