Why isn't my palindrome working? - java

I'm an aspiring java user taking college courses and I've run into a problem. My prof. told us to write a java program that detects a 5 digit number based palindrome. I've written something but it won't work the way I've planned. Could I get some help please? Using netbeans IDE.
package palindrome;
import javax.swing.JOptionPane;
public class Palindrome {
public static void main(String[] args) {
String stringNumber;
int number;
String stringPal;
int palindrome;
stringNumber = JOptionPane
.showInputDialog("Please, if you will, enter a five digit palindrome: ");
number = Integer.parseInt(stringNumber);
if (number < 10000 && number > 99999) {
System.out
.println("Your number is invalid, please enter a FIVE digit number: ");
} else if (number % 10 == number % 100) {
System.out.println("your number: " + number + "is a palindrome");
} else {
System.out.println("You FAIL loser");
}
}
}

Your palindrome logic is incorrect. You check if the remainder when divided by 10 equals the remainder when divided by 100 - that is the case if and only if there is a 0 in the tens digit. That is not the definition of a palindrome.

As already pointed out, that your logic for palindrome is wrong.
What you need to check is if the string/number is same when reversed.
So, suppose you want to check whether the a string is palindrome, reverse it and check if it is same as the original string.
You should try to complete this template:
boolean isPalindrome(String s){
String reverseString = reverseString(s);
if(reverseString.equals(s)){
return true;
}
return false;
}
String reverse(String s){
//add code to reverse String. (and optionally check if it is Integer, if it is a requirement)
}
You can now google how to reverse a string.
PS: You might wanna take a look at StringBuilder class.

i don't understand, how number % 10 == number % 100, implies palindrome, but all it does is compare the value of the last 2 digits to the value of the last 1 digit.
My advice would be to take input as a string or char array and the compare the last element of the string to the first, and then continue until you hit the middle
here's some psudo-code:
isPalindrome = true;
for i=0 to stringLength
if(input[i] != input[length - i - 1])
isPalindrome = false;

Related

Method to check if the string contains certain elements that accepts a parameter String

I am a student and kind of new to Java. For my homework I have to:
Ask the user to input a number (at least 7) using a do while loop.
Using a for loop I am required to ask the user to input that number of words.
Then I have to check if one of the words fulfills the given conditions:
The word must:
Start with an uppercase letter
End with a number
Contain the word "cse".
I am asked to create a method inside some code homework that does a specific task, the method should check all the required conditions, the name of the method should be countTest and it accepts the String as a parameter.
I will show you my code but I don't know how to create this specific method.
Output format
System.out.println("There as a total number of words " + count + " and
the ones that fulfill the condition are: " + condition);
The problem is, I dont know how to create the method or constructor or whatever it is called that calls all of the 3 methods inside it, and then connect that particular method to the main method!
I hope you guys can understand I am new to this, thank you in advance!
public class D6_6 {
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
System.out.println("Type a number that is at least 7");
int number = sc.nextInt();
int count = 0;
int condition = 0;
do{
if(number<7){
System.out.println("You should type a number that is at least 7 or higher");
number = sc.nextInt();
}
}
while(number<7);
sc.nextLine();
String str;
for(int i =0; i<number; i++){
System.out.println("Type a word");
str = sc.nextLine();
count++;
}
}
public boolean countTest(String str) {
}```
To check if the word start with an uppercase:
You can do that by first selecting the character you want to check by str.charAt(0). This will return a char that is the first letter of the input str.
To check if this char is an uppercase letter, you can easily use char.isUppercase(). This will return a boolean. You have to replace char by the name of the variable were you put the char of str.charAt(0) in.
To check if the last character is a number:
You can do that again by first selecting the last character by str.charAt(str.length()-1), were string.length-1 is the number of the last character.
To check if this character is a number, you can use the ascii table. Every character has it's own number. So if you want to check if your character is between 0 and 9, you can use char >= 48 || char <= 57 (look up in the ascii table). Again, char is the name of the variable were you put the char of str.charAt(str.length()-1) in.
To check if the word contains "cse":
There is a very easy method for that: str.contains("cse") will return a boolean that is true when "cse" is in the word and false when the word does not contain "cse".
I hope it is clear for you now!
I think I did it, thank you guys very much, I appreciate it!
public class D6_6 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Type a number that is at least 7");
int number = sc.nextInt();
int count = 0;
int condition = 0;
do {
if (number < 7) {
System.out.println("You should type a number that is at least 7 or higher");
number = sc.nextInt();
}
}
while (number < 7);
sc.nextLine();
String str;
for (int i = 0; i < number; i++) {
System.out.println("Type a word");
str = sc.nextLine();
count++;
if((countTest(str))){
condition++;
}
}
if(count == 0){
System.out.println("No words typed");
} else {
System.out.println("Total number of words typed: " + count + ", which fulfill the condition: "+ condition);
}
}
public static boolean countTest(String str) {
return Character.isUpperCase(str.charAt(0)) && str.charAt(str.length() - 1) >= 48 || str.charAt(str.length() - 1) <= 57 || str.contains("cse");
}
}```

Keep Reversing the no. & adding it to the original no. until there is a Palindrome Number

It's not "Find the Palindrome of a Number" ! it's a bit twisted than that:
Step 1: Reverse the digits of a original number.
Step 2: Add the reversed number.
Step 3: If the new number is a palindrome number then print the output.
The limit is 15 steps & we can print the original number if that is a palindrome in itself. We have to use function calling in this program. Here I have used two functions() - FIRST to reverse the number & SECOND to add the original number and the reversed number & check if the sum is a Palindrome or not.
Please suggest your opinions if I can improve this long code in any way.
PS: newbie in Java & especially function calling!
Thank you!! Here's the code, it's a little bit long! I am sorry :(
import java.util.*;
public class PalindromicNumber
{
public int PalinReverse(int n)
{
int n1=n;
int x1=0, d1=0;
while (n1>0)//just used to store the reverse of the original number
{
d1=n1%10;
x1=(x1*10)+d1;
n1=n1/10;
}
return x1;
}
public int PalinCheck (int n, int p)
{
int F=0;
F=n+p;
int n1=F, x1=0, d1=0;
while(n1>0)//checks if the sum of reversed no. and the original number is palindrome or not
{
d1=n1%10;
x1=(x1*10)+d1;
n1=n1/10;
}
if (x1==F)
{
System.out.println("The number"+ F +"is a Palindrome");
return 1;
}
else
return F; //returns the sum if it is not a palindrome
}
public static void main (String args[])
{
Scanner sc=new Scanner(System.in);
PalindromicNumber ob=new PalindromicNumber();
System.out.println("Enter the original number");
int n=sc.nextInt();
int count=0;
int n1=n, x1=0, d1=0;
while(n1>0) //this checks if the original no. is a palindrome or not
{
d1=n1%10;
x1=(x1*10)+d1;
n1=n1/10;
}
if (x1==n)
System.out.println("The original number="+n+"is a palindrome number");
else
for (count=0;count<15;count++)
{
int a=ob.PalinReverse(n);
System.out.println("The reversed number is"+a);
int b=ob.PalinCheck(n,a);
if(b==1)
{
System.out.println("The no. of steps it took was"count+1);
break;// the palindromic no. is now found out
}
else
n=b;//used to update the value of n
}
}
}
The problem is in your PalinReverse method. Your while loop is running infinitely because the condition is always true.
Replace
while (n>0)
with
while (n1>0)
You should also learn how to debug a program. Your life will be 10 times easy after that.

How do I count too see how many numbers and letters are in a user inputted string?

I have been asked to write an application that prompts the user for a String that contains at least five letters and at least five digits. Continuously reprompt the user until a valid String is entered. Display a message indicating whether the user was successful or did not enter enough digits, letters, or both.
I am a beginner programmer and I need help figuring out how too make this application work correctly. My issue is I am unable to figure out how to make my program interpret the letters and numbers from user input. Here is what I have so far:
public static void main(String[] args) {
// Declare variables.
String message;
int numLetters = 0;
int numDigits = 0;
boolean letters = false;
boolean digits = false;
// Input.
Scanner input = new Scanner(System.in);
System.out.println("Type a message with 5 letters and 5 digits: ");
message = input.nextLine();
// Loop through string.
The dark art of regular expressions can crush this problem with just one method call:
public static boolean check(String input) {
return input.matches("(?i)(?=(.*?[a-z]){5})(?=(.*?\\d){5}).*");
}
Breakdown:
the matches() method accepts a regex that must match the whole string to return true
the basic matching regex is .*, which matches everything
(?i) means "ignore case"
[a-z] is a character class as means "any lowercase letter"
.*?[a-z] means "0-n chars (but the smallest number possible) then a letter"
(.*?[a-z]){5} means "5 copies of the above"
(?=(.*?[a-z]){5}) is a "look ahead", which asserts, but does not consume the input (so you can fire another one) and means "there must be at least 5 letters in the input"
(?=(.*?\\d){5}) is similar, but asserts there are at least 5 numbers
Create a method to check if it has 5 letters and 5 digits:
public boolean check(String input){
int numDigits = 0;
int numLetters = 0;
for(int i=0; i<input.length();i++){
if(Character.isLetter(input.charAt(i))) numLetters++;
if(Character.isDigit(input.charAt(i))) numDigits++;
}
return (numDigits >= 5) && (numLetters >= 5);
}
Then you can add this method to a while loop:
while(!check(message)){
// get the input again and assign it to message
}
HA!!!! I GOT IT... For all you kids out there that need an answer to REFERENCE, check this out! Since everyone likes to dance around giving a good answer here is copy and paste code that will work. (Please dont hand it in as your own, but check out how this PITA code works!
//Date: 5/31/2015
//Subject: Mod 4, pg 389, Question 3
//Purpose:User is to input 5 digits and 5 letters. It will re prompt user until at least 5 digits and 5 letters are typed in.
import java.util.Scanner;
public class FiveLettersAndFiveDigits
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int numDigits = 0;
int numLetters = 0;
String message;
System.out.println("Please enter a 5 letter word and 5 digits.");
message = keyboard.nextLine();
while(numLetters < 5 &&numDigits <5)
{
for(int i=0; i < message.length();i++)
if(Character.isLetter(message.charAt(i))) ++numDigits;
for(int j=0; j < message.length();j++)
if(Character.isDigit(message.charAt(j))) ++numLetters;
if(numLetters >= 5 && numDigits >= 5)
{
System.out.println("You have " +numDigits+ " numbers and " +numLetters+ " letters, great job.");
}
else
{
System.out.println("You have typed in "+numDigits+" letters and "+numLetters+" numbers. Please try again.");
System.out.println("Please enter a 5 letter word and 5 digits.");
message = keyboard.nextLine();
continue;
}
}
System.out.println("This problem was no fun, hahaha. Took me like 3 hours!");
}
}
And that is that folks! Thank your lucky stars you had a reference online that was straight forward! hahaha Nothing sucks more than looking for some kind of direction and all you get is half #$$3D hints. Feel free to check out how this works.

string index out of range: 7 error

Hello I'm writing a code that asks the user for a tweet then tells the user if the tweet is the correct length and how many #'s #'s and links that are in it but everytime I run this I get the error string index out or range: 7. Any ideas?
import java.util.Scanner;
import java.lang.Math;
class Main {
public static void main(String[] args)
{
Scanner scan = new Scanner (System.in);
System.out.println ("Please enter a tweet: ");
String tweet = scan.nextLine();
int hashtags = 0;
int attributions = 0;
int links = 0;
if (tweet.length() > 140) {
int excess = tweet.length()-140;
System.out.println ("Excess Characters: " + excess);
} else {
System.out.println ("Length Correct.");
while (tweet.length() <= 140) {
if (tweet.charAt(0) == '#'){
hashtags ++;
}
if (tweet.charAt(0) == '#'){
attributions ++;
}
if (tweet.substring(0,8) == "http://") {
links ++;
}
tweet = tweet.substring(1);
}
System.out.println ("Number of Hashtags: " + hashtags);
System.out.println ("Number of Attributions: " + attributions);
System.out.println ("Number of Links: " + links);
}
}
}
Two problems, at least. The first is that you should not use substring on a string that's too short. It's far better to use String.startsWith:
if (tweet.startsWith("http://")) ...
so that you don't have to even worry about the length of the string, or getting your character count wrong, or having it fail because you used == rather than String.equals() :-)
Secondly, regarding the following code:
while (tweet.length() <= 140) {
:
tweet = tweet.substring(1);
}
That's going to keep going once your string is empty, simply because zero (and every negative number for that matter) is less than 140.
And, of course, doing something like tweet.charAt(0) on an empty string is going to give you a bit of a problem, similar to your use of substring. You need to re-examine your terminating condition for the loop, making it something like:
while (tweet.length() > 0) {
The first problem is that you're trying to get an 8-length substring of the tweet string without knowing how long the tweet is. What if the tweet is only 6 characters? If it is, you get an index out of bounds exception because you're looking two indices past where the array ends.
You should add a conditional guard:
if (tweet.length() >= 8 && tweet.substring(0,8).equals("http://")) {
links++;
}
The && operator means that tweet.substring() will never be checked if the length of the string is less than 8, so you avoid stepping out of bounds.
The second problem is that, even once you add that condtional guard, what you're doing doesn't make any sense. The length of the string returned by substring(beginIndex, endIndex) is equal to endIndex - beginIndex, or 8 in this case. The string "http://" is only seven letters, so it's logically impossible for an 8-character string to ever equal it. Use the startsWith() function instead of substring from the 0 position:
The line from before should look like so:
if (tweet.startsWith("http://")) {
links++;
}
You should definitely use a for loop instead:
String string= "hello";
for (int i = 0; i < string.length(); ++i)
{
if (string.charAt( i ) == '#')
{
//do something
}
}
That will insure that you traverse the entire string correctly.
Secondly, you need to make sure that the substring(0, 8) is inbounds before you assume. That is probably what's causing your error in some test cases.

Password w/ Specific Requirements Program

I'm currently doing an assignment for my Java programming class.
The question in the book asks for the user to create a program that uses the JOptionPane boxes to ask the user for a password. The password has to be between 6 and 10 characters, and have at least one digit, and one letter. Once this requirement is met, ask the user to verify their password. If their second input doesn't match the first, ask the original question again. Once both inputs match, display a message saying "success!".
I've gotten mine to the point where it checks for the number of characters, but I can't for the life of me, figure out how to check for digits and letters also. I've tried nested for loops that search for digits and letters, but I can't figure out a way to make it bypass the length requirement when it doesn't have a number or letter. This is my current code.
import javax.swing.JOptionPane;
class Password{
public static void main(String[] args){
String input1 = "";
String input2 = "";
int inputLength;
do{
do{
input1 = JOptionPane.showInputDialog(null, "Enter your password\nIt must be 6 to 10 characters and\nhave at least one digit and one letter");
inputLength = input1.length();
}while(inputLength < 6 || inputLength > 10);
input2 = JOptionPane.showInputDialog(null, "Verify Password");
}while(!(input1.equals(input2)));
JOptionPane.showMessageDialog(null, "Success!");
}
}
You can deal with regular expression.
(?=.*\d) mean at last one digit in the word
(?=.*[a-zA-Z]) mean at least one letter
{6,10} mean between 6 and 10 characters
So the correct regex is ((?=.\d)(?=.[a-zA-Z]).{6,10})
Now look at the `.matches(String regex) method of String :)
If you can't use regex :
Get the CharArray (input1.toCharArray()) and iterate.
For each char, check if it's a number or a character
Keep 2 boolean (for exemple num and alpha) and set them to true when you see a number of a character
Then, look at you flag, and then test this
num && alpha && inputLenght > 6 && inputLenght < 10
Edit:
You can use Character.isLetter() and Character.isDigit(), i think you have enough informations now !
Figured it out! I ended up adding two while loops to check for digits and letters inside of the inner do loop. I set the while loops to make the boolean expressions false if the correct thing is found (I know, it seems backwards). But it makes it so the do loop will not run again if the correct characters are found. Thank you to everyone that posted, it really helped clear things up!
Here's the completed code:
import javax.swing.JOptionPane;
class Password{
public static void main(String[] args){
String input1 = "";
String input2 = "";
int inputLength;
boolean isDigit = true;
boolean isLetter = true;
char c = ' ';
char d = ' ';
int x = 0;
do{
do{
input1 = JOptionPane.showInputDialog(null, "Enter your password\nIt must be 6 to 10 characters and\nhave at least one digit and one letter");
inputLength = input1.length();
while(x < input1.length()){
c = input1.charAt(x);
if(Character.isDigit(c)){
isDigit = false;
break;
}
x++;
}
x = 0;
while(x < input1.length()){
d = input1.charAt(x);
if(Character.isLetter(d)){
isLetter = false;
break;
}
x++;
}
}while(inputLength < 6 || inputLength > 10 || isDigit || isLetter);
input2 = JOptionPane.showInputDialog(null, "Verify Password");
}while(!(input1.equals(input2)));
JOptionPane.showMessageDialog(null, "Success!");
}
}

Categories

Resources