Palindromes: in this program i have to try and figure out if the user input is a palindrome or not - palindrome

When ever i execute the program the output says not a palindrome when it is a palindrome(only does this when input has spaces or punctuation) can some one tell me where i went wrong in my code?
public class Palindromes
{
public static void main(String[]args)
{
ConsoleIO keyboard=new ConsoleIO();
String word, word2="",terminate;
int length;
do
{
System.out.print("Enter a string:");
word=keyboard.readLine();
word=word.toLowerCase();
word=word.trim();
word=word.replaceAll("\\W", "");
word=word.replaceAll(" ","");
length=word.length();
//finding the reverse of the string
for(int i=length-1;i>=0;i--)
{
word2+=word.charAt(i);
}
//checking to see if the string is a palindrome
if(word.length()==1)
{
System.out.println("The string you entered is not a palindrome");
}
else if(word.equals(word2))
{
System.out.println("The string you entered is a palindrome.");
}
else
{
System.out.println("The string you entered is not a palindrome.");
}
System.out.print("Do you want to continue (yes or no):");
terminate=keyboard.readLine();
System.out.println();
}
while(terminate.equalsIgnoreCase("yes"));
}
}

I think you'd need to account for the punctuation because that will affect the plaindrome test you have. ra.cecar is not otherwise a palindrome. Have you tried adding more lines like the following?
word=word.replaceAll(".", "");
word=word.replaceAll("?", "");
word=word.replaceAll("!", "");
word=word.replaceAll("-", "");

To end all problem to Palindrome, I've made this Java program that will end all suffering to it. It's in Java so you're in luck. It basically strip every non-word character, put it to lower case just with 13 lines. Hope this help haha! Let's hope other guys would get lucky to find this too.
import java.util.Scanner;
public class Palindrome {
public static void main(String[]args){
if(isReverse()){System.out.println("This is a palindrome.");}
else{System.out.print("This is not a palindrome");}
}
public static boolean isReverse(){
Scanner keyboard = new Scanner(System.in);
System.out.print("Please type something: ");
String line = ((keyboard.nextLine()).toLowerCase()).replaceAll("\\W","");
return (line.equals(new StringBuffer(line).reverse().toString()));
}
}

Related

Most proper way to throw exception as validation for reactive stream

I have a reactive stream that I would like one step of which to apply a validation check, that if failed, will throw an exception. Is there a commonly accepted style to do that with? From what I can tell I have three options (using Mono) in then(), filter(), and map().
filter() is closest to the flow I want, in that I'm not actually trying to change the type of data in the stream or switch to another stream. But, filter is supposed to return true/false to filter out items, so it's a little goofy to always return TRUE.
then() lets me specifically choose error/success emissions, but sometimes for this type of validation I am not able to easily split it off into it's own private method and the boilerplate makes the stream declaration messier to read.
map() is pretty much the same as using filter(), except you always return in the input instead of TRUE.
As a very contrived example, consider a service that has a list of 0 or more letters to send to a person:
public interface Person {
UUID getId();
List<String> getKnownLanguages();
}
public interface Letter {
String getLanguage();
}
public class LetterService {
private Letter findOneLetterForPerson(final UUID id) { /* ... */ }
private void removeLetter(final Letter letter) { /* ... */ }
}
What is the better option for creating a method that looks like this:
public Mono<Optional<Letter>> getNextValidLetterForPerson(final Person person) {
return Mono.just(person)
.and(this::getNextLetterForPerson)
/////////////////////////////////////////
//
.filter(this::validatePersonCanReadLetter1)
.map(Tuple2::getT2)
//
// OR
//
.then(this::validatePersonCanReadLetter2)
//
// OR
//
.map(this::validatePersonCanReadLetter3)
//
/////////////////////////////////////////
// If the letter was invalid for the person, remove the letter from the
// the system as a side effect, and retry retrieving a letter to send
.doOnError(this::removeInvalidLetter)
.retry(this::ifLetterValidationFailed)
// Map the result to an appropriate Optional
.map(Optional::of)
.defaultIfEmpty(Optional.empty());
}
The supporting methods used in the example above are:
public static class LetterInvalidException extends RuntimeException {
private Letter mLetter;
public LetterInvalidException(final Letter letter) { mLetter = letter; }
public Letter getLetter() { return mLetter; }
}
/** Gets the next letter for a person, as a reactive stream */
private Mono<Letter> getNextLetterForPerson(final Person person) {
return Mono.create(emitter -> {
final Letter letter = mLetterService.findOneLetterForPerson(person.getId());
if (letter != null) {
emitter.success(letter);
}
else {
emitter.success();
}
});
}
/** Used to check whether the cause of an error was due to an invalid letter */
private boolean ifLetterValidationFailed(final Throwable e) {
return e instanceof LetterInvalidException;
}
/** Used to remove an invalid letter from the system */
private void removeInvalidLetter(final Throwable e) {
if (ifLetterValidationFailed(e)) {
mLetterService.removeLetter(((LetterInvalidException)e).getLetter());
}
}
/*************************************************************************
*
*************************************************************************/
private boolean validatePersonCanReadLetter1(final Tuple2<Person, Letter> tuple) {
final Person person = tuple.getT1();
final Letter letter = tuple.getT2();
if (!person.getKnownLanguages().contains(letter.getLanguage())) {
throw new LetterInvalidException(letter);
}
return true;
}
private Mono<Letter> validatePersonCanReadLetter2(final Tuple2<Person, Letter> tuple) {
return Mono.create(emitter -> {
final Person person = tuple.getT1();
final Letter letter = tuple.getT2();
if (!person.getKnownLanguages().contains(letter.getLanguage())) {
emitter.error(new LetterInvalidException(letter));
}
else {
emitter.success(letter);
}
});
}
private Letter validatePersonCanReadLetter3(final Tuple2<Person, Letter> tuple) {
final Person person = tuple.getT1();
final Letter letter = tuple.getT2();
if (!person.getKnownLanguages().contains(letter.getLanguage())) {
throw new LetterInvalidException(letter);
}
return letter;
}
Ideally I would loved a method such as Mono<T> validate(..) that would allow testing the stream item and either returning or throwing an exception (if returned, the framework would treat that as an error), but I'm rather new to reactive programming and didn't see anything that worked like that.
Maybe handle is a better solution it can serve as a combination of map and filter:
Mono.just(p).and(test::getNextLetterForPerson).handle((tuple, sink) -> {
final Person person = tuple.getT1();
final Letter letter = tuple.getT2();
if (!person.getKnownLanguages().contains(letter.getLanguage())) {
sink.error(new LetterInvalidException(letter));
return;
}
sink.next(letter);
}).subscribe(value -> System.out.println(((Letter) value).getLanguage()),
t -> System.out.println(t.getMessage()));
As you can see it's almost like your validatePersonCanReadLetter3

using a method to resolve a chess tile colour

I have been looking for a while but people seem to be waaaaay ahead of me on on the chess front. All i want to do is have a method in a class to resolve the colour of a tile but my colour keeps coming up as "null".
import java.util.Scanner;
public class ChessTileTest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String tileColour;
chessTile test = new chessTile();
System.out.print(" Enter chess move : ");
String move = in.next();
tileColour = test.setColour(move);
System.out.println(tileColour);
}
}
public class chessTile {
private String colour;
private String address;
public chessTile(){
}
public String setColour(String move){
char letter;
int number;
letter = move.charAt(0);
number = move.charAt(1);
if((letter=='a'||letter=='c'||letter=='e'||letter=='g')&&(number/2==1)){
colour = "Black";
}
else if((letter=='a'||letter=='c'||letter=='e'||letter=='g')&&(number/2==0)){
colour = "white";
}
else if((letter=='b'||letter=='d'||letter=='f'||letter=='h')&&(number/2==1)){
colour = "white";
}
else if((letter=='b'||letter=='d'||letter=='f'||letter=='h')&&(number/2==0)){
colour = "Black";
}
return colour;
}
}
First lines of setColour(...) are
char letter = move.charAt(0); // gets ASCII character at index 0
int number = move.charAt(1); // gets **int value of** ASCII character at index 1
So, for exmaple, if your string is "a1", then letter = a but number = 49 because the integer ASCII value of the character "1" is 49. See this ASCII chart for more . . . http://www.asciitable.com/index/asciifull.gif
You will need to convert the character into a proper int. You can do that with the following . . .
int number = Character.getNumericValue( move.charAt(1) );
Since you are probably getting a bad value, none of the if-statements are satisfied and a null value is returned

How to do this Card class in java?

so basically for my computer science class we have to create a Card class which takes user input for the card notation (for example "4S") and has a getDescription method which returns the description of the card ("four of spades"). the problem is, i keep getting an "unreachable statement" error in regards to the if statement. I probably did the whole thing wrong but here is what i did:
import java.util.Scanner;
public class Card
{
private String face;
private String suit;
public Card()
{
Scanner card = new Scanner(System.in);
System.out.print("Enter the card notation: ");
String input = card.next();
face = input.substring(0,1);
suit = input.substring(1);
}
public String getDescription()
{
return "Your card was the ";
if (face.equals("A")) return "ace";
return getDescription();
}
}
Any code placed after a return statement is unreachable, because the return statement tells a method to exit and go back to wherever it was called from with the information provided. Thus they should go at the end of methods, once you've fully prepared the information you want to send back. Something like
public String getDescription() {
String s = "Your card was the ";
if (face.equals("A")) {
s += "ace";
};
return s;
}

How to get down to StringLiterals with Eclipse AST?

I need to create an Eclipse plugin that displays a tooltip when I hover the mouse over a String literal.
But only if that String literal is the first parameter of a special method.
Here is the Test.java file I use to test my plugin:
package test;
public class Test {
public static void main(String[] args) {
String hello = "Hello";
String world = Translator.get("Test.worldLabel");
System.out.println(hello + " " + world);
}
}
I created a class implementing IJavaEditorTextHover and I need to compile the currently edited Java file to compute if the cursor is hovering a String that needs to be translated or not.
Hovering "Hello" will do nothing.
Hovering "Test.worldLabel" will display my tooltip because that literal is included inside a Translator.get() method call.
At first I used this (170 is inside "Test.worldLabel"):
ITypeRoot typeRoot = (ITypeRoot)
JavaUI.getEditorInputJavaElement(editorPart.getEditorInput());
JavaElement foundElement = (JavaElement) typeRoot.getElementAt(170);
But the foundElement contains the whole main() method: it is not fine-grained enough.
Then, the correct way is, I think:
private static ASTNode parse(ICompilationUnit unit, int position) {
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(unit);
parser.setResolveBindings(true);
parser.setIgnoreMethodBodies(false);
// TODO Future optimisation: parser.setFocalPosition(position);
return parser.createAST((IProgressMonitor) null); // parse
}
And in my IJavaEditorTextHover.getHoverInfo(...) implementation:
ICompilationUnit compilationUnit = (ICompilationUnit)
JavaUI.getEditorInputJavaElement(editor.getEditorInput())
int position = 170/*hoverRegion.getOffset()*/;
ASTNode ast = parse(compilationUnit, position);
And now, here is my question:
How, from this ast node, do I get the ASTNode reprensenting the StringLiteral at position 170 in the source code (the "Test.worldLabel" String)?
Bonus question: did I choose the right solution? On a performance basis.
Edit:
Well, here is a solution I found:
private StringLiteral findStringLiteralAtPosition(final ASTNode parent, final int position) {
final List<StringLiteral> stringLiterals = new ArrayList<StringLiteral>();
parent.accept(new ASTVisitor() {
#Override
public boolean visit(StringLiteral stringLiteral) {
int start = stringLiteral.getStartPosition();
int end = start + stringLiteral.getLength();
if (start <= position && position <= end) {
stringLiterals.add(stringLiteral);
}
return super.visit(stringLiteral);
}
});
return (stringLiterals.size() > 0 ? stringLiterals.get(0) : null);
}
Does it seam OK?
Or is it an easier way or a more performant one?
One solution will be not using the offset logic at all.
You can generalise the solution by using a node parent check.
Here is a sample code:
public boolean visit(StringLiteral stringLiteral) {
// Check if parent is a method inovacation.
if (stringLiteral.getParent().getNodeType() == ASTNode.METHOD_INVOCATION) {
// get the parent method inovacation.
MethodInvocation miNode = (MethodInvocation) stringLiteral.getParent();
//To do: null and empty check on argument list.
// Check if is the special method and this is the 1st argument
if (miNode.getName().toString().equals("SpecialMethod")
&& miNode.arguments().get(0).toString().equals(stringLiteral.toString())) {
System.out.println("Found it : " + stringLiteral.toString());
}
}
return true;
}

XText: first and last character truncated in custom STRING terminals

I have redefined the STRING terminal this way
terminal STRING : ('.'|'+'|'('|')'|'a'..'z'|'A'..'Z'|'_'|'0'..'9')*;
because I have to recognize STRING not delimited by " or '
the problem is that, though the generated parser works, it truncates the first and the last character of the recognized string. What am I missing?
If you customize the STRING rule, you'll have to adapt the respective value converter, too.
Something like this has to be bound in your runtime module:
public class MyStringValueConverter extends STRINGValueConverter {
#Override
protected String toEscapedString(String value) {
return value;
}
public String toValue(String string, INode node) {
if (string == null)
return null;
return string;
}
}
See the docs for details.