Simple Palindrome [duplicate] - java

This question already has an answer here:
Simple Palindrome Detector [duplicate]
(1 answer)
Closed 4 years ago.
I've tried different approaches to do this, and when I do this..
import java.util.*;
public class Palindrome {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number");
int number = in .nextInt();
int first = number
int middle = 0;
int last = first;
boolean isPalindrome = last == first;
if (isPalindrome) {
System.out.print("This is a palindrome");
} else
System.out.print("This is not a palindrome");
}
}
it spits out "this is a palindrome". Mind you I can't use loops. Shouldn't this work?
It works when I do this...
import java.util.*;
public class Palindrome {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number");
int first = 1;
int middle = 0;
int last = 5;
boolean isPalindrome = last == first;
if (isPalindrome) {
System.out.print("This is a palindrome");
} else
System.out.print("This is not a palindrome");
}
}
It tells me if it's a palindrome or not...
So, it works on my end, but not the users end.
What am I missing

The problem is, you are assigning the value of the input to your variable first then you assigned the value of first to the variable last. You declared your boolean as isPalindrome = first==last (true) which will always be true in this scenario that's why you get "This is a palindrome". On your second block of code which you said "works" is because you declared first = 1 and last = 5, when you did isPalindrome = first==last (false) the value of the palindrome will always be false hence you get "This is not a palindrome" output.
I think what you need to do is rewrite your logic so you can elaborate the process you want to do. Feel free to ask a follow-up question.

In the first one, the user enters a number which is assigned to first, then you set last to be a reference to first. Since the truth value of isPalindrome depends on whether last == first, it will always be true, since you coded it that way. However, this doesn't actually prove that the number is a palindrome, because for example if the user enters the number 56, the number 56056 is not a palindrome (reverse is 65065).
In the second program, first is always 1 and last is always 5, so since they are never equivalent the condition last == first will always be false.
What are you attempting to achieve with the programs? Neither one tests the user input to be a palindrome. Try writing psuedocode first, in the comments if you like.

Related

How to end do while loop with user input with if statement [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
import java.util.Scanner;
public class main {
public static void main(String[] args) {
boolean a = true;
do {
Scanner input = new Scanner(System.in);
System.out.println("Press any on keyboard:");
String keys = input.nextLine();
System.out.println("You pressed:");
System.out.println(keys);
System.out.println("Your hash is:");
String B = "#B";
String hash = B+keys;
System.out.println(hash);
System.out.println("To end loop press f");
//End Loop
Scanner exit = new Scanner(System.in);
String end = exit.nextLine();
if (end=="f") {
a=false;
}
}
while(a);
}
}
I've been using python and I decided to start learning java since android studio requires it. I'm learning how to do loops again. I can't get this to work. I already looked this up I couldn't find it. How would I end this by pressing 'f'? My thought process was that once it was done going though the first lines of the do loop, it would go though the if statement changing the value of a ending the loop.
use break statement under if(){} body. also your == comparison will give false, use str1.equals(str2) for comparison.
Your problem is you are comparing strings with ==.You have to use equals to write correct if statement.
if (end.equals("f")){...}
You could use the below code to check
if (end.equals("f")) { // end == "f" , it check the reference.
a = false;
}

Checking length of a String and using do-while in Java

I want to create a program where you enter a string and it checks if the length is 9 or not. If it is, it gives a message that it is okay. If not, it will give a message that is not, and prompt the user to enter the string again. While running it, I always get that is wrong. Where am I going wrong?
import java.util.*;
public class Sec {
public static void main(String[] args) {
Scanner Secnum = new Scanner(System.in);
System.out.println("Give Sec: ");
String Sec = Secnum.nextLine();
do{
if (Sec.length()!= 9);
System.out.println("Wrong lenght Sec,enter again");
Secnum.nextLine();
}while (Sec.length() == 9);
System.out.println("Sec lenght okay");
}
}
You want to request a new value as long as the length is NOT 9.
So your loop should have that as condition. Further your if is incorrect. If in Java needs curly braces else it will effect the next statement only. A statement can be only a semi-colon as well. So your if-statement is completely useless.
To make the code even more compact you can take out the if and swap the do-while loop. That will only run if the condition is true and not once in the beginning no matter the condition.
A code that should work better:
import java.util.*;
public class Sec {
public static void main(String[] args) {
Scanner secnum = new Scanner(System.in);
System.out.println("Give Sec: ");
String sec = secnum.nextLine();
while (sec.length() != 9) {
System.out.println("Wrong lenght Sec,enter again");
secnum.nextLine();
}
System.out.println("Sec lenght okay");
}
}
On a side note: Use lowercase variable names. That is the better code-style :)
You are terminating the if statement.
if (Sec.length()!= 9);
So, the next print always executes irrespective of it being true or not.
Put the logic for failure inside an if block.
if (Sec.length()!= 9) {
// Print failure message
// Other logic
}

hasNext() of Scanner keeps looping [duplicate]

This question already has answers here:
How to use .nextInt() and hasNextInt() in a while loop
(3 answers)
Closed 6 years ago.
I have this code that I want to run to solve a problem which needs a three user inputs, and I used Scanner class for this:
public static void main(String[] args) {
int M = 0;
int A = 0;
Scanner input = new Scanner(System.in);
System.out.println("Please, insert the normal dose in ml:");
M = input.nextInt();
System.out.println("Please, insert the set of experiments (3 integers per line, stop by 0 0 0):");
try {
while (input.hasNextInt()) {
System.out.print(input.hasNext());
int i = input.nextInt();
A += i;
System.out.println(A);
}
} catch (Exception x) {
System.out.print(x.getMessage());
}
System.out.println("Loop ended");
}
The strange thing is that input.hasNextInt() gets stuck or something after I Insert the three values, It seem that it keeps looping or something even though there are no inputs in the console, can some one provide some help for me?
That's because input.hasNextInt() waits until a integer value is available. It would return false if an alphanumeric value was informed.
You have to define another way to break while loop, maybe with a counter or, like your message says, checking whether 3 values are equal to 0.

Make Java Program Loop until x is entered?

I want to make my program loop until the user types in x instead of a number. I tried using a while statement but I do not know how to use it with multiple variables. Here is my code
public static void main(String[] args)
{
int denominatorOne = 1, numeratorOne = 1;
System.out.println("Welcome, type an \"x\" at any point to exit the program");
while (numeratorOne !=x)
{
Scanner in = new Scanner(System.in);
//Prompt the user for fraction one
System.out.print("Enter the first numerator (top number): ");
numeratorOne = in.nextInt();
System.out.print("Enter the first denominator (bottom number): ");
denominatorOne = in.nextInt();
}
}
The exact phrasing from my assignment is The program should run in loop and allow the user to exit with some special character input (e.g. x or X to exit)
First off, 'x' isn't a number and won't be accepted by nextInt or a comparison to 'x', you should trying checking to see if it has next int (in.hasNextInt()) and process depending. Besides the point, you can easily test two variables in a while loop. Assuming you set up the variables right to be chars:
do {
// scan code.
} while(!(numChar1.equals('x') && numChar2.equals('x')))
what you need to do is have a bool value that holds the loop and when have a if statement check for the keydown event in the loop
bool looping = true
while ( looping == true)
{
if (x button was pressed == true)
{looping = false
}
}
try changing it to
while(!numeratorOne.equals("x")){...}
You can just call the method over again in this case main();.
What I suggest however is to create a new method, in the method just checking the users input returning the input as a string. Then you can check the string in your main method, and if that's not the string you wanted then recall the method. Here's an example, please note I didn't use an IDE for this.
public String getMessage(){
Scanner input = System.in();
return input;
}
public void checkMessage(String wantedString){
if(!getMessage().equalsIgnoreCase(wantedString)){
System.out.println("Please retry");
checkMessage();
}
}
public static void main(String[] args){
checkMessage();
}

Else-if statement not working properly when evaluating Strings [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am writing a program for a school assignment to create one string array of 3 riddles and another string array of 3 answers to each riddle. However when I input the correct answer to the riddle it keeps on showing the else part of the if-else statement. Here's my code:
import java.util.Scanner;
import java.util.Random;
public class riddleProgram {
public static void main (String[]args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
int index;
int chosenRiddles = rand.nextInt(2);
//declares the riddles in the program as well as choosing a random riddle from the three presented
String[]riddle = new String[3];
riddle[0] = "What starts with a T, ends with a T, and has T in it?";
riddle[1] = "The day before two days after the day before tommorrow is Saturday. What day is it today?";
riddle[2] = "What grows up while growing down?";
//declares the answers to the riddles
String[]answer = new String[3];
answer[0] = ("teapot");
answer[1] = ("friday");
answer[2] = ("goose");
//asks user to enter guessed answer for the randomly presented riddle
for (index=0; index<3; index++); {
System.out.println(riddle[chosenRiddles]);
System.out.print("Enter your answer for the presented riddle (lowercase): ");
String inputtedAnswer = input.nextLine();
//if user inputs right answer, congratulates user
//if user inputs incorrect answer, tells user the correct answer
if (inputtedAnswer == answer[chosenRiddles]) {
System.out.println("Congratulations, you have gotten the right answer!"); }
else {
System.out.println("Sorry you had the wrong answer. The right answer is " + answer[chosenRiddles] + ".");}
}
}
}
never compare strings with ==
you should always use .equals( )
if (answer[chosenRiddles].equals(inputtedAnswer)) {
you should also try to have the constant value (the one that will always exist) on the left of these, to prevent possible NullPointerExceptions.

Categories